text
stringlengths
54
60.6k
<commit_before>/* * opencog/atoms/base/Atom.cc * * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * Written by Thiago Maia <[email protected]> * Andre Senna <[email protected]> * Welter Silva <[email protected]> * * 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 <set> #include <sstream> #ifndef WIN32 #include <unistd.h> #endif #include <opencog/util/misc.h> #include <opencog/util/platform.h> #include <opencog/atoms/base/Atom.h> #include <opencog/atoms/base/ClassServer.h> #include <opencog/atoms/base/Link.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/AtomTable.h> //! Atom flag #define FETCHED_RECENTLY 1 //BIT0 #define MARKED_FOR_REMOVAL 2 //BIT1 // #define MULTIPLE_TRUTH_VALUES 4 //BIT2 // #define FIRED_ACTIVATION 8 //BIT3 // #define HYPOTETHICAL_FLAG 16 //BIT4 // #define REMOVED_BY_DECAY 32 //BIT5 #define CHECKED 64 //BIT6 //#define DPRINTF printf #define DPRINTF(...) #undef Type namespace opencog { Atom::~Atom() { _atomTable = NULL; if (0 < getIncomingSetSize()) { // This can't ever possibly happen. If it does, then there is // some very sick bug with the reference counting that the // shared pointers are doing. (Or someone explcitly called the // destructor! Which they shouldn't do.) OC_ASSERT(0 == getIncomingSet().size(), "Atom deletion failure; incoming set not empty for %s h=%x", classserver().getTypeName(_type).c_str(), get_hash()); } drop_incoming_set(); } // ============================================================== // Return the atomspace in which this atom is inserted. AtomSpace* Atom::getAtomSpace() const { if (_atomTable) return _atomTable->getAtomSpace(); return nullptr; } // ============================================================== // Whole lotta truthiness going on here. Does it really need to be // this complicated!? void Atom::setTruthValue(TruthValuePtr newTV) { if (nullptr == newTV) return; // We need to guarantee that the signal goes out with the // correct truth value. That is, another setter could be changing // this, even as we are. So make a copy, first. TruthValuePtr oldTV(getTruthValue()); // ... and we still need to make sure that only one thread is // writing this at a time. std:shared_ptr is NOT thread-safe against // multiple writers: see "Example 5" in // http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety std::unique_lock<std::mutex> lck(_mtx); _truthValue = newTV; lck.unlock(); if (_atomTable != NULL) { TVCHSigl& tvch = _atomTable->TVChangedSignal(); tvch(getHandle(), oldTV, newTV); } } TruthValuePtr Atom::getTruthValue() const { // OK. The atomic thread-safety of shared-pointers is subtle. See // http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety // and http://cppwisdom.quora.com/shared_ptr-is-almost-thread-safe // What it boils down to here is that we must *always* make a copy // of _truthValue before we use it, since it can go out of scope // because it can get set in another thread. Viz, using it to // dereference can return a raw pointer to an object that has been // deconstructed. The AtomSpaceAsyncUTest will hit this, as will // the multi-threaded async atom store in the SQL peristance backend. // Furthermore, we must make a copy while holding the lock! Got that? std::lock_guard<std::mutex> lck(_mtx); TruthValuePtr local(_truthValue); return local; #if THIS_WONT_WORK_AS_NICELY_AS_YOU_MIGHT_GUESS // This automatic fetching of TV's from the database seems OK, but // gets really nasty, really quick. One problem is that getTV is // used everywhere -- printing atoms, you name it, and so gets hit // a lot. Another, more subtle, problem is that the current Atom // ctors accept a TV argument, and so cause the TV to be fetched // during the ctor. This has multiple undeseriable side-effects: // one is that for UnorderredLinks, a badly-ordered version of the // link is inserted into the TLB, before the ctor has finished // sorting the outgoing set! A third issue is that the backend // itself calls this method, when saving the TV! So that's just // kind-of crazy. These are all difficult technical problems to // solve, so the code below, although initially appealing, doesn't // really do the right thing. if (_flags & FETCHED_RECENTLY) return local; if (nullptr == _atomTable) return local; // XXX The only time that as is null is in BasicSaveUTest // In all other cases, it will never be null. AtomSpace* as = _atomTable->getAtomSpace(); if (nullptr == as) return local; BackingStore* bs = as->_backing_store; if (nullptr == bs) return local; TruthValuePtr tv; if (isNode()) { tv = bs->getNode(getType(), getName().c_str()); } else { Atom* that = (Atom*) this; // cast away constness tv = bs->getLink(that->getHandle()); } if (tv) { _flags = _flags | FETCHED_RECENTLY; _truthValue = tv; return tv; } return local; #endif } void Atom::merge(TruthValuePtr tvn, const MergeCtrl& mc) { if (nullptr == tvn or tvn->isDefaultTV()) return; // No locking to be done here. It is possible that between the time // that we read the TV here (i.e. set currentTV) and the time that // we look to see if currentTV is default, that some other thread // will have changed _truthValue. This is a race, but we don't care, // because if two threads are trying to simultaneously set the TV on // one atom, without co-operating with one-another, they get what // they deserve -- a race. (We still use getTruthValue() to avoid a // read-write race on the shared_pointer itself!) TruthValuePtr currentTV(getTruthValue()); if (currentTV->isDefaultTV()) { setTruthValue(tvn); return; } TruthValuePtr mergedTV(currentTV->merge(tvn, mc)); setTruthValue(mergedTV); } // ============================================================== // Flag stuff bool Atom::isMarkedForRemoval() const { return (_flags & MARKED_FOR_REMOVAL) != 0; } void Atom::unsetRemovalFlag(void) { _flags &= ~MARKED_FOR_REMOVAL; } void Atom::markForRemoval(void) { _flags |= MARKED_FOR_REMOVAL; } bool Atom::isChecked() const { return (_flags & CHECKED) != 0; } void Atom::setChecked(void) { _flags |= CHECKED; } void Atom::setUnchecked(void) { _flags &= ~CHECKED; } // ============================================================== void Atom::setAtomTable(AtomTable *tb) { if (tb == _atomTable) return; // Either the existing _atomTable is null, and tb is not, i.e. this // atom is being inserted into tb, or _atomTable is not null, while // tb is null, i.e. atom is being removed from _atomTable. It is // illegal to just switch membership: one or the other of these two // pointers must be null. OC_ASSERT (NULL == _atomTable or tb == NULL, "Atom table is not null!"); _atomTable = tb; } // ============================================================== // Incoming set stuff /// Start tracking the incoming set for this atom. /// An atom can't know what it's incoming set is, until this method /// is called. If this atom is added to any links before this call /// is made, those links won't show up in the incoming set. /// /// We don't automatically track incoming sets for two reasons: /// 1) std::set takes up 48 bytes /// 2) adding and remoiving uses up cpu cycles. /// Thus, if the incoming set isn't needed, then don't bother /// tracking it. void Atom::keep_incoming_set() { if (_incoming_set) return; _incoming_set = std::make_shared<InSet>(); } /// Stop tracking the incoming set for this atom. /// After this call, the incoming set for this atom can no longer /// be queried; it is erased. void Atom::drop_incoming_set() { if (NULL == _incoming_set) return; std::lock_guard<std::mutex> lck (_mtx); _incoming_set->_iset.clear(); // delete _incoming_set; _incoming_set = NULL; } /// Add an atom to the incoming set. void Atom::insert_atom(const LinkPtr& a) { if (NULL == _incoming_set) return; std::lock_guard<std::mutex> lck (_mtx); _incoming_set->_iset.insert(a); #ifdef INCOMING_SET_SIGNALS _incoming_set->_addAtomSignal(shared_from_this(), a); #endif /* INCOMING_SET_SIGNALS */ } /// Remove an atom from the incoming set. void Atom::remove_atom(const LinkPtr& a) { if (NULL == _incoming_set) return; std::lock_guard<std::mutex> lck (_mtx); #ifdef INCOMING_SET_SIGNALS _incoming_set->_removeAtomSignal(shared_from_this(), a); #endif /* INCOMING_SET_SIGNALS */ _incoming_set->_iset.erase(a); } /// Remove old, and add new, atomically, so that every user /// will see either one or the other, but not both/neither in /// the incoming set. This is used to manage the StateLink. void Atom::swap_atom(const LinkPtr& old, const LinkPtr& neu) { if (NULL == _incoming_set) return; std::lock_guard<std::mutex> lck (_mtx); #ifdef INCOMING_SET_SIGNALS _incoming_set->_removeAtomSignal(shared_from_this(), old); #endif /* INCOMING_SET_SIGNALS */ _incoming_set->_iset.erase(old); _incoming_set->_iset.insert(neu); #ifdef INCOMING_SET_SIGNALS _incoming_set->_addAtomSignal(shared_from_this(), neu); #endif /* INCOMING_SET_SIGNALS */ } size_t Atom::getIncomingSetSize() const { if (NULL == _incoming_set) return 0; std::lock_guard<std::mutex> lck (_mtx); return _incoming_set->_iset.size(); } // We return a copy here, and not a reference, because the set itself // is not thread-safe during reading while simultaneous insertion and // deletion. Besides, the incoming set is weak; we have to make it // strong in order to hand it out. IncomingSet Atom::getIncomingSet(AtomSpace* as) { static IncomingSet empty_set; if (NULL == _incoming_set) return empty_set; if (as) { const AtomTable *atab = &as->get_atomtable(); // Prevent update of set while a copy is being made. std::lock_guard<std::mutex> lck (_mtx); IncomingSet iset; for (WinkPtr w : _incoming_set->_iset) { LinkPtr l(w.lock()); if (l and atab->in_environ(l)) iset.emplace_back(l); } return iset; } // Prevent update of set while a copy is being made. std::lock_guard<std::mutex> lck (_mtx); IncomingSet iset; for (WinkPtr w : _incoming_set->_iset) { LinkPtr l(w.lock()); if (l) iset.emplace_back(l); } return iset; } IncomingSet Atom::getIncomingSetByType(Type type, bool subclass) { HandleSeq inhs; getIncomingSetByType(std::back_inserter(inhs), type, subclass); IncomingSet inlinks; for (const Handle& h : inhs) inlinks.emplace_back(LinkCast(h)); return inlinks; } std::string oc_to_string(const IncomingSet& iset) { std::stringstream ss; ss << "size = " << iset.size() << std::endl; for (unsigned i = 0; i < iset.size(); i++) ss << "link[" << i << "]:" << std::endl << iset[i]->toString(); return ss.str(); } } // ~namespace opencog <commit_msg>Huh. Use another const refernce for this.<commit_after>/* * opencog/atoms/base/Atom.cc * * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * Written by Thiago Maia <[email protected]> * Andre Senna <[email protected]> * Welter Silva <[email protected]> * * 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 <set> #include <sstream> #ifndef WIN32 #include <unistd.h> #endif #include <opencog/util/misc.h> #include <opencog/util/platform.h> #include <opencog/atoms/base/Atom.h> #include <opencog/atoms/base/ClassServer.h> #include <opencog/atoms/base/Link.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/AtomTable.h> //! Atom flag #define FETCHED_RECENTLY 1 //BIT0 #define MARKED_FOR_REMOVAL 2 //BIT1 // #define MULTIPLE_TRUTH_VALUES 4 //BIT2 // #define FIRED_ACTIVATION 8 //BIT3 // #define HYPOTETHICAL_FLAG 16 //BIT4 // #define REMOVED_BY_DECAY 32 //BIT5 #define CHECKED 64 //BIT6 //#define DPRINTF printf #define DPRINTF(...) #undef Type namespace opencog { Atom::~Atom() { _atomTable = NULL; if (0 < getIncomingSetSize()) { // This can't ever possibly happen. If it does, then there is // some very sick bug with the reference counting that the // shared pointers are doing. (Or someone explcitly called the // destructor! Which they shouldn't do.) OC_ASSERT(0 == getIncomingSet().size(), "Atom deletion failure; incoming set not empty for %s h=%x", classserver().getTypeName(_type).c_str(), get_hash()); } drop_incoming_set(); } // ============================================================== // Return the atomspace in which this atom is inserted. AtomSpace* Atom::getAtomSpace() const { if (_atomTable) return _atomTable->getAtomSpace(); return nullptr; } // ============================================================== // Whole lotta truthiness going on here. Does it really need to be // this complicated!? void Atom::setTruthValue(TruthValuePtr newTV) { if (nullptr == newTV) return; // We need to guarantee that the signal goes out with the // correct truth value. That is, another setter could be changing // this, even as we are. So make a copy, first. TruthValuePtr oldTV(getTruthValue()); // ... and we still need to make sure that only one thread is // writing this at a time. std:shared_ptr is NOT thread-safe against // multiple writers: see "Example 5" in // http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety std::unique_lock<std::mutex> lck(_mtx); _truthValue = newTV; lck.unlock(); if (_atomTable != NULL) { TVCHSigl& tvch = _atomTable->TVChangedSignal(); tvch(getHandle(), oldTV, newTV); } } TruthValuePtr Atom::getTruthValue() const { // OK. The atomic thread-safety of shared-pointers is subtle. See // http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety // and http://cppwisdom.quora.com/shared_ptr-is-almost-thread-safe // What it boils down to here is that we must *always* make a copy // of _truthValue before we use it, since it can go out of scope // because it can get set in another thread. Viz, using it to // dereference can return a raw pointer to an object that has been // deconstructed. The AtomSpaceAsyncUTest will hit this, as will // the multi-threaded async atom store in the SQL peristance backend. // Furthermore, we must make a copy while holding the lock! Got that? std::lock_guard<std::mutex> lck(_mtx); TruthValuePtr local(_truthValue); return local; #if THIS_WONT_WORK_AS_NICELY_AS_YOU_MIGHT_GUESS // This automatic fetching of TV's from the database seems OK, but // gets really nasty, really quick. One problem is that getTV is // used everywhere -- printing atoms, you name it, and so gets hit // a lot. Another, more subtle, problem is that the current Atom // ctors accept a TV argument, and so cause the TV to be fetched // during the ctor. This has multiple undeseriable side-effects: // one is that for UnorderredLinks, a badly-ordered version of the // link is inserted into the TLB, before the ctor has finished // sorting the outgoing set! A third issue is that the backend // itself calls this method, when saving the TV! So that's just // kind-of crazy. These are all difficult technical problems to // solve, so the code below, although initially appealing, doesn't // really do the right thing. if (_flags & FETCHED_RECENTLY) return local; if (nullptr == _atomTable) return local; // XXX The only time that as is null is in BasicSaveUTest // In all other cases, it will never be null. AtomSpace* as = _atomTable->getAtomSpace(); if (nullptr == as) return local; BackingStore* bs = as->_backing_store; if (nullptr == bs) return local; TruthValuePtr tv; if (isNode()) { tv = bs->getNode(getType(), getName().c_str()); } else { Atom* that = (Atom*) this; // cast away constness tv = bs->getLink(that->getHandle()); } if (tv) { _flags = _flags | FETCHED_RECENTLY; _truthValue = tv; return tv; } return local; #endif } void Atom::merge(TruthValuePtr tvn, const MergeCtrl& mc) { if (nullptr == tvn or tvn->isDefaultTV()) return; // No locking to be done here. It is possible that between the time // that we read the TV here (i.e. set currentTV) and the time that // we look to see if currentTV is default, that some other thread // will have changed _truthValue. This is a race, but we don't care, // because if two threads are trying to simultaneously set the TV on // one atom, without co-operating with one-another, they get what // they deserve -- a race. (We still use getTruthValue() to avoid a // read-write race on the shared_pointer itself!) TruthValuePtr currentTV(getTruthValue()); if (currentTV->isDefaultTV()) { setTruthValue(tvn); return; } TruthValuePtr mergedTV(currentTV->merge(tvn, mc)); setTruthValue(mergedTV); } // ============================================================== // Flag stuff bool Atom::isMarkedForRemoval() const { return (_flags & MARKED_FOR_REMOVAL) != 0; } void Atom::unsetRemovalFlag(void) { _flags &= ~MARKED_FOR_REMOVAL; } void Atom::markForRemoval(void) { _flags |= MARKED_FOR_REMOVAL; } bool Atom::isChecked() const { return (_flags & CHECKED) != 0; } void Atom::setChecked(void) { _flags |= CHECKED; } void Atom::setUnchecked(void) { _flags &= ~CHECKED; } // ============================================================== void Atom::setAtomTable(AtomTable *tb) { if (tb == _atomTable) return; // Either the existing _atomTable is null, and tb is not, i.e. this // atom is being inserted into tb, or _atomTable is not null, while // tb is null, i.e. atom is being removed from _atomTable. It is // illegal to just switch membership: one or the other of these two // pointers must be null. OC_ASSERT (NULL == _atomTable or tb == NULL, "Atom table is not null!"); _atomTable = tb; } // ============================================================== // Incoming set stuff /// Start tracking the incoming set for this atom. /// An atom can't know what it's incoming set is, until this method /// is called. If this atom is added to any links before this call /// is made, those links won't show up in the incoming set. /// /// We don't automatically track incoming sets for two reasons: /// 1) std::set takes up 48 bytes /// 2) adding and remoiving uses up cpu cycles. /// Thus, if the incoming set isn't needed, then don't bother /// tracking it. void Atom::keep_incoming_set() { if (_incoming_set) return; _incoming_set = std::make_shared<InSet>(); } /// Stop tracking the incoming set for this atom. /// After this call, the incoming set for this atom can no longer /// be queried; it is erased. void Atom::drop_incoming_set() { if (NULL == _incoming_set) return; std::lock_guard<std::mutex> lck (_mtx); _incoming_set->_iset.clear(); // delete _incoming_set; _incoming_set = NULL; } /// Add an atom to the incoming set. void Atom::insert_atom(const LinkPtr& a) { if (NULL == _incoming_set) return; std::lock_guard<std::mutex> lck (_mtx); _incoming_set->_iset.insert(a); #ifdef INCOMING_SET_SIGNALS _incoming_set->_addAtomSignal(shared_from_this(), a); #endif /* INCOMING_SET_SIGNALS */ } /// Remove an atom from the incoming set. void Atom::remove_atom(const LinkPtr& a) { if (NULL == _incoming_set) return; std::lock_guard<std::mutex> lck (_mtx); #ifdef INCOMING_SET_SIGNALS _incoming_set->_removeAtomSignal(shared_from_this(), a); #endif /* INCOMING_SET_SIGNALS */ _incoming_set->_iset.erase(a); } /// Remove old, and add new, atomically, so that every user /// will see either one or the other, but not both/neither in /// the incoming set. This is used to manage the StateLink. void Atom::swap_atom(const LinkPtr& old, const LinkPtr& neu) { if (NULL == _incoming_set) return; std::lock_guard<std::mutex> lck (_mtx); #ifdef INCOMING_SET_SIGNALS _incoming_set->_removeAtomSignal(shared_from_this(), old); #endif /* INCOMING_SET_SIGNALS */ _incoming_set->_iset.erase(old); _incoming_set->_iset.insert(neu); #ifdef INCOMING_SET_SIGNALS _incoming_set->_addAtomSignal(shared_from_this(), neu); #endif /* INCOMING_SET_SIGNALS */ } size_t Atom::getIncomingSetSize() const { if (NULL == _incoming_set) return 0; std::lock_guard<std::mutex> lck (_mtx); return _incoming_set->_iset.size(); } // We return a copy here, and not a reference, because the set itself // is not thread-safe during reading while simultaneous insertion and // deletion. Besides, the incoming set is weak; we have to make it // strong in order to hand it out. IncomingSet Atom::getIncomingSet(AtomSpace* as) { static IncomingSet empty_set; if (NULL == _incoming_set) return empty_set; if (as) { const AtomTable *atab = &as->get_atomtable(); // Prevent update of set while a copy is being made. std::lock_guard<std::mutex> lck (_mtx); IncomingSet iset; for (const WinkPtr& w : _incoming_set->_iset) { LinkPtr l(w.lock()); if (l and atab->in_environ(l)) iset.emplace_back(l); } return iset; } // Prevent update of set while a copy is being made. std::lock_guard<std::mutex> lck (_mtx); IncomingSet iset; for (WinkPtr w : _incoming_set->_iset) { LinkPtr l(w.lock()); if (l) iset.emplace_back(l); } return iset; } IncomingSet Atom::getIncomingSetByType(Type type, bool subclass) { HandleSeq inhs; getIncomingSetByType(std::back_inserter(inhs), type, subclass); IncomingSet inlinks; for (const Handle& h : inhs) inlinks.emplace_back(LinkCast(h)); return inlinks; } std::string oc_to_string(const IncomingSet& iset) { std::stringstream ss; ss << "size = " << iset.size() << std::endl; for (unsigned i = 0; i < iset.size(); i++) ss << "link[" << i << "]:" << std::endl << iset[i]->toString(); return ss.str(); } } // ~namespace opencog <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX64M DMAC サンプル @n ・P07(176) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @n @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/sci_io.hpp" #include "common/cmt_io.hpp" #include "common/fixed_fifo.hpp" #include "common/format.hpp" #include "common/delay.hpp" #include "common/command.hpp" #include "common/dmac_man.hpp" namespace { typedef device::PORT<device::PORT0, device::bitpos::B7> LED; typedef device::cmt_io<device::CMT0> CMT; CMT cmt_; typedef utils::fixed_fifo<char, 128> BUFFER; typedef device::sci_io<device::SCI1, BUFFER, BUFFER> SCI; SCI sci_; utils::command<256> cmd_; /// DMAC 終了割り込み class dmac_task { uint32_t count_; public: dmac_task() : count_(0) { } void operator() () { ++count_; } uint32_t get_count() const { return count_; } }; typedef device::dmac_man<device::DMAC0, dmac_task> DMAC_MAN; DMAC_MAN dmac_man_; char tmp_[256]; } extern "C" { void sci_putch(char ch) { sci_.putch(ch); } char sci_getch(void) { return sci_.getch(); } void sci_puts(const char *str) { sci_.puts(str); } uint16_t sci_length(void) { return sci_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { device::system_io<12000000>::setup_system_clock(); { // タイマー設定(60Hz) uint8_t int_level = 4; cmt_.start(60, int_level); } { // SCI 設定 uint8_t int_level = 2; sci_.start(115200, int_level); } utils::format("RX64M DMAC sample start\n"); cmd_.set_prompt("# "); LED::DIR = 1; { uint8_t intr_level = 4; dmac_man_.start(intr_level); } // copy 機能の確認 std::memset(tmp_, 0, sizeof(tmp_)); std::strcpy(tmp_, "ASDFGHJKLQWERTYUZXCVBNMIOP"); uint32_t copy_len = 16; dmac_man_.copy(&tmp_[0], &tmp_[128], copy_len); utils::format("DMA Copy: %d\n") % copy_len; while(dmac_man_.probe()) ; utils::format("ORG(%d): '%s'\n") % std::strlen(tmp_) % tmp_; utils::format("CPY(%d): '%s'\n") % std::strlen(&tmp_[128]) % &tmp_[128]; utils::format("DMAC task: %d\n") % dmac_man_.at_task().get_count(); uint32_t cnt = 0; while(1) { cmt_.sync(); if(cmd_.service()) { } ++cnt; if(cnt >= 30) { cnt = 0; } LED::P = (cnt < 10) ? 0 : 1; } } <commit_msg>update: cleanup<commit_after>//=====================================================================// /*! @file @brief RX64M DMAC サンプル @n ・P07(176) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @n @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/renesas.hpp" #include "common/sci_io.hpp" #include "common/cmt_io.hpp" #include "common/fixed_fifo.hpp" #include "common/format.hpp" #include "common/delay.hpp" #include "common/command.hpp" namespace { typedef device::PORT<device::PORT0, device::bitpos::B7> LED; typedef device::cmt_io<device::CMT0> CMT; CMT cmt_; typedef utils::fixed_fifo<char, 128> BUFFER; typedef device::sci_io<device::SCI1, BUFFER, BUFFER> SCI; SCI sci_; utils::command<256> cmd_; /// DMAC 終了割り込み class dmac_task { uint32_t count_; public: dmac_task() : count_(0) { } void operator() () { ++count_; } uint32_t get_count() const { return count_; } }; typedef device::dmac_mgr<device::DMAC0, dmac_task> DMAC_MGR; DMAC_MGR dmac_mgr_; char tmp_[256]; } extern "C" { void sci_putch(char ch) { sci_.putch(ch); } char sci_getch(void) { return sci_.getch(); } void sci_puts(const char *str) { sci_.puts(str); } uint16_t sci_length(void) { return sci_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { device::system_io<12000000>::setup_system_clock(); { // タイマー設定(60Hz) uint8_t int_level = 4; cmt_.start(60, int_level); } { // SCI 設定 uint8_t int_level = 2; sci_.start(115200, int_level); } utils::format("RX64M DMAC sample start\n"); cmd_.set_prompt("# "); LED::DIR = 1; { uint8_t intr_level = 4; dmac_mgr_.start(intr_level); } // copy 機能の確認 std::memset(tmp_, 0, sizeof(tmp_)); std::strcpy(tmp_, "ASDFGHJKLQWERTYUZXCVBNMIOP"); uint32_t copy_len = 16; dmac_mgr_.copy(&tmp_[0], &tmp_[128], copy_len, true); utils::format("DMA Copy: %d\n") % copy_len; while(dmac_mgr_.probe()) ; utils::format("ORG(%d): '%s'\n") % std::strlen(tmp_) % tmp_; utils::format("CPY(%d): '%s'\n") % std::strlen(&tmp_[128]) % &tmp_[128]; utils::format("DMAC task: %d\n") % dmac_mgr_.at_task().get_count(); dmac_mgr_.fill(&tmp_[0], 4, copy_len, true); utils::format("DMA fill: %d\n") % copy_len; while(dmac_mgr_.probe()) ; utils::format("ORG(%d): '%s'\n") % std::strlen(tmp_) % tmp_; utils::format("DMAC task: %d\n") % dmac_mgr_.at_task().get_count(); uint8_t val = 'Z'; copy_len = 31; dmac_mgr_.memset(&tmp_[0], val, copy_len, true); utils::format("DMA memset: %d\n") % copy_len; while(dmac_mgr_.probe()) ; utils::format("ORG(%d): '%s'\n") % std::strlen(tmp_) % tmp_; utils::format("DMAC task: %d\n") % dmac_mgr_.at_task().get_count(); uint32_t cnt = 0; while(1) { cmt_.sync(); if(cmd_.service()) { } ++cnt; if(cnt >= 30) { cnt = 0; } LED::P = (cnt < 10) ? 0 : 1; } } <|endoftext|>
<commit_before>// Copyright 2018 Ulf Adams // // The contents of this file may be used under the terms of the Apache License, // Version 2.0. // // (See accompanying file LICENSE-Apache or copy at // http://www.apache.org/licenses/LICENSE-2.0) // // Alternatively, the contents of this file may be used under the terms of // the Boost Software License, Version 1.0. // (See accompanying file LICENSE-Boost or copy at // https://www.boost.org/LICENSE_1_0.txt) // // Unless required by applicable law or agreed to in writing, this software // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. #include <math.h> #include <inttypes.h> #include <iostream> #include <string.h> #include <chrono> #include <random> #include <stdint.h> #include <stdio.h> #if defined(__linux__) #include <sys/types.h> #include <unistd.h> #endif #include "ryu/ryu.h" #include "third_party/double-conversion/double-conversion/utils.h" #include "third_party/double-conversion/double-conversion/double-conversion.h" using double_conversion::StringBuilder; using double_conversion::DoubleToStringConverter; using namespace std::chrono; constexpr int BUFFER_SIZE = 40; static char buffer[BUFFER_SIZE]; static DoubleToStringConverter converter( DoubleToStringConverter::Flags::EMIT_TRAILING_DECIMAL_POINT | DoubleToStringConverter::Flags::EMIT_TRAILING_ZERO_AFTER_POINT, "Infinity", "NaN", 'E', 7, 7, 0, 0); static StringBuilder builder(buffer, BUFFER_SIZE); void fcv(float value) { builder.Reset(); converter.ToShortestSingle(value, &builder); builder.Finalize(); } void dcv(double value) { builder.Reset(); converter.ToShortest(value, &builder); builder.Finalize(); } static float int32Bits2Float(uint32_t bits) { float f; memcpy(&f, &bits, sizeof(float)); return f; } static double int64Bits2Double(uint64_t bits) { double f; memcpy(&f, &bits, sizeof(double)); return f; } struct mean_and_variance { int64_t n = 0; double mean = 0; double m2 = 0; void update(double x) { ++n; double d = x - mean; mean += d / n; double d2 = x - mean; m2 += d * d2; } double variance() const { return m2 / (n - 1); } double stddev() const { return sqrt(variance()); } }; static int bench32(int samples, int iterations, bool verbose, bool ryu_only, bool invert) { char bufferown[BUFFER_SIZE]; std::mt19937 mt32(12345); mean_and_variance mv1; mean_and_variance mv2; int throwaway = 0; if (!invert) { for (int i = 0; i < samples; ++i) { uint32_t r = mt32(); float f = int32Bits2Float(r); auto t1 = steady_clock::now(); for (int j = 0; j < iterations; ++j) { f2s_buffered(f, bufferown); throwaway += bufferown[2]; } auto t2 = steady_clock::now(); double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations); mv1.update(delta1); t1 = steady_clock::now(); if (!ryu_only) { for (int j = 0; j < iterations; ++j) { fcv(f); throwaway += buffer[2]; } } t2 = steady_clock::now(); double delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations); mv2.update(delta2); if (verbose) { printf("%u,%lf,%lf\n", r, delta1, delta2); } if (!ryu_only && strcmp(bufferown, buffer) != 0) { printf("For %x %20s %20s\n", r, bufferown, buffer); } } } else { std::vector<float> vec(samples); for (int i = 0; i < samples; ++i) { uint32_t r = mt32(); float f = int32Bits2Float(r); vec[i] = f; } for (int j = 0; j < iterations; ++j) { auto t1 = steady_clock::now(); for (int i = 0; i < samples; ++i) { f2s_buffered(vec[i], bufferown); throwaway += bufferown[2]; } auto t2 = steady_clock::now(); double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples); mv1.update(delta1); t1 = steady_clock::now(); if (!ryu_only) { for (int i = 0; i < samples; ++i) { fcv(vec[i]); throwaway += buffer[2]; } } t2 = steady_clock::now(); double delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples); mv2.update(delta2); if (verbose) { printf("N/A,%lf,%lf\n", delta1, delta2); } } } if (!verbose) { printf("32: %8.3f %8.3f %8.3f %8.3f\n", mv1.mean, mv1.stddev(), mv2.mean, mv2.stddev()); } return throwaway; } static int bench64(int samples, int iterations, bool verbose, bool ryu_only, bool invert) { char bufferown[BUFFER_SIZE]; std::mt19937 mt32(12345); mean_and_variance mv1; mean_and_variance mv2; int throwaway = 0; if (!invert) { for (int i = 0; i < samples; ++i) { uint64_t r = mt32(); r <<= 32; r |= mt32(); // calling mt32() in separate statements guarantees order of evaluation double f = int64Bits2Double(r); auto t1 = steady_clock::now(); for (int j = 0; j < iterations; ++j) { d2s_buffered(f, bufferown); throwaway += bufferown[2]; } auto t2 = steady_clock::now(); double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations); mv1.update(delta1); t1 = steady_clock::now(); if (!ryu_only) { for (int j = 0; j < iterations; ++j) { dcv(f); throwaway += buffer[2]; } } t2 = steady_clock::now(); double delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations); mv2.update(delta2); if (verbose) { printf("%" PRIu64 ",%lf,%lf\n", r, delta1, delta2); } if (!ryu_only && strcmp(bufferown, buffer) != 0) { printf("For %16" PRIX64 " %28s %28s\n", r, bufferown, buffer); } } } else { std::vector<double> vec(samples); for (int i = 0; i < samples; ++i) { uint64_t r = mt32(); r <<= 32; r |= mt32(); // calling mt32() in separate statements guarantees order of evaluation double f = int64Bits2Double(r); vec[i] = f; } for (int j = 0; j < iterations; ++j) { auto t1 = steady_clock::now(); for (int i = 0; i < samples; ++i) { d2s_buffered(vec[i], bufferown); throwaway += bufferown[2]; } auto t2 = steady_clock::now(); double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples); mv1.update(delta1); t1 = steady_clock::now(); if (!ryu_only) { for (int i = 0; i < samples; ++i) { dcv(vec[i]); throwaway += buffer[2]; } } t2 = steady_clock::now(); double delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples); mv2.update(delta2); if (verbose) { printf("N/A,%lf,%lf\n", delta1, delta2); } } } if (!verbose) { printf("64: %8.3f %8.3f %8.3f %8.3f\n", mv1.mean, mv1.stddev(), mv2.mean, mv2.stddev()); } return throwaway; } int main(int argc, char** argv) { #if defined(__linux__) // Also disable hyperthreading with something like this: // cat /sys/devices/system/cpu/cpu*/topology/core_id // sudo /bin/bash -c "echo 0 > /sys/devices/system/cpu/cpu6/online" cpu_set_t my_set; CPU_ZERO(&my_set); CPU_SET(2, &my_set); sched_setaffinity(getpid(), sizeof(cpu_set_t), &my_set); #endif // By default, run both 32 and 64-bit benchmarks with 10000 samples and 1000 iterations each. bool run32 = true; bool run64 = true; int samples = 10000; int iterations = 1000; bool verbose = false; bool ryu_only = false; bool invert = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-32") == 0) { run32 = true; run64 = false; } else if (strcmp(argv[i], "-64") == 0) { run32 = false; run64 = true; } else if (strcmp(argv[i], "-v") == 0) { verbose = true; } else if (strcmp(argv[i], "-ryu") == 0) { ryu_only = true; } else if (strcmp(argv[i], "-invert") == 0) { invert = true; } else if (strncmp(argv[i], "-samples=", 9) == 0) { sscanf(argv[i], "-samples=%i", &samples); } else if (strncmp(argv[i], "-iterations=", 12) == 0) { sscanf(argv[i], "-iterations=%i", &iterations); } } if (!verbose) { // No need to buffer the output if we're just going to print three lines. setbuf(stdout, NULL); } if (verbose) { printf("float_bits_as_int,ryu_time_in_ns,grisu3_time_in_ns\n"); } else { printf(" Average & Stddev Ryu Average & Stddev Grisu3\n"); } int throwaway = 0; if (run32) { throwaway += bench32(samples, iterations, verbose, ryu_only, invert); } if (run64) { throwaway += bench64(samples, iterations, verbose, ryu_only, invert); } if (argc == 1000) { // Prevent the compiler from optimizing the code away. printf("%d\n", throwaway); } return 0; } <commit_msg>benchmark.cc: Improve "-ryu" and "-invert" output.<commit_after>// Copyright 2018 Ulf Adams // // The contents of this file may be used under the terms of the Apache License, // Version 2.0. // // (See accompanying file LICENSE-Apache or copy at // http://www.apache.org/licenses/LICENSE-2.0) // // Alternatively, the contents of this file may be used under the terms of // the Boost Software License, Version 1.0. // (See accompanying file LICENSE-Boost or copy at // https://www.boost.org/LICENSE_1_0.txt) // // Unless required by applicable law or agreed to in writing, this software // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. #include <math.h> #include <inttypes.h> #include <iostream> #include <string.h> #include <chrono> #include <random> #include <stdint.h> #include <stdio.h> #if defined(__linux__) #include <sys/types.h> #include <unistd.h> #endif #include "ryu/ryu.h" #include "third_party/double-conversion/double-conversion/utils.h" #include "third_party/double-conversion/double-conversion/double-conversion.h" using double_conversion::StringBuilder; using double_conversion::DoubleToStringConverter; using namespace std::chrono; constexpr int BUFFER_SIZE = 40; static char buffer[BUFFER_SIZE]; static DoubleToStringConverter converter( DoubleToStringConverter::Flags::EMIT_TRAILING_DECIMAL_POINT | DoubleToStringConverter::Flags::EMIT_TRAILING_ZERO_AFTER_POINT, "Infinity", "NaN", 'E', 7, 7, 0, 0); static StringBuilder builder(buffer, BUFFER_SIZE); void fcv(float value) { builder.Reset(); converter.ToShortestSingle(value, &builder); builder.Finalize(); } void dcv(double value) { builder.Reset(); converter.ToShortest(value, &builder); builder.Finalize(); } static float int32Bits2Float(uint32_t bits) { float f; memcpy(&f, &bits, sizeof(float)); return f; } static double int64Bits2Double(uint64_t bits) { double f; memcpy(&f, &bits, sizeof(double)); return f; } struct mean_and_variance { int64_t n = 0; double mean = 0; double m2 = 0; void update(double x) { ++n; double d = x - mean; mean += d / n; double d2 = x - mean; m2 += d * d2; } double variance() const { return m2 / (n - 1); } double stddev() const { return sqrt(variance()); } }; static int bench32(int samples, int iterations, bool verbose, bool ryu_only, bool invert) { char bufferown[BUFFER_SIZE]; std::mt19937 mt32(12345); mean_and_variance mv1; mean_and_variance mv2; int throwaway = 0; if (!invert) { for (int i = 0; i < samples; ++i) { uint32_t r = mt32(); float f = int32Bits2Float(r); auto t1 = steady_clock::now(); for (int j = 0; j < iterations; ++j) { f2s_buffered(f, bufferown); throwaway += bufferown[2]; } auto t2 = steady_clock::now(); double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations); mv1.update(delta1); double delta2 = 0.0; if (!ryu_only) { t1 = steady_clock::now(); for (int j = 0; j < iterations; ++j) { fcv(f); throwaway += buffer[2]; } t2 = steady_clock::now(); delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations); mv2.update(delta2); } if (verbose) { if (ryu_only) { printf("%u,%lf\n", r, delta1); } else { printf("%u,%lf,%lf\n", r, delta1, delta2); } } if (!ryu_only && strcmp(bufferown, buffer) != 0) { printf("For %x %20s %20s\n", r, bufferown, buffer); } } } else { std::vector<float> vec(samples); for (int i = 0; i < samples; ++i) { uint32_t r = mt32(); float f = int32Bits2Float(r); vec[i] = f; } for (int j = 0; j < iterations; ++j) { auto t1 = steady_clock::now(); for (int i = 0; i < samples; ++i) { f2s_buffered(vec[i], bufferown); throwaway += bufferown[2]; } auto t2 = steady_clock::now(); double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples); mv1.update(delta1); double delta2 = 0.0; if (!ryu_only) { t1 = steady_clock::now(); for (int i = 0; i < samples; ++i) { fcv(vec[i]); throwaway += buffer[2]; } t2 = steady_clock::now(); delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples); mv2.update(delta2); } if (verbose) { if (ryu_only) { printf("%lf\n", delta1); } else { printf("%lf,%lf\n", delta1, delta2); } } } } if (!verbose) { printf("32: %8.3f %8.3f", mv1.mean, mv1.stddev()); if (!ryu_only) { printf(" %8.3f %8.3f", mv2.mean, mv2.stddev()); } printf("\n"); } return throwaway; } static int bench64(int samples, int iterations, bool verbose, bool ryu_only, bool invert) { char bufferown[BUFFER_SIZE]; std::mt19937 mt32(12345); mean_and_variance mv1; mean_and_variance mv2; int throwaway = 0; if (!invert) { for (int i = 0; i < samples; ++i) { uint64_t r = mt32(); r <<= 32; r |= mt32(); // calling mt32() in separate statements guarantees order of evaluation double f = int64Bits2Double(r); auto t1 = steady_clock::now(); for (int j = 0; j < iterations; ++j) { d2s_buffered(f, bufferown); throwaway += bufferown[2]; } auto t2 = steady_clock::now(); double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations); mv1.update(delta1); double delta2 = 0.0; if (!ryu_only) { t1 = steady_clock::now(); for (int j = 0; j < iterations; ++j) { dcv(f); throwaway += buffer[2]; } t2 = steady_clock::now(); delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(iterations); mv2.update(delta2); } if (verbose) { if (ryu_only) { printf("%" PRIu64 ",%lf\n", r, delta1); } else { printf("%" PRIu64 ",%lf,%lf\n", r, delta1, delta2); } } if (!ryu_only && strcmp(bufferown, buffer) != 0) { printf("For %16" PRIX64 " %28s %28s\n", r, bufferown, buffer); } } } else { std::vector<double> vec(samples); for (int i = 0; i < samples; ++i) { uint64_t r = mt32(); r <<= 32; r |= mt32(); // calling mt32() in separate statements guarantees order of evaluation double f = int64Bits2Double(r); vec[i] = f; } for (int j = 0; j < iterations; ++j) { auto t1 = steady_clock::now(); for (int i = 0; i < samples; ++i) { d2s_buffered(vec[i], bufferown); throwaway += bufferown[2]; } auto t2 = steady_clock::now(); double delta1 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples); mv1.update(delta1); double delta2 = 0.0; if (!ryu_only) { t1 = steady_clock::now(); for (int i = 0; i < samples; ++i) { dcv(vec[i]); throwaway += buffer[2]; } t2 = steady_clock::now(); delta2 = duration_cast<nanoseconds>(t2 - t1).count() / static_cast<double>(samples); mv2.update(delta2); } if (verbose) { if (ryu_only) { printf("%lf\n", delta1); } else { printf("%lf,%lf\n", delta1, delta2); } } } } if (!verbose) { printf("64: %8.3f %8.3f", mv1.mean, mv1.stddev()); if (!ryu_only) { printf(" %8.3f %8.3f", mv2.mean, mv2.stddev()); } printf("\n"); } return throwaway; } int main(int argc, char** argv) { #if defined(__linux__) // Also disable hyperthreading with something like this: // cat /sys/devices/system/cpu/cpu*/topology/core_id // sudo /bin/bash -c "echo 0 > /sys/devices/system/cpu/cpu6/online" cpu_set_t my_set; CPU_ZERO(&my_set); CPU_SET(2, &my_set); sched_setaffinity(getpid(), sizeof(cpu_set_t), &my_set); #endif // By default, run both 32 and 64-bit benchmarks with 10000 samples and 1000 iterations each. bool run32 = true; bool run64 = true; int samples = 10000; int iterations = 1000; bool verbose = false; bool ryu_only = false; bool invert = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-32") == 0) { run32 = true; run64 = false; } else if (strcmp(argv[i], "-64") == 0) { run32 = false; run64 = true; } else if (strcmp(argv[i], "-v") == 0) { verbose = true; } else if (strcmp(argv[i], "-ryu") == 0) { ryu_only = true; } else if (strcmp(argv[i], "-invert") == 0) { invert = true; } else if (strncmp(argv[i], "-samples=", 9) == 0) { sscanf(argv[i], "-samples=%i", &samples); } else if (strncmp(argv[i], "-iterations=", 12) == 0) { sscanf(argv[i], "-iterations=%i", &iterations); } } if (!verbose) { // No need to buffer the output if we're just going to print three lines. setbuf(stdout, NULL); } if (verbose) { printf("%sryu_time_in_ns%s\n", invert ? "" : "float_bits_as_int,", ryu_only ? "" : ",grisu3_time_in_ns"); } else { printf(" Average & Stddev Ryu%s\n", ryu_only ? "" : " Average & Stddev Grisu3"); } int throwaway = 0; if (run32) { throwaway += bench32(samples, iterations, verbose, ryu_only, invert); } if (run64) { throwaway += bench64(samples, iterations, verbose, ryu_only, invert); } if (argc == 1000) { // Prevent the compiler from optimizing the code away. printf("%d\n", throwaway); } return 0; } <|endoftext|>
<commit_before>#include <Engine/Renderer/RenderTechnique/ShaderProgram.hpp> #include <Core/Utils/StringUtils.hpp> #include <globjects/base/File.h> #include <globjects/base/StaticStringSource.h> #include <globjects/NamedString.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <globjects/Texture.h> #include <regex> #ifdef OS_WINDOWS # include <direct.h> # define getCurrentDir _getcwd #else # include <unistd.h> # define getCurrentDir getcwd #endif #include <Core/Math/GlmAdapters.hpp> #include <Core/Utils/Log.hpp> #include <Engine/Renderer/Texture/Texture.hpp> #include <numeric> // for std::accumulate namespace Ra { namespace Engine { using namespace Core::Utils; // log ShaderProgram::ShaderProgram() : m_program{nullptr} { std::fill( m_shaderObjects.begin(), m_shaderObjects.end(), nullptr ); std::fill( m_shaderSources.begin(), m_shaderSources.end(), nullptr ); } ShaderProgram::ShaderProgram( const ShaderConfiguration& config ) : m_program{nullptr} { std::fill( m_shaderObjects.begin(), m_shaderObjects.end(), nullptr ); std::fill( m_shaderSources.begin(), m_shaderSources.end(), nullptr ); load( config ); } ShaderProgram::~ShaderProgram() { // first delete shader objects (before program and source) since it refer to // them during delete // See ~Shader (setSource(nullptr) for ( auto& s : m_shaderObjects ) { s.reset( nullptr ); } for ( auto& s : m_shaderSources ) { s.reset( nullptr ); } m_program.reset( nullptr ); } void ShaderProgram::loadShader( ShaderType type, const std::string& name, const std::set<std::string>& props, const std::vector<std::pair<std::string, ShaderType>>& includes, const std::string& version ) { #ifdef OS_MACOS if ( type == ShaderType_COMPUTE ) { LOG( logERROR ) << "No compute shader on OsX !"; return; } #endif // Radium V2 --> for the moment : standard includepaths. Might be controlled per shader ... // Paths in which globjects will be looking for shaders includes. // "/" refer to the root of the directory structure conaining the shader (i.e. the Shaders/ // directory). auto loadedSource = globjects::Shader::sourceFromFile( name ); // header string that contains #version and pre-declarations ... std::string shaderHeader; if ( type == ShaderType_VERTEX ) { shaderHeader = std::string( version + "\n\n" "out gl_PerVertex {\n" " vec4 gl_Position;\n" " float gl_PointSize;\n" " float gl_ClipDistance[];\n" "};\n\n" ); } else { shaderHeader = std::string( version + "\n\n" ); } // Add properties at the beginning of the file. shaderHeader = std::accumulate( props.begin(), props.end(), shaderHeader, []( std::string a, const std::string& b ) { return std::move( a ) + b + std::string( "\n" ); } ); // Add includes, depending on the shader type. shaderHeader = std::accumulate( includes.begin(), includes.end(), shaderHeader, [type]( std::string a, const std::pair<std::string, ShaderType>& b ) -> std::string { if ( b.second == type ) { return std::move( a ) + b.first + std::string( "\n" ); } else { return a; } } ); auto fullsource = globjects::Shader::sourceFromString( shaderHeader + loadedSource->string() ); // Radium V2 : allow to define global replacement per renderer, shader, rendertechnique ... auto shaderSource = globjects::Shader::applyGlobalReplacements( fullsource.get() ); // Workaround globject #include bug ... // Radium V2 : update globject to see if tis bug is always here ... std::string preprocessedSource = preprocessIncludes( name, shaderSource->string(), 0 ); auto ptrSource = globjects::Shader::sourceFromString( preprocessedSource ); addShaderFromSource( type, std::move( ptrSource ) ); } void ShaderProgram::addShaderFromSource( ShaderType type, std::unique_ptr<globjects::StaticStringSource>&& ptrSource, const std::string& name ) { auto shader = globjects::Shader::create( getTypeAsGLEnum( type ) ); shader->setSource( ptrSource.get() ); shader->setName( name ); shader->compile(); GL_CHECK_ERROR; m_shaderObjects[type].swap( shader ); // raw ptrSource are stored in shader object, need to keep them valid during // shader life m_shaderSources[type].swap( ptrSource ); } GLenum ShaderProgram::getTypeAsGLEnum( ShaderType type ) const { switch ( type ) { case ShaderType_VERTEX: return GL_VERTEX_SHADER; case ShaderType_FRAGMENT: return GL_FRAGMENT_SHADER; case ShaderType_GEOMETRY: return GL_GEOMETRY_SHADER; case ShaderType_TESS_EVALUATION: return GL_TESS_EVALUATION_SHADER; case ShaderType_TESS_CONTROL: return GL_TESS_CONTROL_SHADER; #ifndef OS_MACOS // GL_COMPUTE_SHADER requires OpenGL >= 4.2, Apple provides OpenGL 4.1 case ShaderType_COMPUTE: return GL_COMPUTE_SHADER; #endif default: CORE_ERROR( "Wrong ShaderType" ); } // Should never get there return GL_ZERO; } ShaderType ShaderProgram::getGLenumAsType( GLenum type ) const { switch ( type ) { case GL_VERTEX_SHADER: return ShaderType_VERTEX; case GL_FRAGMENT_SHADER: return ShaderType_FRAGMENT; case GL_GEOMETRY_SHADER: return ShaderType_GEOMETRY; case GL_TESS_EVALUATION_SHADER: return ShaderType_TESS_EVALUATION; case GL_TESS_CONTROL_SHADER: return ShaderType_TESS_CONTROL; #ifndef OS_MACOS case GL_COMPUTE_SHADER: return ShaderType_COMPUTE; #endif default: CORE_ERROR( "Wrong GLenum" ); } // Should never get there return ShaderType_COUNT; } void ShaderProgram::load( const ShaderConfiguration& shaderConfig ) { m_configuration = shaderConfig; CORE_ERROR_IF( m_configuration.isComplete(), ( "Shader program " + shaderConfig.m_name + " misses vertex or fragment shader." ) .c_str() ); for ( size_t i = 0; i < ShaderType_COUNT; ++i ) { if ( !m_configuration.m_shaders[i].empty() ) { LOG( logDEBUG ) << "Loading shader " << m_configuration.m_shaders[i]; loadShader( ShaderType( i ), m_configuration.m_shaders[i], m_configuration.getProperties(), m_configuration.getIncludes(), m_configuration.m_version ); } } link(); } void ShaderProgram::link() { m_program = globjects::Program::create(); for ( int i = 0; i < ShaderType_COUNT; ++i ) { if ( m_shaderObjects[i] ) { m_program->attach( m_shaderObjects[i].get() ); } } m_program->setParameter( GL_PROGRAM_SEPARABLE, GL_TRUE ); m_program->link(); GL_CHECK_ERROR; int texUnit = 0; auto total = GLuint( m_program->get( GL_ACTIVE_UNIFORMS ) ); textureUnits.clear(); for ( GLuint i = 0; i < total; ++i ) { auto name = m_program->getActiveUniformName( i ); auto type = m_program->getActiveUniform( i, GL_UNIFORM_TYPE ); //!\todo add other sampler type (or manage all type of sampler automatically) if ( type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE || type == GL_SAMPLER_2D_RECT || type == GL_SAMPLER_2D_SHADOW || type == GL_SAMPLER_3D || type == GL_SAMPLER_CUBE_SHADOW ) { auto location = m_program->getUniformLocation( name ); textureUnits[name] = TextureBinding( texUnit++, location ); } } } void ShaderProgram::bind() const { m_program->use(); } void ShaderProgram::validate() const { m_program->validate(); if ( !m_program->isValid() ) { LOG( logDEBUG ) << m_program->infoLog(); } } void ShaderProgram::unbind() const { m_program->release(); } void ShaderProgram::reload() { for ( auto& s : m_shaderObjects ) { if ( s != nullptr ) { LOG( logDEBUG ) << "Reloading shader " << s->name(); m_program->detach( s.get() ); loadShader( getGLenumAsType( s->type() ), s->name(), m_configuration.getProperties(), m_configuration.getIncludes() ); } } link(); } ShaderConfiguration ShaderProgram::getBasicConfiguration() const { ShaderConfiguration basicConfig; basicConfig.m_shaders = m_configuration.m_shaders; basicConfig.m_name = m_configuration.m_name; return basicConfig; } void ShaderProgram::setUniform( const char* name, int value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, unsigned int value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, float value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, double value ) const { m_program->setUniform( name, static_cast<float>( value ) ); } //! void ShaderProgram::setUniform( const char* name, std::vector<int> values ) const { m_program->setUniform( name, values ); } void ShaderProgram::setUniform( const char* name, std::vector<unsigned int> values ) const { m_program->setUniform( name, values ); } void ShaderProgram::setUniform( const char* name, std::vector<float> values ) const { m_program->setUniform( name, values ); } //! void ShaderProgram::setUniform( const char* name, const Core::Vector2i& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector2f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector2d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Vector3i& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector3f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector3d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Vector4i& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector4f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector4d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix2f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix2d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix3f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix3d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix4f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix4d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, Texture* tex, int texUnit ) const { tex->bind( texUnit ); m_program->setUniform( name, texUnit ); } void ShaderProgram::setUniformTexture( const char* name, Texture* tex ) const { auto itr = textureUnits.find( std::string( name ) ); if ( itr != textureUnits.end() ) { tex->bind( itr->second.m_texUnit ); m_program->setUniform( itr->second.m_location, itr->second.m_texUnit ); } } globjects::Program* ShaderProgram::getProgramObject() const { return m_program.get(); } /**************************************************** * Include workaround due to globject bugs ****************************************************/ std::string ShaderProgram::preprocessIncludes( const std::string& name, const std::string& shader, int level, int line ) { CORE_ERROR_IF( level < 32, "Shader inclusion depth limit reached." ); std::string result{}; std::vector<std::string> finalStrings; uint nline = 0; static const std::regex reg( "^[ ]*#[ ]*include[ ]+[\"<](.*)[\">].*" ); // source: https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/ std::istringstream iss( shader ); std::string codeline; while ( std::getline( iss, codeline, '\n' ) ) { std::smatch match; if ( std::regex_search( codeline, match, reg ) ) { // Radium V2 : for composable shaders, use the includePaths set elsewhere. auto includeNameString = globjects::NamedString::getFromRegistry( std::string( "/" ) + match[1].str() ); if ( includeNameString != nullptr ) { codeline = preprocessIncludes( match[1].str(), includeNameString->string(), level + 1, 0 ); } else { LOG( logWARNING ) << "Cannot open included file " << match[1].str() << " at line" << nline << " of file " << name << ". Ignored."; continue; } // Radium V2, adapt this if globjct includes bug is still present /* std::string inc; std::string file = m_filepath + match[1].str(); if (parseFile(file, inc)) { sublerr.start = nline; sublerr.name = file; lerr.subfiles.push_back(sublerr); line = preprocessIncludes(inc, level + 1, lerr.subfiles.back()); nline = lerr.subfiles.back().end; } else { LOG(logWARNING) << "Cannot open included file " << file << " from " << m_filename << ". Ignored."; continue; } */ } finalStrings.push_back( codeline ); ++nline; } // Build final shader string for ( const auto& l : finalStrings ) { result.append( l ); result.append( "\n" ); } result.append( "\0" ); return result; } } // namespace Engine } // namespace Ra <commit_msg>Fix missing filename when creating a shader.<commit_after>#include <Engine/Renderer/RenderTechnique/ShaderProgram.hpp> #include <Core/Utils/StringUtils.hpp> #include <globjects/base/File.h> #include <globjects/base/StaticStringSource.h> #include <globjects/NamedString.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <globjects/Texture.h> #include <regex> #ifdef OS_WINDOWS # include <direct.h> # define getCurrentDir _getcwd #else # include <unistd.h> # define getCurrentDir getcwd #endif #include <Core/Math/GlmAdapters.hpp> #include <Core/Utils/Log.hpp> #include <Engine/Renderer/Texture/Texture.hpp> #include <numeric> // for std::accumulate namespace Ra { namespace Engine { using namespace Core::Utils; // log ShaderProgram::ShaderProgram() : m_program{nullptr} { std::fill( m_shaderObjects.begin(), m_shaderObjects.end(), nullptr ); std::fill( m_shaderSources.begin(), m_shaderSources.end(), nullptr ); } ShaderProgram::ShaderProgram( const ShaderConfiguration& config ) : m_program{nullptr} { std::fill( m_shaderObjects.begin(), m_shaderObjects.end(), nullptr ); std::fill( m_shaderSources.begin(), m_shaderSources.end(), nullptr ); load( config ); } ShaderProgram::~ShaderProgram() { // first delete shader objects (before program and source) since it refer to // them during delete // See ~Shader (setSource(nullptr) for ( auto& s : m_shaderObjects ) { s.reset( nullptr ); } for ( auto& s : m_shaderSources ) { s.reset( nullptr ); } m_program.reset( nullptr ); } void ShaderProgram::loadShader( ShaderType type, const std::string& name, const std::set<std::string>& props, const std::vector<std::pair<std::string, ShaderType>>& includes, const std::string& version ) { #ifdef OS_MACOS if ( type == ShaderType_COMPUTE ) { LOG( logERROR ) << "No compute shader on OsX !"; return; } #endif // Radium V2 --> for the moment : standard includepaths. Might be controlled per shader ... // Paths in which globjects will be looking for shaders includes. // "/" refer to the root of the directory structure conaining the shader (i.e. the Shaders/ // directory). auto loadedSource = globjects::Shader::sourceFromFile( name ); // header string that contains #version and pre-declarations ... std::string shaderHeader; if ( type == ShaderType_VERTEX ) { shaderHeader = std::string( version + "\n\n" "out gl_PerVertex {\n" " vec4 gl_Position;\n" " float gl_PointSize;\n" " float gl_ClipDistance[];\n" "};\n\n" ); } else { shaderHeader = std::string( version + "\n\n" ); } // Add properties at the beginning of the file. shaderHeader = std::accumulate( props.begin(), props.end(), shaderHeader, []( std::string a, const std::string& b ) { return std::move( a ) + b + std::string( "\n" ); } ); // Add includes, depending on the shader type. shaderHeader = std::accumulate( includes.begin(), includes.end(), shaderHeader, [type]( std::string a, const std::pair<std::string, ShaderType>& b ) -> std::string { if ( b.second == type ) { return std::move( a ) + b.first + std::string( "\n" ); } else { return a; } } ); auto fullsource = globjects::Shader::sourceFromString( shaderHeader + loadedSource->string() ); // Radium V2 : allow to define global replacement per renderer, shader, rendertechnique ... auto shaderSource = globjects::Shader::applyGlobalReplacements( fullsource.get() ); // Workaround globject #include bug ... // Radium V2 : update globject to see if tis bug is always here ... std::string preprocessedSource = preprocessIncludes( name, shaderSource->string(), 0 ); auto ptrSource = globjects::Shader::sourceFromString( preprocessedSource ); addShaderFromSource( type, std::move( ptrSource ), name ); } void ShaderProgram::addShaderFromSource( ShaderType type, std::unique_ptr<globjects::StaticStringSource>&& ptrSource, const std::string& name ) { auto shader = globjects::Shader::create( getTypeAsGLEnum( type ) ); shader->setName( name ); shader->setSource( ptrSource.get() ); shader->compile(); GL_CHECK_ERROR; m_shaderObjects[type].swap( shader ); m_shaderSources[type].swap( ptrSource ); // ^^^ raw ptrSource are stored in shader object, need to keep them valid during // shader life } GLenum ShaderProgram::getTypeAsGLEnum( ShaderType type ) const { switch ( type ) { case ShaderType_VERTEX: return GL_VERTEX_SHADER; case ShaderType_FRAGMENT: return GL_FRAGMENT_SHADER; case ShaderType_GEOMETRY: return GL_GEOMETRY_SHADER; case ShaderType_TESS_EVALUATION: return GL_TESS_EVALUATION_SHADER; case ShaderType_TESS_CONTROL: return GL_TESS_CONTROL_SHADER; #ifndef OS_MACOS // GL_COMPUTE_SHADER requires OpenGL >= 4.2, Apple provides OpenGL 4.1 case ShaderType_COMPUTE: return GL_COMPUTE_SHADER; #endif default: CORE_ERROR( "Wrong ShaderType" ); } // Should never get there return GL_ZERO; } ShaderType ShaderProgram::getGLenumAsType( GLenum type ) const { switch ( type ) { case GL_VERTEX_SHADER: return ShaderType_VERTEX; case GL_FRAGMENT_SHADER: return ShaderType_FRAGMENT; case GL_GEOMETRY_SHADER: return ShaderType_GEOMETRY; case GL_TESS_EVALUATION_SHADER: return ShaderType_TESS_EVALUATION; case GL_TESS_CONTROL_SHADER: return ShaderType_TESS_CONTROL; #ifndef OS_MACOS case GL_COMPUTE_SHADER: return ShaderType_COMPUTE; #endif default: CORE_ERROR( "Wrong GLenum" ); } // Should never get there return ShaderType_COUNT; } void ShaderProgram::load( const ShaderConfiguration& shaderConfig ) { m_configuration = shaderConfig; CORE_ERROR_IF( m_configuration.isComplete(), ( "Shader program " + shaderConfig.m_name + " misses vertex or fragment shader." ) .c_str() ); for ( size_t i = 0; i < ShaderType_COUNT; ++i ) { if ( !m_configuration.m_shaders[i].empty() ) { LOG( logDEBUG ) << "Loading shader " << m_configuration.m_shaders[i]; loadShader( ShaderType( i ), m_configuration.m_shaders[i], m_configuration.getProperties(), m_configuration.getIncludes(), m_configuration.m_version ); } } link(); } void ShaderProgram::link() { m_program = globjects::Program::create(); for ( int i = 0; i < ShaderType_COUNT; ++i ) { if ( m_shaderObjects[i] ) { m_program->attach( m_shaderObjects[i].get() ); } } m_program->setParameter( GL_PROGRAM_SEPARABLE, GL_TRUE ); m_program->link(); GL_CHECK_ERROR; int texUnit = 0; auto total = GLuint( m_program->get( GL_ACTIVE_UNIFORMS ) ); textureUnits.clear(); for ( GLuint i = 0; i < total; ++i ) { auto name = m_program->getActiveUniformName( i ); auto type = m_program->getActiveUniform( i, GL_UNIFORM_TYPE ); //!\todo add other sampler type (or manage all type of sampler automatically) if ( type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE || type == GL_SAMPLER_2D_RECT || type == GL_SAMPLER_2D_SHADOW || type == GL_SAMPLER_3D || type == GL_SAMPLER_CUBE_SHADOW ) { auto location = m_program->getUniformLocation( name ); textureUnits[name] = TextureBinding( texUnit++, location ); } } } void ShaderProgram::bind() const { m_program->use(); } void ShaderProgram::validate() const { m_program->validate(); if ( !m_program->isValid() ) { LOG( logDEBUG ) << m_program->infoLog(); } } void ShaderProgram::unbind() const { m_program->release(); } void ShaderProgram::reload() { for ( auto& s : m_shaderObjects ) { /// \todo find a way to reload shader without source code file name. if ( s != nullptr && !s->name().empty() ) { LOG( logDEBUG ) << "Reloading shader " << s->name(); m_program->detach( s.get() ); loadShader( getGLenumAsType( s->type() ), s->name(), m_configuration.getProperties(), m_configuration.getIncludes() ); } } link(); } ShaderConfiguration ShaderProgram::getBasicConfiguration() const { ShaderConfiguration basicConfig; basicConfig.m_shaders = m_configuration.m_shaders; basicConfig.m_name = m_configuration.m_name; return basicConfig; } void ShaderProgram::setUniform( const char* name, int value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, unsigned int value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, float value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, double value ) const { m_program->setUniform( name, static_cast<float>( value ) ); } //! void ShaderProgram::setUniform( const char* name, std::vector<int> values ) const { m_program->setUniform( name, values ); } void ShaderProgram::setUniform( const char* name, std::vector<unsigned int> values ) const { m_program->setUniform( name, values ); } void ShaderProgram::setUniform( const char* name, std::vector<float> values ) const { m_program->setUniform( name, values ); } //! void ShaderProgram::setUniform( const char* name, const Core::Vector2i& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector2f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector2d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Vector3i& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector3f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector3d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Vector4i& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector4f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Vector4d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix2f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix2d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix3f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix3d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix4f& value ) const { m_program->setUniform( name, value ); } void ShaderProgram::setUniform( const char* name, const Core::Matrix4d& value ) const { m_program->setUniform( name, value.cast<float>().eval() ); } void ShaderProgram::setUniform( const char* name, Texture* tex, int texUnit ) const { tex->bind( texUnit ); m_program->setUniform( name, texUnit ); } void ShaderProgram::setUniformTexture( const char* name, Texture* tex ) const { auto itr = textureUnits.find( std::string( name ) ); if ( itr != textureUnits.end() ) { tex->bind( itr->second.m_texUnit ); m_program->setUniform( itr->second.m_location, itr->second.m_texUnit ); } } globjects::Program* ShaderProgram::getProgramObject() const { return m_program.get(); } /**************************************************** * Include workaround due to globject bugs ****************************************************/ std::string ShaderProgram::preprocessIncludes( const std::string& name, const std::string& shader, int level, int line ) { CORE_ERROR_IF( level < 32, "Shader inclusion depth limit reached." ); std::string result{}; std::vector<std::string> finalStrings; uint nline = 0; static const std::regex reg( "^[ ]*#[ ]*include[ ]+[\"<](.*)[\">].*" ); // source: https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/ std::istringstream iss( shader ); std::string codeline; while ( std::getline( iss, codeline, '\n' ) ) { std::smatch match; if ( std::regex_search( codeline, match, reg ) ) { // Radium V2 : for composable shaders, use the includePaths set elsewhere. auto includeNameString = globjects::NamedString::getFromRegistry( std::string( "/" ) + match[1].str() ); if ( includeNameString != nullptr ) { codeline = preprocessIncludes( match[1].str(), includeNameString->string(), level + 1, 0 ); } else { LOG( logWARNING ) << "Cannot open included file " << match[1].str() << " at line" << nline << " of file " << name << ". Ignored."; continue; } // Radium V2, adapt this if globjct includes bug is still present /* std::string inc; std::string file = m_filepath + match[1].str(); if (parseFile(file, inc)) { sublerr.start = nline; sublerr.name = file; lerr.subfiles.push_back(sublerr); line = preprocessIncludes(inc, level + 1, lerr.subfiles.back()); nline = lerr.subfiles.back().end; } else { LOG(logWARNING) << "Cannot open included file " << file << " from " << m_filename << ". Ignored."; continue; } */ } finalStrings.push_back( codeline ); ++nline; } // Build final shader string for ( const auto& l : finalStrings ) { result.append( l ); result.append( "\n" ); } result.append( "\0" ); return result; } } // namespace Engine } // namespace Ra <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/notifications/balloon_collection_impl.h" #include <algorithm> #include "base/logging.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/chromeos/notifications/balloon_view.h" #include "chrome/browser/chromeos/notifications/notification_panel.h" #include "chrome/browser/notifications/balloon.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/ui/window_sizer.h" #include "chrome/common/notification_service.h" #include "gfx/rect.h" #include "gfx/size.h" namespace { // Margin from the edge of the work area const int kVerticalEdgeMargin = 5; const int kHorizontalEdgeMargin = 5; } // namespace namespace chromeos { BalloonCollectionImpl::BalloonCollectionImpl() : notification_ui_(new NotificationPanel()) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, NotificationService::AllSources()); } BalloonCollectionImpl::~BalloonCollectionImpl() { Shutdown(); } void BalloonCollectionImpl::Add(const Notification& notification, Profile* profile) { Balloon* new_balloon = MakeBalloon(notification, profile); base_.Add(new_balloon); new_balloon->Show(); notification_ui_->Add(new_balloon); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } bool BalloonCollectionImpl::AddDOMUIMessageCallback( const Notification& notification, const std::string& message, MessageCallback* callback) { Balloon* balloon = FindBalloon(notification); if (!balloon) { delete callback; return false; } BalloonViewHost* host = static_cast<BalloonViewHost*>(balloon->view()->GetHost()); return host->AddDOMUIMessageCallback(message, callback); } void BalloonCollectionImpl::AddSystemNotification( const Notification& notification, Profile* profile, bool sticky, bool control) { Balloon* new_balloon = new Balloon(notification, profile, this); new_balloon->set_view( new chromeos::BalloonViewImpl(sticky, control, true)); base_.Add(new_balloon); new_balloon->Show(); notification_ui_->Add(new_balloon); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } bool BalloonCollectionImpl::UpdateNotification( const Notification& notification) { Balloon* balloon = FindBalloon(notification); if (!balloon) return false; balloon->Update(notification); notification_ui_->Update(balloon); return true; } bool BalloonCollectionImpl::UpdateAndShowNotification( const Notification& notification) { Balloon* balloon = FindBalloon(notification); if (!balloon) return false; balloon->Update(notification); bool updated = notification_ui_->Update(balloon); DCHECK(updated); notification_ui_->Show(balloon); return true; } bool BalloonCollectionImpl::RemoveById(const std::string& id) { return base_.CloseById(id); } bool BalloonCollectionImpl::RemoveBySourceOrigin(const GURL& origin) { return base_.CloseAllBySourceOrigin(origin); } void BalloonCollectionImpl::RemoveAll() { base_.CloseAll(); } bool BalloonCollectionImpl::HasSpace() const { return true; } void BalloonCollectionImpl::ResizeBalloon(Balloon* balloon, const gfx::Size& size) { notification_ui_->ResizeNotification(balloon, size); } void BalloonCollectionImpl::OnBalloonClosed(Balloon* source) { notification_ui_->Remove(source); base_.Remove(source); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } void BalloonCollectionImpl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::BROWSER_CLOSED); bool app_closing = *Details<bool>(details).ptr(); // When exitting, we need to shutdown all renderers in // BalloonViewImpl before IO thread gets deleted in the // BrowserProcessImpl's destructor. See http://crbug.com/40810 // for details. if (app_closing) Shutdown(); } void BalloonCollectionImpl::Shutdown() { // We need to remove the panel first because deleting // views that are not owned by parent will not remove // themselves from the parent. DVLOG(1) << "Shutting down notification UI"; notification_ui_.reset(); } Balloon* BalloonCollectionImpl::MakeBalloon(const Notification& notification, Profile* profile) { Balloon* new_balloon = new Balloon(notification, profile, this); new_balloon->set_view(new chromeos::BalloonViewImpl(false, true, false)); return new_balloon; } } // namespace chromeos // static BalloonCollection* BalloonCollection::Create() { return new chromeos::BalloonCollectionImpl(); } <commit_msg>Notification UI should not be reset at browser-close, as the notification ui logic will try to close open balloons during shutdown, resulting in a crash later.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/notifications/balloon_collection_impl.h" #include <algorithm> #include "base/logging.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/chromeos/notifications/balloon_view.h" #include "chrome/browser/chromeos/notifications/notification_panel.h" #include "chrome/browser/notifications/balloon.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/ui/window_sizer.h" #include "chrome/common/notification_service.h" #include "gfx/rect.h" #include "gfx/size.h" namespace { // Margin from the edge of the work area const int kVerticalEdgeMargin = 5; const int kHorizontalEdgeMargin = 5; } // namespace namespace chromeos { BalloonCollectionImpl::BalloonCollectionImpl() : notification_ui_(new NotificationPanel()) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, NotificationService::AllSources()); } BalloonCollectionImpl::~BalloonCollectionImpl() { Shutdown(); } void BalloonCollectionImpl::Add(const Notification& notification, Profile* profile) { Balloon* new_balloon = MakeBalloon(notification, profile); base_.Add(new_balloon); new_balloon->Show(); notification_ui_->Add(new_balloon); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } bool BalloonCollectionImpl::AddDOMUIMessageCallback( const Notification& notification, const std::string& message, MessageCallback* callback) { Balloon* balloon = FindBalloon(notification); if (!balloon) { delete callback; return false; } BalloonViewHost* host = static_cast<BalloonViewHost*>(balloon->view()->GetHost()); return host->AddDOMUIMessageCallback(message, callback); } void BalloonCollectionImpl::AddSystemNotification( const Notification& notification, Profile* profile, bool sticky, bool control) { Balloon* new_balloon = new Balloon(notification, profile, this); new_balloon->set_view( new chromeos::BalloonViewImpl(sticky, control, true)); base_.Add(new_balloon); new_balloon->Show(); notification_ui_->Add(new_balloon); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } bool BalloonCollectionImpl::UpdateNotification( const Notification& notification) { Balloon* balloon = FindBalloon(notification); if (!balloon) return false; balloon->Update(notification); notification_ui_->Update(balloon); return true; } bool BalloonCollectionImpl::UpdateAndShowNotification( const Notification& notification) { Balloon* balloon = FindBalloon(notification); if (!balloon) return false; balloon->Update(notification); bool updated = notification_ui_->Update(balloon); DCHECK(updated); notification_ui_->Show(balloon); return true; } bool BalloonCollectionImpl::RemoveById(const std::string& id) { return base_.CloseById(id); } bool BalloonCollectionImpl::RemoveBySourceOrigin(const GURL& origin) { return base_.CloseAllBySourceOrigin(origin); } void BalloonCollectionImpl::RemoveAll() { base_.CloseAll(); } bool BalloonCollectionImpl::HasSpace() const { return true; } void BalloonCollectionImpl::ResizeBalloon(Balloon* balloon, const gfx::Size& size) { notification_ui_->ResizeNotification(balloon, size); } void BalloonCollectionImpl::OnBalloonClosed(Balloon* source) { notification_ui_->Remove(source); base_.Remove(source); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } void BalloonCollectionImpl::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::BROWSER_CLOSED); bool app_closing = *Details<bool>(details).ptr(); // When exiting, we need to shutdown all renderers in // BalloonViewImpl before IO thread gets deleted in the // BrowserProcessImpl's destructor. See http://crbug.com/40810 // for details. if (app_closing) RemoveAll(); } void BalloonCollectionImpl::Shutdown() { // We need to remove the panel first because deleting // views that are not owned by parent will not remove // themselves from the parent. DVLOG(1) << "Shutting down notification UI"; notification_ui_.reset(); } Balloon* BalloonCollectionImpl::MakeBalloon(const Notification& notification, Profile* profile) { Balloon* new_balloon = new Balloon(notification, profile, this); new_balloon->set_view(new chromeos::BalloonViewImpl(false, true, false)); return new_balloon; } } // namespace chromeos // static BalloonCollection* BalloonCollection::Create() { return new chromeos::BalloonCollectionImpl(); } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2014 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // // ospray #include "Renderer.h" #include "../common/Library.h" // stl #include <map> // ispc exports #include "Renderer_ispc.h" // ospray #include "LoadBalancer.h" namespace ospray { using std::cout; using std::endl; typedef Renderer *(*creatorFct)(); std::map<std::string, creatorFct> rendererRegistry; void Renderer::commit() { spp = getParam1i("spp",1); nearClip = getParam1f("near_clip",1e-6f); if(this->getIE()) { ispc::Renderer_setSPP(this->getIE(),spp); ispc::Renderer_setNearClip(this->getIE(), nearClip); } } Renderer *Renderer::createRenderer(const char *type) { std::map<std::string, Renderer *(*)()>::iterator it = rendererRegistry.find(type); if (it != rendererRegistry.end()) return it->second ? (it->second)() : NULL; if (ospray::logLevel >= 2) std::cout << "#ospray: trying to look up renderer type '" << type << "' for the first time" << std::endl; std::string creatorName = "ospray_create_renderer__"+std::string(type); creatorFct creator = (creatorFct)getSymbol(creatorName); //dlsym(RTLD_DEFAULT,creatorName.c_str()); rendererRegistry[type] = creator; if (creator == NULL) { if (ospray::logLevel >= 1) std::cout << "#ospray: could not find renderer type '" << type << "'" << std::endl; return NULL; } Renderer *renderer = (*creator)(); renderer->managedObjectType = OSP_RENDERER; return(renderer); } void Renderer::renderTile(Tile &tile) { ispc::Renderer_renderTile(getIE(),(ispc::Tile&)tile); } void Renderer::beginFrame(FrameBuffer *fb) { this->currentFB = fb; ispc::Renderer_beginFrame(getIE(),fb->getIE()); } void Renderer::endFrame(const int32 fbChannelFlags) { FrameBuffer *fb = this->currentFB; if ((fbChannelFlags & OSP_FB_ACCUM)) fb->accumID++; ispc::Renderer_endFrame(getIE(),fb->accumID); } void Renderer::renderFrame(FrameBuffer *fb, const uint32 channelFlags) { TiledLoadBalancer::instance->renderFrame(this,fb,channelFlags); } OSPPickData Renderer::unproject(const vec2f &screenPos) { assert(getIE()); bool hit; float x, y, z; ispc::Renderer_unproject(getIE(),(const ispc::vec2f&)screenPos, hit, x, y, z); OSPPickData ret = { hit, x, y, z }; return ret; } } // ::ospray <commit_msg>can now load renderers as name@lib<commit_after>// ======================================================================== // // Copyright 2009-2014 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // // ospray #include "Renderer.h" #include "../common/Library.h" // stl #include <map> // ispc exports #include "Renderer_ispc.h" // ospray #include "LoadBalancer.h" namespace ospray { using std::cout; using std::endl; typedef Renderer *(*creatorFct)(); std::map<std::string, creatorFct> rendererRegistry; void Renderer::commit() { spp = getParam1i("spp",1); nearClip = getParam1f("near_clip",1e-6f); if(this->getIE()) { ispc::Renderer_setSPP(this->getIE(),spp); ispc::Renderer_setNearClip(this->getIE(), nearClip); } } Renderer *Renderer::createRenderer(const char *_type) { char type[strlen(_type)+1]; strcpy(type,_type); char *atSign = strstr(type,"@"); char *libName = NULL; if (atSign) { *atSign = 0; libName = atSign+1; } if (libName) loadLibrary("ospray_module_"+std::string(libName)); std::map<std::string, Renderer *(*)()>::iterator it = rendererRegistry.find(type); if (it != rendererRegistry.end()) return it->second ? (it->second)() : NULL; if (ospray::logLevel >= 2) std::cout << "#ospray: trying to look up renderer type '" << type << "' for the first time" << std::endl; std::string creatorName = "ospray_create_renderer__"+std::string(type); creatorFct creator = (creatorFct)getSymbol(creatorName); //dlsym(RTLD_DEFAULT,creatorName.c_str()); rendererRegistry[type] = creator; if (creator == NULL) { PING; if (ospray::logLevel >= 1) std::cout << "#ospray: could not find renderer type '" << type << "'" << std::endl; return NULL; } Renderer *renderer = (*creator)(); renderer->managedObjectType = OSP_RENDERER; return(renderer); } void Renderer::renderTile(Tile &tile) { ispc::Renderer_renderTile(getIE(),(ispc::Tile&)tile); } void Renderer::beginFrame(FrameBuffer *fb) { this->currentFB = fb; ispc::Renderer_beginFrame(getIE(),fb->getIE()); } void Renderer::endFrame(const int32 fbChannelFlags) { FrameBuffer *fb = this->currentFB; if ((fbChannelFlags & OSP_FB_ACCUM)) fb->accumID++; ispc::Renderer_endFrame(getIE(),fb->accumID); } void Renderer::renderFrame(FrameBuffer *fb, const uint32 channelFlags) { TiledLoadBalancer::instance->renderFrame(this,fb,channelFlags); } OSPPickData Renderer::unproject(const vec2f &screenPos) { assert(getIE()); bool hit; float x, y, z; ispc::Renderer_unproject(getIE(),(const ispc::vec2f&)screenPos, hit, x, y, z); OSPPickData ret = { hit, x, y, z }; return ret; } } // ::ospray <|endoftext|>
<commit_before><commit_msg>fix spelling: garded -> guarded<commit_after><|endoftext|>
<commit_before>#include <mixal/mdk_program_loader.h> #include <mixal/program_loader.h> #include <mixal/exceptions.h> #include <core/optional.h> #include <fstream> namespace mixal { namespace { // This part of code is piece of MDK that loads compiled file. // Code can be found there: https://www.gnu.org/software/mdk/ // (Mostly) from mix_code_file.c struct mix_cfheader_t { std::int32_t signature; std::int32_t mj_ver; std::int32_t mn_ver; std::int16_t start; std::uint64_t path_len; }; using mix_word_t = std::uint32_t; using mix_short_t = std::uint16_t; const std::int32_t k_signature = 0xDEADBEEF; const std::int32_t k_signature_debug = 0xBEEFDEAD; const mix_word_t k_mdk_word_sign_bit = (1L << 30); const mix_word_t k_mdk_addr_tag = (k_mdk_word_sign_bit << 1); const mix_word_t k_mdk_word_zero = 0; const mix_word_t k_mdk_short_max = ((1L << 12) - 1); bool IsInstructionWord(mix_word_t tagged) { return ((tagged & k_mdk_addr_tag) == 0); } bool IsAddressWord(mix_word_t tagged) { return ((tagged & k_mdk_addr_tag) == k_mdk_addr_tag); } Word ExtractInstruction(mix_word_t tagged) { const bool has_sign = ((tagged & k_mdk_word_sign_bit) == k_mdk_word_sign_bit); if (has_sign) { return WordValue(mix::Sign::Negative , static_cast<WordValue::Type>(tagged & ~k_mdk_word_sign_bit)); } return static_cast<WordValue::Type>(tagged); } int ExtractAddress(mix_word_t tagged) { return static_cast<int>(tagged & k_mdk_short_max); } bool IsDebugSignature(std::int32_t signature) { return (signature == k_signature_debug); } bool IsReleaseSignature(std::int32_t signature) { return (signature == k_signature); } bool IsValidSignature(std::int32_t signature) { return IsDebugSignature(signature) || IsReleaseSignature(signature); } std::optional<TranslatedWord> ParseNextWord(std::istream& stream , bool is_debug, int& address_counter) { mix_word_t next = 0; while (true) { if (!stream.read(reinterpret_cast<char*>(&next), sizeof(next))) { return std::nullopt; } if (IsAddressWord(next)) { address_counter = ExtractAddress(next); } else if (IsInstructionWord(next)) { if (is_debug) { mix_short_t line_number = 0; if (!stream.read(reinterpret_cast<char*>(&line_number), sizeof(line_number))) { return std::nullopt; } (void)line_number; } TranslatedWord translated; translated.original_address = address_counter++; translated.value = ExtractInstruction(next); return translated; } } assert(false && "Not reachable"); return std::nullopt; } } // namespace TranslatedProgram ParseProgramFromMDKStream(std::istream& stream) { // 1. Header mix_cfheader_t header{}; if (!stream.read(reinterpret_cast<char*>(&header), sizeof(header))) { throw CorruptedMDKStream("failed to read header"); } if (!IsValidSignature(header.signature)) { throw CorruptedMDKStream("invalid signature"); } // 2. Translated file path std::string file_path(static_cast<std::size_t>(header.path_len) + 1, '\0'); if (!stream.read(&(file_path[0]), header.path_len)) { throw CorruptedMDKStream("failed to read file path"); } (void)file_path; const bool is_debug = IsDebugSignature(header.signature); // 3. Debug symbol names and values if (is_debug) { while (stream.get() == ',') { std::string symbol; long value = 0; std::getline(stream, symbol, '='); stream >> value; (void)symbol; (void)value; } } // 5. Finally, bytecode TranslatedProgram mdk_program; int address = 0; while (auto translated = ParseNextWord(stream, is_debug, address)) { mdk_program.commands.push_back(std::move(*translated)); } mdk_program.start_address = header.start; mdk_program.completed = true; return mdk_program; } TranslatedProgram ParseProgramFromMDKFile(const std::string& file_path) { std::ifstream input(file_path, std::ios_base::binary); return ParseProgramFromMDKStream(input); } void LoadProgramFromMDKFile(mix::Computer& computer, const std::string& file_path) { LoadProgram(computer, ParseProgramFromMDKFile(file_path)); } void LoadProgramFromMDKStream(mix::Computer& computer, std::istream& stream) { LoadProgram(computer, ParseProgramFromMDKStream(stream)); } } // namespace mixal <commit_msg>Fix unused variable warning (k_mdk_word_zero)<commit_after>#include <mixal/mdk_program_loader.h> #include <mixal/program_loader.h> #include <mixal/exceptions.h> #include <core/optional.h> #include <fstream> namespace mixal { namespace { // This part of code is piece of MDK that loads compiled file. // Code can be found there: https://www.gnu.org/software/mdk/ // (Mostly) from mix_code_file.c struct mix_cfheader_t { std::int32_t signature; std::int32_t mj_ver; std::int32_t mn_ver; std::int16_t start; std::uint64_t path_len; }; using mix_word_t = std::uint32_t; using mix_short_t = std::uint16_t; const std::int32_t k_signature = 0xDEADBEEF; const std::int32_t k_signature_debug = 0xBEEFDEAD; const mix_word_t k_mdk_word_sign_bit = (1L << 30); const mix_word_t k_mdk_addr_tag = (k_mdk_word_sign_bit << 1); const mix_word_t k_mdk_word_zero = 0; const mix_word_t k_mdk_short_max = ((1L << 12) - 1); bool IsInstructionWord(mix_word_t tagged) { return ((tagged & k_mdk_addr_tag) == k_mdk_word_zero); } bool IsAddressWord(mix_word_t tagged) { return ((tagged & k_mdk_addr_tag) == k_mdk_addr_tag); } Word ExtractInstruction(mix_word_t tagged) { const bool has_sign = ((tagged & k_mdk_word_sign_bit) == k_mdk_word_sign_bit); if (has_sign) { return WordValue(mix::Sign::Negative , static_cast<WordValue::Type>(tagged & ~k_mdk_word_sign_bit)); } return static_cast<WordValue::Type>(tagged); } int ExtractAddress(mix_word_t tagged) { return static_cast<int>(tagged & k_mdk_short_max); } bool IsDebugSignature(std::int32_t signature) { return (signature == k_signature_debug); } bool IsReleaseSignature(std::int32_t signature) { return (signature == k_signature); } bool IsValidSignature(std::int32_t signature) { return IsDebugSignature(signature) || IsReleaseSignature(signature); } std::optional<TranslatedWord> ParseNextWord(std::istream& stream , bool is_debug, int& address_counter) { mix_word_t next = 0; while (true) { if (!stream.read(reinterpret_cast<char*>(&next), sizeof(next))) { return std::nullopt; } if (IsAddressWord(next)) { address_counter = ExtractAddress(next); } else if (IsInstructionWord(next)) { if (is_debug) { mix_short_t line_number = 0; if (!stream.read(reinterpret_cast<char*>(&line_number), sizeof(line_number))) { return std::nullopt; } (void)line_number; } TranslatedWord translated; translated.original_address = address_counter++; translated.value = ExtractInstruction(next); return translated; } } assert(false && "Not reachable"); return std::nullopt; } } // namespace TranslatedProgram ParseProgramFromMDKStream(std::istream& stream) { // 1. Header mix_cfheader_t header{}; if (!stream.read(reinterpret_cast<char*>(&header), sizeof(header))) { throw CorruptedMDKStream("failed to read header"); } if (!IsValidSignature(header.signature)) { throw CorruptedMDKStream("invalid signature"); } // 2. Translated file path std::string file_path(static_cast<std::size_t>(header.path_len) + 1, '\0'); if (!stream.read(&(file_path[0]), header.path_len)) { throw CorruptedMDKStream("failed to read file path"); } (void)file_path; const bool is_debug = IsDebugSignature(header.signature); // 3. Debug symbol names and values if (is_debug) { while (stream.get() == ',') { std::string symbol; long value = 0; std::getline(stream, symbol, '='); stream >> value; (void)symbol; (void)value; } } // 5. Finally, bytecode TranslatedProgram mdk_program; int address = 0; while (auto translated = ParseNextWord(stream, is_debug, address)) { mdk_program.commands.push_back(std::move(*translated)); } mdk_program.start_address = header.start; mdk_program.completed = true; return mdk_program; } TranslatedProgram ParseProgramFromMDKFile(const std::string& file_path) { std::ifstream input(file_path, std::ios_base::binary); return ParseProgramFromMDKStream(input); } void LoadProgramFromMDKFile(mix::Computer& computer, const std::string& file_path) { LoadProgram(computer, ParseProgramFromMDKFile(file_path)); } void LoadProgramFromMDKStream(mix::Computer& computer, std::istream& stream) { LoadProgram(computer, ParseProgramFromMDKStream(stream)); } } // namespace mixal <|endoftext|>
<commit_before>// Copyright (c) 2019 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <franka_hw/franka_combined_hw.h> #include <algorithm> #include <memory> #include <actionlib/server/simple_action_server.h> #include <ros/node_handle.h> #include <ros/time.h> #include <std_srvs/Trigger.h> #include <franka_hw/franka_combinable_hw.h> #include <franka_hw/franka_hw.h> #include <franka_msgs/ErrorRecoveryAction.h> namespace franka_hw { FrankaCombinedHW::FrankaCombinedHW() = default; bool FrankaCombinedHW::init(ros::NodeHandle& root_nh, ros::NodeHandle& robot_hw_nh) { bool success = CombinedRobotHW::init(root_nh, robot_hw_nh); // Error recovery server for all FrankaHWs combined_recovery_action_server_ = std::make_unique<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>>( robot_hw_nh, "error_recovery", [&](const franka_msgs::ErrorRecoveryGoalConstPtr&) { try { is_recovering_ = true; for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr) { franka_combinable_hw_ptr->resetError(); } else { ROS_ERROR( "FrankaCombinedHW: dynamic_cast from RobotHW to FrankaCombinableHW failed."); is_recovering_ = false; combined_recovery_action_server_->setAborted( franka_msgs::ErrorRecoveryResult(), "dynamic_cast from RobotHW to FrankaCombinableHW failed"); return; } } is_recovering_ = false; combined_recovery_action_server_->setSucceeded(); } catch (const franka::Exception& ex) { is_recovering_ = false; combined_recovery_action_server_->setAborted(franka_msgs::ErrorRecoveryResult(), ex.what()); } }, false); combined_recovery_action_server_->start(); connect_server_ = robot_hw_nh.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "connect", [this](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { try { connect(); ROS_INFO("FrankaCombinedHW: successfully connected robots."); response.success = 1u; response.message = ""; } catch (const std::exception& e) { ROS_INFO("Combined: exception %s", e.what()); response.success = 0u; response.message = "FrankaCombinedHW: Failed to connect robot: " + std::string(e.what()); } return true; }); disconnect_server_ = robot_hw_nh.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "disconnect", [this](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { bool success = disconnect(); response.success = success ? 1u : 0u; response.message = success ? "FrankaCombinedHW: Successfully disconnected robots." : "FrankaCombinedHW: Failed to disconnect robots. All active " "controllers must be stopped before you can disconnect."; if (success) { ROS_INFO("%s", response.message.c_str()); } else { ROS_ERROR("%s", response.message.c_str()); } return true; }); return success; } void FrankaCombinedHW::read(const ros::Time& time, const ros::Duration& period) { // Call the read method of the single RobotHW objects. CombinedRobotHW::read(time, period); handleError(); } bool FrankaCombinedHW::controllerNeedsReset() { // Check if any of the RobotHW object needs a controller reset bool controller_reset = false; for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr) { controller_reset = controller_reset || franka_combinable_hw_ptr->controllerNeedsReset(); } else { ROS_ERROR("FrankaCombinedHW: dynamic_cast from RobotHW to FrankaCombinableHW failed."); return false; } } return controller_reset; } void FrankaCombinedHW::handleError() { // Trigger error state of all other RobotHW objects when one of them has a error. if (hasError() && !is_recovering_) { triggerError(); } } bool FrankaCombinedHW::hasError() { bool has_error = false; for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr) { has_error = has_error || franka_combinable_hw_ptr->hasError(); } else { ROS_ERROR("FrankaCombinedHW: dynamic_cast from RobotHW to FrankaCombinableHW failed."); return false; } } return has_error; } void FrankaCombinedHW::triggerError() { // Trigger error state of all RobotHW objects. for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr) { franka_combinable_hw_ptr->triggerError(); } else { ROS_ERROR("FrankaCombinedHW: dynamic_cast from RobotHW to FrankaCombinableHW failed."); } } } void FrankaCombinedHW::connect() { for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr && !franka_combinable_hw_ptr->connected()) { franka_combinable_hw_ptr->connect(); } } } bool FrankaCombinedHW::disconnect() { // Ensure all robots are disconnectable (not running a controller) for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr && franka_combinable_hw_ptr->controllerActive()) { return false; } } // Only if all robots are in fact disconnectable, disconnecting them. // Fail and abort if any robot cannot be disconnected. for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr && !franka_combinable_hw_ptr->disconnect()) { return false; } } return true; } } // namespace franka_hw <commit_msg>check whether robot is connected when trying to recover combined<commit_after>// Copyright (c) 2019 Franka Emika GmbH // Use of this source code is governed by the Apache-2.0 license, see LICENSE #include <franka_hw/franka_combined_hw.h> #include <algorithm> #include <memory> #include <actionlib/server/simple_action_server.h> #include <ros/node_handle.h> #include <ros/time.h> #include <std_srvs/Trigger.h> #include <franka_hw/franka_combinable_hw.h> #include <franka_hw/franka_hw.h> #include <franka_msgs/ErrorRecoveryAction.h> namespace franka_hw { FrankaCombinedHW::FrankaCombinedHW() = default; bool FrankaCombinedHW::init(ros::NodeHandle& root_nh, ros::NodeHandle& robot_hw_nh) { bool success = CombinedRobotHW::init(root_nh, robot_hw_nh); // Error recovery server for all FrankaHWs combined_recovery_action_server_ = std::make_unique<actionlib::SimpleActionServer<franka_msgs::ErrorRecoveryAction>>( robot_hw_nh, "error_recovery", [&](const franka_msgs::ErrorRecoveryGoalConstPtr&) { try { is_recovering_ = true; for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr && franka_combinable_hw_ptr->connected()) { franka_combinable_hw_ptr->resetError(); } else { ROS_ERROR("FrankaCombinedHW: failed to reset error. Is the robot connected?"); is_recovering_ = false; combined_recovery_action_server_->setAborted( franka_msgs::ErrorRecoveryResult(), "dynamic_cast from RobotHW to FrankaCombinableHW failed"); return; } } is_recovering_ = false; combined_recovery_action_server_->setSucceeded(); } catch (const franka::Exception& ex) { is_recovering_ = false; combined_recovery_action_server_->setAborted(franka_msgs::ErrorRecoveryResult(), ex.what()); } }, false); combined_recovery_action_server_->start(); connect_server_ = robot_hw_nh.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "connect", [this](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { try { connect(); ROS_INFO("FrankaCombinedHW: successfully connected robots."); response.success = 1u; response.message = ""; } catch (const std::exception& e) { ROS_INFO("Combined: exception %s", e.what()); response.success = 0u; response.message = "FrankaCombinedHW: Failed to connect robot: " + std::string(e.what()); } return true; }); disconnect_server_ = robot_hw_nh.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>( "disconnect", [this](std_srvs::Trigger::Request& request, std_srvs::Trigger::Response& response) -> bool { bool success = disconnect(); response.success = success ? 1u : 0u; response.message = success ? "FrankaCombinedHW: Successfully disconnected robots." : "FrankaCombinedHW: Failed to disconnect robots. All active " "controllers must be stopped before you can disconnect."; if (success) { ROS_INFO("%s", response.message.c_str()); } else { ROS_ERROR("%s", response.message.c_str()); } return true; }); return success; } void FrankaCombinedHW::read(const ros::Time& time, const ros::Duration& period) { // Call the read method of the single RobotHW objects. CombinedRobotHW::read(time, period); handleError(); } bool FrankaCombinedHW::controllerNeedsReset() { // Check if any of the RobotHW object needs a controller reset bool controller_reset = false; for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr) { controller_reset = controller_reset || franka_combinable_hw_ptr->controllerNeedsReset(); } else { ROS_ERROR("FrankaCombinedHW: dynamic_cast from RobotHW to FrankaCombinableHW failed."); return false; } } return controller_reset; } void FrankaCombinedHW::handleError() { // Trigger error state of all other RobotHW objects when one of them has a error. if (hasError() && !is_recovering_) { triggerError(); } } bool FrankaCombinedHW::hasError() { bool has_error = false; for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr) { has_error = has_error || franka_combinable_hw_ptr->hasError(); } else { ROS_ERROR("FrankaCombinedHW: dynamic_cast from RobotHW to FrankaCombinableHW failed."); return false; } } return has_error; } void FrankaCombinedHW::triggerError() { // Trigger error state of all RobotHW objects. for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr) { franka_combinable_hw_ptr->triggerError(); } else { ROS_ERROR("FrankaCombinedHW: dynamic_cast from RobotHW to FrankaCombinableHW failed."); } } } void FrankaCombinedHW::connect() { for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr && !franka_combinable_hw_ptr->connected()) { franka_combinable_hw_ptr->connect(); } } } bool FrankaCombinedHW::disconnect() { // Ensure all robots are disconnectable (not running a controller) for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr && franka_combinable_hw_ptr->controllerActive()) { return false; } } // Only if all robots are in fact disconnectable, disconnecting them. // Fail and abort if any robot cannot be disconnected. for (const auto& robot_hw : robot_hw_list_) { auto* franka_combinable_hw_ptr = dynamic_cast<franka_hw::FrankaCombinableHW*>(robot_hw.get()); if (franka_combinable_hw_ptr != nullptr && !franka_combinable_hw_ptr->disconnect()) { return false; } } return true; } } // namespace franka_hw <|endoftext|>
<commit_before>/***************************************************************************** * Copyright 2011 Sergey Shekyan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ /***** * Author: Sergey Shekyan [email protected] * Victor Agababov [email protected] * * Slow HTTP attack vulnerability test tool * http://code.google.com/p/slowhttptest/ *****/ #include <ctime> #include <errno.h> #ifdef __linux #include <execinfo.h> #endif #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "slowlog.h" namespace { static FILE* log_file = NULL; int current_log_level; void print_call_stack() { #ifdef __linux__ static void* buf[64]; const int depth = backtrace(buf, sizeof(buf)/sizeof(buf[0])); backtrace_symbols_fd(buf, depth, fileno(stdout)); if (stdout != log_file) { backtrace_symbols_fd(buf, depth, fileno(log_file)); } #else return; #endif } } namespace slowhttptest { void slowlog_init(int debug_level, const char* file_name) { log_file = file_name == NULL ? stdout : fopen(file_name, "w"); if(!log_file) { printf("Unable to open log file %s for writing: %s", file_name, strerror(errno)); } current_log_level = debug_level; } void check(bool f, const char* message) { if (!f) { fprintf(log_file, "%s\n", message); fflush(log_file); print_call_stack(); exit(1); } } void log_fatal(const char* format, ...) { const time_t now = time(NULL); char ctimebuf[32]; const char* buf = ctime_r(&now, ctimebuf); fprintf(log_file, "%-.24s FATAL:", buf); va_list va; va_start(va, format); vfprintf(log_file, format, va); va_end(va); fflush(log_file); print_call_stack(); exit(1); } void slowlog(int lvl, const char* format, ...) { if(lvl <= current_log_level || lvl == LOG_FATAL) { const time_t now = time(NULL); char ctimebuf[32]; const char* buf = ctime_r(&now, ctimebuf); fprintf(log_file, "%-.24s:", buf); va_list va; va_start(va, format); vfprintf(log_file, format, va); va_end(va); } } } // namespace slowhttptest <commit_msg>removed execinfo at all, even for linux<commit_after>/***************************************************************************** * Copyright 2011 Sergey Shekyan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *****************************************************************************/ /***** * Author: Sergey Shekyan [email protected] * Victor Agababov [email protected] * * Slow HTTP attack vulnerability test tool * http://code.google.com/p/slowhttptest/ *****/ #include <ctime> #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "slowlog.h" namespace { static FILE* log_file = NULL; int current_log_level; } namespace slowhttptest { void slowlog_init(int debug_level, const char* file_name) { log_file = file_name == NULL ? stdout : fopen(file_name, "w"); if(!log_file) { printf("Unable to open log file %s for writing: %s", file_name, strerror(errno)); } current_log_level = debug_level; } void check(bool f, const char* message) { if (!f) { fprintf(log_file, "%s\n", message); fflush(log_file); exit(1); } } void log_fatal(const char* format, ...) { const time_t now = time(NULL); char ctimebuf[32]; const char* buf = ctime_r(&now, ctimebuf); fprintf(log_file, "%-.24s FATAL:", buf); va_list va; va_start(va, format); vfprintf(log_file, format, va); va_end(va); fflush(log_file); exit(1); } void slowlog(int lvl, const char* format, ...) { if(lvl <= current_log_level || lvl == LOG_FATAL) { const time_t now = time(NULL); char ctimebuf[32]; const char* buf = ctime_r(&now, ctimebuf); fprintf(log_file, "%-.24s:", buf); va_list va; va_start(va, format); vfprintf(log_file, format, va); va_end(va); } } } // namespace slowhttptest <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <cassert> #include "receiver_fec.h" #include "rtp_receiver_video.h" #include "rtp_utility.h" // RFC 5109 namespace webrtc { ReceiverFEC::ReceiverFEC(const WebRtc_Word32 id, RTPReceiverVideo* owner) : _owner(owner), _fec(new ForwardErrorCorrection(id)), _payloadTypeFEC(-1), _lastFECSeqNum(0), _frameComplete(true) { } ReceiverFEC::~ReceiverFEC() { // Clean up DecodeFEC() while (!_receivedPacketList.empty()){ ForwardErrorCorrection::ReceivedPacket* receivedPacket = _receivedPacketList.front(); delete receivedPacket->pkt; delete receivedPacket; _receivedPacketList.pop_front(); } assert(_receivedPacketList.empty()); if (_fec != NULL) { bool frameComplete = true; _fec->DecodeFEC(&_receivedPacketList, &_recoveredPacketList,_lastFECSeqNum, frameComplete); delete _fec; } } void ReceiverFEC::SetPayloadTypeFEC(const WebRtc_Word8 payloadType) { _payloadTypeFEC = payloadType; } /* 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |F| block PT | timestamp offset | block length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ RFC 2198 RTP Payload for Redundant Audio Data September 1997 The bits in the header are specified as follows: F: 1 bit First bit in header indicates whether another header block follows. If 1 further header blocks follow, if 0 this is the last header block. If 0 there is only 1 byte RED header block PT: 7 bits RTP payload type for this block. timestamp offset: 14 bits Unsigned offset of timestamp of this block relative to timestamp given in RTP header. The use of an unsigned offset implies that redundant data must be sent after the primary data, and is hence a time to be subtracted from the current timestamp to determine the timestamp of the data for which this block is the redundancy. block length: 10 bits Length in bytes of the corresponding data block excluding header. */ WebRtc_Word32 ReceiverFEC::AddReceivedFECPacket( const WebRtcRTPHeader* rtpHeader, const WebRtc_UWord8* incomingRtpPacket, const WebRtc_UWord16 payloadDataLength, bool& FECpacket, bool oldPacket) { if (_payloadTypeFEC == -1) { return -1; } WebRtc_UWord8 REDHeaderLength = 1; // Add to list without RED header, aka a virtual RTP packet // we remove the RED header ForwardErrorCorrection::ReceivedPacket* receivedPacket = new ForwardErrorCorrection::ReceivedPacket; receivedPacket->pkt = new ForwardErrorCorrection::Packet; // get payload type from RED header WebRtc_UWord8 payloadType = incomingRtpPacket[rtpHeader->header.headerLength] & 0x7f; // use the payloadType to decide if it's FEC or coded data if(_payloadTypeFEC == payloadType) { receivedPacket->isFec = true; FECpacket = true; // We don't need to parse old FEC packets. // Old FEC packets are sent to jitter buffer as empty packets in the // callback in rtp_receiver_video. if (oldPacket) return 0; } else { receivedPacket->isFec = false; FECpacket = false; } receivedPacket->lastMediaPktInFrame = rtpHeader->header.markerBit; receivedPacket->seqNum = rtpHeader->header.sequenceNumber; WebRtc_UWord16 blockLength = 0; if(incomingRtpPacket[rtpHeader->header.headerLength] & 0x80) { // f bit set in RED header REDHeaderLength = 4; WebRtc_UWord16 timestampOffset = (incomingRtpPacket[rtpHeader->header.headerLength + 1]) << 8; timestampOffset += incomingRtpPacket[rtpHeader->header.headerLength+2]; timestampOffset = timestampOffset >> 2; if(timestampOffset != 0) { // sanity timestampOffset must be 0 assert(false); return -1; } blockLength = (0x03 & incomingRtpPacket[rtpHeader->header.headerLength + 2]) << 8; blockLength += (incomingRtpPacket[rtpHeader->header.headerLength + 3]); // check next RED header if(incomingRtpPacket[rtpHeader->header.headerLength+4] & 0x80) { // more than 2 blocks in packet not supported assert(false); return -1; } if(blockLength > payloadDataLength - REDHeaderLength) { // block length longer than packet assert(false); return -1; } } ForwardErrorCorrection::ReceivedPacket* secondReceivedPacket = NULL; if (blockLength > 0) { // handle block length, split into 2 packets REDHeaderLength = 5; // copy the RTP header memcpy(receivedPacket->pkt->data, incomingRtpPacket, rtpHeader->header.headerLength); // replace the RED payload type receivedPacket->pkt->data[1] &= 0x80; // reset the payload receivedPacket->pkt->data[1] += payloadType; // set the media payload type // copy the payload data memcpy(receivedPacket->pkt->data + rtpHeader->header.headerLength, incomingRtpPacket + rtpHeader->header.headerLength + REDHeaderLength, blockLength); receivedPacket->pkt->length = blockLength; secondReceivedPacket = new ForwardErrorCorrection::ReceivedPacket; secondReceivedPacket->pkt = new ForwardErrorCorrection::Packet; secondReceivedPacket->isFec = true; secondReceivedPacket->lastMediaPktInFrame = false; secondReceivedPacket->seqNum = rtpHeader->header.sequenceNumber; // copy the FEC payload data memcpy(secondReceivedPacket->pkt->data, incomingRtpPacket + rtpHeader->header.headerLength + REDHeaderLength + blockLength, payloadDataLength - REDHeaderLength - blockLength); secondReceivedPacket->pkt->length = payloadDataLength - REDHeaderLength - blockLength; } else if(receivedPacket->isFec) { // everything behind the RED header memcpy(receivedPacket->pkt->data, incomingRtpPacket + rtpHeader->header.headerLength + REDHeaderLength, payloadDataLength - REDHeaderLength); receivedPacket->pkt->length = payloadDataLength - REDHeaderLength; receivedPacket->ssrc = ModuleRTPUtility::BufferToUWord32(&incomingRtpPacket[8]); } else { // copy the RTP header memcpy(receivedPacket->pkt->data, incomingRtpPacket, rtpHeader->header.headerLength); // replace the RED payload type receivedPacket->pkt->data[1] &= 0x80; // reset the payload receivedPacket->pkt->data[1] += payloadType; // set the media payload type // copy the media payload data memcpy(receivedPacket->pkt->data + rtpHeader->header.headerLength, incomingRtpPacket + rtpHeader->header.headerLength + REDHeaderLength, payloadDataLength - REDHeaderLength); receivedPacket->pkt->length = rtpHeader->header.headerLength + payloadDataLength - REDHeaderLength; } if(receivedPacket->isFec) { AddReceivedFECInfo(rtpHeader, NULL, FECpacket); } if(receivedPacket->pkt->length == 0) { delete receivedPacket->pkt; delete receivedPacket; return 0; } // Send any old media packets to jitter buffer, don't push them onto // received list for FEC decoding (we don't do FEC decoding on old packets). if (oldPacket && receivedPacket->isFec == false) { if (ParseAndReceivePacket(receivedPacket->pkt) != 0) { return -1; } delete receivedPacket->pkt; delete receivedPacket; } else { _receivedPacketList.push_back(receivedPacket); if (secondReceivedPacket) { _receivedPacketList.push_back(secondReceivedPacket); } } return 0; } void ReceiverFEC::AddReceivedFECInfo(const WebRtcRTPHeader* rtpHeader, const WebRtc_UWord8* incomingRtpPacket, bool& FECpacket) { // store the highest FEC seq num received if (_lastFECSeqNum >= rtpHeader->header.sequenceNumber) { if (_lastFECSeqNum > 0xff00 && rtpHeader->header.sequenceNumber < 0x0ff ) { // wrap _lastFECSeqNum = rtpHeader->header.sequenceNumber; } else { // old seqNum } } else { // check for a wrap if(rtpHeader->header.sequenceNumber > 0xff00 && _lastFECSeqNum < 0x0ff ) { // old seqNum } else { _lastFECSeqNum = rtpHeader->header.sequenceNumber; } } if (incomingRtpPacket) { // get payload type from RED header WebRtc_UWord8 payloadType = incomingRtpPacket[rtpHeader->header.headerLength] & 0x7f; // use the payloadType to decide if it's FEC or coded data if(_payloadTypeFEC == payloadType) { FECpacket = true; } else { FECpacket = false; } } } WebRtc_Word32 ReceiverFEC::ProcessReceivedFEC(const bool forceFrameDecode) { if (!_receivedPacketList.empty()) { if (_fec->DecodeFEC(&_receivedPacketList, &_recoveredPacketList, _lastFECSeqNum, _frameComplete) != 0) { return -1; } assert(_receivedPacketList.empty()); } if (forceFrameDecode) { _frameComplete = true; } if (_frameComplete) { while (!_recoveredPacketList.empty()) { ForwardErrorCorrection::RecoveredPacket* recoveredPacket = _recoveredPacketList.front(); if (ParseAndReceivePacket(recoveredPacket->pkt) != 0) { return -1; } delete recoveredPacket->pkt; delete recoveredPacket; _recoveredPacketList.pop_front(); } assert(_recoveredPacketList.empty()); } return 0; } int ReceiverFEC::ParseAndReceivePacket( const ForwardErrorCorrection::Packet* packet) { WebRtcRTPHeader header; memset(&header, 0, sizeof(header)); ModuleRTPUtility::RTPHeaderParser parser(packet->data, packet->length); if (!parser.Parse(header)) { return -1; } if (_owner->ReceiveRecoveredPacketCallback( &header, &packet->data[header.header.headerLength], packet->length - header.header.headerLength) != 0) { return -1; } return 0; } } // namespace webrtc <commit_msg>Removing an assert for a case that can occur when corrupt packets are injected into voice engine. Review URL: https://webrtc-codereview.appspot.com/373004<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <cassert> #include "receiver_fec.h" #include "rtp_receiver_video.h" #include "rtp_utility.h" // RFC 5109 namespace webrtc { ReceiverFEC::ReceiverFEC(const WebRtc_Word32 id, RTPReceiverVideo* owner) : _owner(owner), _fec(new ForwardErrorCorrection(id)), _payloadTypeFEC(-1), _lastFECSeqNum(0), _frameComplete(true) { } ReceiverFEC::~ReceiverFEC() { // Clean up DecodeFEC() while (!_receivedPacketList.empty()){ ForwardErrorCorrection::ReceivedPacket* receivedPacket = _receivedPacketList.front(); delete receivedPacket->pkt; delete receivedPacket; _receivedPacketList.pop_front(); } assert(_receivedPacketList.empty()); if (_fec != NULL) { bool frameComplete = true; _fec->DecodeFEC(&_receivedPacketList, &_recoveredPacketList,_lastFECSeqNum, frameComplete); delete _fec; } } void ReceiverFEC::SetPayloadTypeFEC(const WebRtc_Word8 payloadType) { _payloadTypeFEC = payloadType; } /* 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |F| block PT | timestamp offset | block length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ RFC 2198 RTP Payload for Redundant Audio Data September 1997 The bits in the header are specified as follows: F: 1 bit First bit in header indicates whether another header block follows. If 1 further header blocks follow, if 0 this is the last header block. If 0 there is only 1 byte RED header block PT: 7 bits RTP payload type for this block. timestamp offset: 14 bits Unsigned offset of timestamp of this block relative to timestamp given in RTP header. The use of an unsigned offset implies that redundant data must be sent after the primary data, and is hence a time to be subtracted from the current timestamp to determine the timestamp of the data for which this block is the redundancy. block length: 10 bits Length in bytes of the corresponding data block excluding header. */ WebRtc_Word32 ReceiverFEC::AddReceivedFECPacket( const WebRtcRTPHeader* rtpHeader, const WebRtc_UWord8* incomingRtpPacket, const WebRtc_UWord16 payloadDataLength, bool& FECpacket, bool oldPacket) { if (_payloadTypeFEC == -1) { return -1; } WebRtc_UWord8 REDHeaderLength = 1; // Add to list without RED header, aka a virtual RTP packet // we remove the RED header ForwardErrorCorrection::ReceivedPacket* receivedPacket = new ForwardErrorCorrection::ReceivedPacket; receivedPacket->pkt = new ForwardErrorCorrection::Packet; // get payload type from RED header WebRtc_UWord8 payloadType = incomingRtpPacket[rtpHeader->header.headerLength] & 0x7f; // use the payloadType to decide if it's FEC or coded data if(_payloadTypeFEC == payloadType) { receivedPacket->isFec = true; FECpacket = true; // We don't need to parse old FEC packets. // Old FEC packets are sent to jitter buffer as empty packets in the // callback in rtp_receiver_video. if (oldPacket) return 0; } else { receivedPacket->isFec = false; FECpacket = false; } receivedPacket->lastMediaPktInFrame = rtpHeader->header.markerBit; receivedPacket->seqNum = rtpHeader->header.sequenceNumber; WebRtc_UWord16 blockLength = 0; if(incomingRtpPacket[rtpHeader->header.headerLength] & 0x80) { // f bit set in RED header REDHeaderLength = 4; WebRtc_UWord16 timestampOffset = (incomingRtpPacket[rtpHeader->header.headerLength + 1]) << 8; timestampOffset += incomingRtpPacket[rtpHeader->header.headerLength+2]; timestampOffset = timestampOffset >> 2; if(timestampOffset != 0) { // timestampOffset should be 0, however, this is a valid error case in // the event of garbage payload. return -1; } blockLength = (0x03 & incomingRtpPacket[rtpHeader->header.headerLength + 2]) << 8; blockLength += (incomingRtpPacket[rtpHeader->header.headerLength + 3]); // check next RED header if(incomingRtpPacket[rtpHeader->header.headerLength+4] & 0x80) { // more than 2 blocks in packet not supported assert(false); return -1; } if(blockLength > payloadDataLength - REDHeaderLength) { // block length longer than packet assert(false); return -1; } } ForwardErrorCorrection::ReceivedPacket* secondReceivedPacket = NULL; if (blockLength > 0) { // handle block length, split into 2 packets REDHeaderLength = 5; // copy the RTP header memcpy(receivedPacket->pkt->data, incomingRtpPacket, rtpHeader->header.headerLength); // replace the RED payload type receivedPacket->pkt->data[1] &= 0x80; // reset the payload receivedPacket->pkt->data[1] += payloadType; // set the media payload type // copy the payload data memcpy(receivedPacket->pkt->data + rtpHeader->header.headerLength, incomingRtpPacket + rtpHeader->header.headerLength + REDHeaderLength, blockLength); receivedPacket->pkt->length = blockLength; secondReceivedPacket = new ForwardErrorCorrection::ReceivedPacket; secondReceivedPacket->pkt = new ForwardErrorCorrection::Packet; secondReceivedPacket->isFec = true; secondReceivedPacket->lastMediaPktInFrame = false; secondReceivedPacket->seqNum = rtpHeader->header.sequenceNumber; // copy the FEC payload data memcpy(secondReceivedPacket->pkt->data, incomingRtpPacket + rtpHeader->header.headerLength + REDHeaderLength + blockLength, payloadDataLength - REDHeaderLength - blockLength); secondReceivedPacket->pkt->length = payloadDataLength - REDHeaderLength - blockLength; } else if(receivedPacket->isFec) { // everything behind the RED header memcpy(receivedPacket->pkt->data, incomingRtpPacket + rtpHeader->header.headerLength + REDHeaderLength, payloadDataLength - REDHeaderLength); receivedPacket->pkt->length = payloadDataLength - REDHeaderLength; receivedPacket->ssrc = ModuleRTPUtility::BufferToUWord32(&incomingRtpPacket[8]); } else { // copy the RTP header memcpy(receivedPacket->pkt->data, incomingRtpPacket, rtpHeader->header.headerLength); // replace the RED payload type receivedPacket->pkt->data[1] &= 0x80; // reset the payload receivedPacket->pkt->data[1] += payloadType; // set the media payload type // copy the media payload data memcpy(receivedPacket->pkt->data + rtpHeader->header.headerLength, incomingRtpPacket + rtpHeader->header.headerLength + REDHeaderLength, payloadDataLength - REDHeaderLength); receivedPacket->pkt->length = rtpHeader->header.headerLength + payloadDataLength - REDHeaderLength; } if(receivedPacket->isFec) { AddReceivedFECInfo(rtpHeader, NULL, FECpacket); } if(receivedPacket->pkt->length == 0) { delete receivedPacket->pkt; delete receivedPacket; return 0; } // Send any old media packets to jitter buffer, don't push them onto // received list for FEC decoding (we don't do FEC decoding on old packets). if (oldPacket && receivedPacket->isFec == false) { if (ParseAndReceivePacket(receivedPacket->pkt) != 0) { return -1; } delete receivedPacket->pkt; delete receivedPacket; } else { _receivedPacketList.push_back(receivedPacket); if (secondReceivedPacket) { _receivedPacketList.push_back(secondReceivedPacket); } } return 0; } void ReceiverFEC::AddReceivedFECInfo(const WebRtcRTPHeader* rtpHeader, const WebRtc_UWord8* incomingRtpPacket, bool& FECpacket) { // store the highest FEC seq num received if (_lastFECSeqNum >= rtpHeader->header.sequenceNumber) { if (_lastFECSeqNum > 0xff00 && rtpHeader->header.sequenceNumber < 0x0ff ) { // wrap _lastFECSeqNum = rtpHeader->header.sequenceNumber; } else { // old seqNum } } else { // check for a wrap if(rtpHeader->header.sequenceNumber > 0xff00 && _lastFECSeqNum < 0x0ff ) { // old seqNum } else { _lastFECSeqNum = rtpHeader->header.sequenceNumber; } } if (incomingRtpPacket) { // get payload type from RED header WebRtc_UWord8 payloadType = incomingRtpPacket[rtpHeader->header.headerLength] & 0x7f; // use the payloadType to decide if it's FEC or coded data if(_payloadTypeFEC == payloadType) { FECpacket = true; } else { FECpacket = false; } } } WebRtc_Word32 ReceiverFEC::ProcessReceivedFEC(const bool forceFrameDecode) { if (!_receivedPacketList.empty()) { if (_fec->DecodeFEC(&_receivedPacketList, &_recoveredPacketList, _lastFECSeqNum, _frameComplete) != 0) { return -1; } assert(_receivedPacketList.empty()); } if (forceFrameDecode) { _frameComplete = true; } if (_frameComplete) { while (!_recoveredPacketList.empty()) { ForwardErrorCorrection::RecoveredPacket* recoveredPacket = _recoveredPacketList.front(); if (ParseAndReceivePacket(recoveredPacket->pkt) != 0) { return -1; } delete recoveredPacket->pkt; delete recoveredPacket; _recoveredPacketList.pop_front(); } assert(_recoveredPacketList.empty()); } return 0; } int ReceiverFEC::ParseAndReceivePacket( const ForwardErrorCorrection::Packet* packet) { WebRtcRTPHeader header; memset(&header, 0, sizeof(header)); ModuleRTPUtility::RTPHeaderParser parser(packet->data, packet->length); if (!parser.Parse(header)) { return -1; } if (_owner->ReceiveRecoveredPacketCallback( &header, &packet->data[header.header.headerLength], packet->length - header.header.headerLength) != 0) { return -1; } return 0; } } // namespace webrtc <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Rainer Gericke // ============================================================================= // // WVP TMeasy tire subsystem // // ============================================================================= #include <algorithm> #include <cmath> #include "chrono_models/vehicle/wvp/WVP_TMeasyTire.h" #include "chrono_vehicle/ChVehicleModelData.h" namespace chrono { namespace vehicle { namespace wvp { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const std::string WVP_TMeasyTire::m_meshName = "hmmwv_tire_POV_geom"; const std::string WVP_TMeasyTire::m_meshFile = "hmmwv/hmmwv_tire.obj"; const double WVP_TMeasyTire::m_mass = 71.1; const ChVector<> WVP_TMeasyTire::m_inertia(9.62, 16.84, 9.62); // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- WVP_TMeasyTire::WVP_TMeasyTire(const std::string& name) : ChTMeasyTire(name) { // Set Handling Charecteristics SetTMeasyParams(); // Set nonlinear vertical stiffness std::vector<double> disp, force; disp.push_back(0.01); force.push_back(3276.0); disp.push_back(0.02); force.push_back(6729.0); disp.push_back(0.03); force.push_back(10361.0); disp.push_back(0.04); force.push_back(14171.0); disp.push_back(0.05); force.push_back(18159.0); disp.push_back(0.06); force.push_back(22325.0); disp.push_back(0.07); force.push_back(26670.0); disp.push_back(0.08); force.push_back(31192.0); disp.push_back(0.09); force.push_back(35893.0); disp.push_back(0.10); force.push_back(40772.0); VerticalStiffnessByTable(disp,force); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void WVP_TMeasyTire::SetTMeasyParams() { // Tire Size = 365/80R20 152K unsigned int li = 152; const double in2m = 0.0254; double w = 0.365; double r = 0.8; double rimdia = 20.0 * in2m; GuessTruck80Par(li, // load index w, // tire width r, // aspect ratio rimdia // rim diameter ); } void WVP_TMeasyTire::GenerateCharacteristicPlots(const std::string& dirname) { // Write a plot file (gnuplot) to check the tire characteristics. // Inside gnuplot use the command load 'filename' std::string filename = dirname + "/365_80R20_" + GetName() + ".gpl"; WritePlots(filename, "365/80R20 152K"); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void WVP_TMeasyTire::AddVisualizationAssets(VisualizationType vis) { if (vis == VisualizationType::MESH) { geometry::ChTriangleMeshConnected trimesh; trimesh.LoadWavefrontMesh(vehicle::GetDataFile(m_meshFile), false, false); m_trimesh_shape = std::make_shared<ChTriangleMeshShape>(); m_trimesh_shape->SetMesh(trimesh); m_trimesh_shape->SetName(m_meshName); m_wheel->AddAsset(m_trimesh_shape); } else { ChTMeasyTire::AddVisualizationAssets(vis); } } void WVP_TMeasyTire::RemoveVisualizationAssets() { ChTMeasyTire::RemoveVisualizationAssets(); // Make sure we only remove the assets added by WVP_FialaTire::AddVisualizationAssets. // This is important for the ChTire object because a wheel may add its own assets // to the same body (the spindle/wheel). auto it = std::find(m_wheel->GetAssets().begin(), m_wheel->GetAssets().end(), m_trimesh_shape); if (it != m_wheel->GetAssets().end()) m_wheel->GetAssets().erase(it); } } // end namespace wvp } // end namespace vehicle } // end namespace chrono <commit_msg>TMeasy tire parameters are taken from Pacejka89 as close as possible instead of truck pattern.<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Rainer Gericke // ============================================================================= // // WVP TMeasy tire subsystem // // ============================================================================= #include <algorithm> #include <cmath> #include "chrono_models/vehicle/wvp/WVP_TMeasyTire.h" #include "chrono_vehicle/ChVehicleModelData.h" namespace chrono { namespace vehicle { namespace wvp { // ----------------------------------------------------------------------------- // Static variables // ----------------------------------------------------------------------------- const std::string WVP_TMeasyTire::m_meshName = "hmmwv_tire_POV_geom"; const std::string WVP_TMeasyTire::m_meshFile = "hmmwv/hmmwv_tire.obj"; const double WVP_TMeasyTire::m_mass = 71.1; const ChVector<> WVP_TMeasyTire::m_inertia(9.62, 16.84, 9.62); // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- WVP_TMeasyTire::WVP_TMeasyTire(const std::string& name) : ChTMeasyTire(name) { // Set Handling Charecteristics as close as possible to Pacejka89 model data // Set nonlinear vertical stiffness std::vector<double> disp, force; disp.push_back(0.01); force.push_back(3276.0); disp.push_back(0.02); force.push_back(6729.0); disp.push_back(0.03); force.push_back(10361.0); disp.push_back(0.04); force.push_back(14171.0); disp.push_back(0.05); force.push_back(18159.0); disp.push_back(0.06); force.push_back(22325.0); disp.push_back(0.07); force.push_back(26670.0); disp.push_back(0.08); force.push_back(31192.0); disp.push_back(0.09); force.push_back(35893.0); disp.push_back(0.10); force.push_back(40772.0); VerticalStiffnessByTable(disp,force); double xi = 0.05; // tire damping ratio m_width = 0.372; m_unloaded_radius = 1.096 / 2.0; m_rolling_resistance = 0.015; m_TMeasyCoeff.mu_0 = 0.8; // average tire vertical spring rate double defl = (-m_TMeasyCoeff.cz+sqrt(pow(m_TMeasyCoeff.cz,2) +4.0*m_TMeasyCoeff.czq*m_TMeasyCoeff.pn))/(2.0*m_TMeasyCoeff.czq); double czm = m_TMeasyCoeff.cz+2.0*m_TMeasyCoeff.czq*defl; m_TMeasyCoeff.dz = 2.0*xi*sqrt(czm*WVP_TMeasyTire::m_mass); m_TMeasyCoeff.dfx0_pn = 208983.611609; m_TMeasyCoeff.sxm_pn = 0.104000; m_TMeasyCoeff.fxm_pn = 13832.621098; m_TMeasyCoeff.sxs_pn = 0.500000; m_TMeasyCoeff.fxs_pn = 12541.768777; m_TMeasyCoeff.dfx0_p2n = 442370.170045; m_TMeasyCoeff.sxm_p2n = 0.064000; m_TMeasyCoeff.fxm_p2n = 24576.287112; m_TMeasyCoeff.sxs_p2n = 0.800000; m_TMeasyCoeff.fxs_p2n = 22495.052482; m_TMeasyCoeff.dfy0_pn = 167824.039124; m_TMeasyCoeff.sym_pn = 0.385868; m_TMeasyCoeff.fym_pn = 13201.861871; m_TMeasyCoeff.sys_pn = 0.800000; m_TMeasyCoeff.fys_pn = 12541.768777; m_TMeasyCoeff.dfy0_p2n = 276247.933241; m_TMeasyCoeff.sym_p2n = 0.275446; m_TMeasyCoeff.fym_p2n = 23679.002612; m_TMeasyCoeff.sys_p2n = 1.000000; m_TMeasyCoeff.fys_p2n = 22495.052482; m_TMeasyCoeff.nto0_pn = 0.160000; m_TMeasyCoeff.synto0_pn = 0.200000; m_TMeasyCoeff.syntoE_pn = 0.480000; m_TMeasyCoeff.nto0_p2n = 0.170000; m_TMeasyCoeff.synto0_p2n = 0.200000; m_TMeasyCoeff.syntoE_p2n = 0.500000; } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void WVP_TMeasyTire::SetTMeasyParams() { // Tire Size = 365/80R20 152K unsigned int li = 152; const double in2m = 0.0254; double w = 0.365; double r = 0.8; double rimdia = 20.0 * in2m; GuessTruck80Par(li, // load index w, // tire width r, // aspect ratio rimdia // rim diameter ); } void WVP_TMeasyTire::GenerateCharacteristicPlots(const std::string& dirname) { // Write a plot file (gnuplot) to check the tire characteristics. // Inside gnuplot use the command load 'filename' std::string filename = dirname + "/365_80R20_" + GetName() + ".gpl"; WritePlots(filename, "365/80R20 152K"); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void WVP_TMeasyTire::AddVisualizationAssets(VisualizationType vis) { if (vis == VisualizationType::MESH) { geometry::ChTriangleMeshConnected trimesh; trimesh.LoadWavefrontMesh(vehicle::GetDataFile(m_meshFile), false, false); m_trimesh_shape = std::make_shared<ChTriangleMeshShape>(); m_trimesh_shape->SetMesh(trimesh); m_trimesh_shape->SetName(m_meshName); m_wheel->AddAsset(m_trimesh_shape); } else { ChTMeasyTire::AddVisualizationAssets(vis); } } void WVP_TMeasyTire::RemoveVisualizationAssets() { ChTMeasyTire::RemoveVisualizationAssets(); // Make sure we only remove the assets added by WVP_FialaTire::AddVisualizationAssets. // This is important for the ChTire object because a wheel may add its own assets // to the same body (the spindle/wheel). auto it = std::find(m_wheel->GetAssets().begin(), m_wheel->GetAssets().end(), m_trimesh_shape); if (it != m_wheel->GetAssets().end()) m_wheel->GetAssets().erase(it); } } // end namespace wvp } // end namespace vehicle } // end namespace chrono <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qaudiosystemplugin.h" #include "qaudiopluginloader_p.h" #include <QtCore/qcoreapplication.h> #include <QtGui/qapplication.h> #include <QtCore/qpluginloader.h> #include <QtCore/qfactoryinterface.h> #include <QtCore/qdir.h> #include <QtCore/qdebug.h> QT_BEGIN_NAMESPACE QAudioPluginLoader::QAudioPluginLoader(const char *iid, const QString &location, Qt::CaseSensitivity): m_iid(iid) { m_location = location + "/"; load(); } QAudioPluginLoader::~QAudioPluginLoader() { for (int i = 0; i < m_plugins.count(); i++ ) { delete m_plugins.at(i); } } QStringList QAudioPluginLoader::pluginList() const { #if !defined QT_NO_DEBUG const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0; #endif QStringList paths = QApplication::libraryPaths(); #ifdef QTM_PLUGIN_PATH paths << QLatin1String(QTM_PLUGIN_PATH); #endif #if !defined QT_NO_DEBUG if (showDebug) qDebug() << "Plugin paths:" << paths; #endif //temp variable to avoid multiple identic path QSet<QString> processed; /* Discover a bunch o plugins */ QStringList plugins; /* Enumerate our plugin paths */ for (int i=0; i < paths.count(); i++) { if (processed.contains(paths.at(i))) continue; processed.insert(paths.at(i)); QDir pluginsDir(paths.at(i)+m_location); if (!pluginsDir.exists()) continue; QStringList files = pluginsDir.entryList(QDir::Files); #if !defined QT_NO_DEBUG if (showDebug) qDebug()<<"Looking for plugins in "<<pluginsDir.path()<<files; #endif for (int j=0; j < files.count(); j++) { const QString &file = files.at(j); #if defined(Q_WS_MAEMO_5) if (!file.contains(QLatin1String("n900audio"))) #endif plugins << pluginsDir.absoluteFilePath(file); } } return plugins; } QStringList QAudioPluginLoader::keys() const { QMutexLocker(m_mutex()); QStringList list; for (int i = 0; i < m_plugins.count(); i++) { QAudioSystemPlugin* p = qobject_cast<QAudioSystemPlugin*>(m_plugins.at(i)->instance()); if (p) list << p->keys(); } return list; } QObject* QAudioPluginLoader::instance(QString const &key) { QMutexLocker(mutex()); for (int i = 0; i < m_plugins.count(); i++) { QAudioSystemPlugin* p = qobject_cast<QAudioSystemPlugin*>(m_plugins.at(i)->instance()); if (p && p->keys().contains(key)) return m_plugins.at(i)->instance(); } return 0; } QList<QObject*> QAudioPluginLoader::instances(QString const &key) { QMutexLocker(mutex()); QList<QObject*> list; for (int i = 0; i < m_plugins.count(); i++) { QAudioSystemPlugin* p = qobject_cast<QAudioSystemPlugin*>(m_plugins.at(i)->instance()); if (p && p->keys().contains(key)) list << m_plugins.at(i)->instance(); } return list; } void QAudioPluginLoader::load() { if (!m_plugins.isEmpty()) return; QStringList plugins = pluginList(); for (int i=0; i < plugins.count(); i++) { QPluginLoader* loader = new QPluginLoader(plugins.at(i)); QObject *o = loader->instance(); if (o != 0 && o->qt_metacast(m_iid) != 0) m_plugins.append(loader); else { qWarning() << "QAudioPluginLoader: Failed to load plugin: " << plugins.at(i) << loader->errorString(); } } } QT_END_NAMESPACE <commit_msg>Fix mutex locking in QAudioPluginLoader.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qaudiosystemplugin.h" #include "qaudiopluginloader_p.h" #include <QtCore/qcoreapplication.h> #include <QtGui/qapplication.h> #include <QtCore/qpluginloader.h> #include <QtCore/qfactoryinterface.h> #include <QtCore/qdir.h> #include <QtCore/qdebug.h> QT_BEGIN_NAMESPACE QAudioPluginLoader::QAudioPluginLoader(const char *iid, const QString &location, Qt::CaseSensitivity): m_iid(iid) { m_location = location + "/"; load(); } QAudioPluginLoader::~QAudioPluginLoader() { for (int i = 0; i < m_plugins.count(); i++ ) { delete m_plugins.at(i); } } QStringList QAudioPluginLoader::pluginList() const { #if !defined QT_NO_DEBUG const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0; #endif QStringList paths = QApplication::libraryPaths(); #ifdef QTM_PLUGIN_PATH paths << QLatin1String(QTM_PLUGIN_PATH); #endif #if !defined QT_NO_DEBUG if (showDebug) qDebug() << "Plugin paths:" << paths; #endif //temp variable to avoid multiple identic path QSet<QString> processed; /* Discover a bunch o plugins */ QStringList plugins; /* Enumerate our plugin paths */ for (int i=0; i < paths.count(); i++) { if (processed.contains(paths.at(i))) continue; processed.insert(paths.at(i)); QDir pluginsDir(paths.at(i)+m_location); if (!pluginsDir.exists()) continue; QStringList files = pluginsDir.entryList(QDir::Files); #if !defined QT_NO_DEBUG if (showDebug) qDebug()<<"Looking for plugins in "<<pluginsDir.path()<<files; #endif for (int j=0; j < files.count(); j++) { const QString &file = files.at(j); #if defined(Q_WS_MAEMO_5) if (!file.contains(QLatin1String("n900audio"))) #endif plugins << pluginsDir.absoluteFilePath(file); } } return plugins; } QStringList QAudioPluginLoader::keys() const { QMutexLocker locker(const_cast<QMutex *>(&m_mutex)); QStringList list; for (int i = 0; i < m_plugins.count(); i++) { QAudioSystemPlugin* p = qobject_cast<QAudioSystemPlugin*>(m_plugins.at(i)->instance()); if (p) list << p->keys(); } return list; } QObject* QAudioPluginLoader::instance(QString const &key) { QMutexLocker locker(&m_mutex); for (int i = 0; i < m_plugins.count(); i++) { QAudioSystemPlugin* p = qobject_cast<QAudioSystemPlugin*>(m_plugins.at(i)->instance()); if (p && p->keys().contains(key)) return m_plugins.at(i)->instance(); } return 0; } QList<QObject*> QAudioPluginLoader::instances(QString const &key) { QMutexLocker locker(&m_mutex); QList<QObject*> list; for (int i = 0; i < m_plugins.count(); i++) { QAudioSystemPlugin* p = qobject_cast<QAudioSystemPlugin*>(m_plugins.at(i)->instance()); if (p && p->keys().contains(key)) list << m_plugins.at(i)->instance(); } return list; } void QAudioPluginLoader::load() { if (!m_plugins.isEmpty()) return; QStringList plugins = pluginList(); for (int i=0; i < plugins.count(); i++) { QPluginLoader* loader = new QPluginLoader(plugins.at(i)); QObject *o = loader->instance(); if (o != 0 && o->qt_metacast(m_iid) != 0) m_plugins.append(loader); else { qWarning() << "QAudioPluginLoader: Failed to load plugin: " << plugins.at(i) << loader->errorString(); } } } QT_END_NAMESPACE <|endoftext|>
<commit_before>/* * HLLib * Copyright (C) 2006-2010 Ryan Gregg * 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. */ #include "HLLib.h" #include "ProcStream.h" using namespace HLLib; using namespace HLLib::Streams; CProcStream::CProcStream(hlVoid *pUserData) : bOpened(hlFalse), uiMode(HL_MODE_INVALID), pUserData(pUserData) { } CProcStream::~CProcStream() { this->Close(); } HLStreamType CProcStream::GetType() const { return HL_STREAM_PROC; } const hlChar *CProcStream::GetFileName() const { return ""; } hlBool CProcStream::GetOpened() const { return this->bOpened; } hlUInt CProcStream::GetMode() const { return this->uiMode; } hlBool CProcStream::Open(hlUInt uiMode) { this->Close(); if(pOpenProc == 0) { LastError.SetErrorMessage("pOpenProc not set."); return hlFalse; } if(!pOpenProc(uiMode, this->pUserData)) { LastError.SetErrorMessage("pOpenProc() failed."); return hlFalse; } this->bOpened = hlTrue; this->uiMode = uiMode; return hlTrue; } hlVoid CProcStream::Close() { if(this->bOpened) { if(pCloseProc != 0) { pCloseProc(this->pUserData); } this->bOpened = hlFalse; this->uiMode = HL_MODE_INVALID; } } hlULongLong CProcStream::GetStreamSize() const { if(!this->bOpened) { return 0; } if(pSizeExProc != 0) { return pSizeExProc(this->pUserData); } else if(pSizeProc != 0) { return static_cast<hlULongLong>(pSizeProc(this->pUserData)); } LastError.SetErrorMessage("pSizeProc not set."); return 0; } hlULongLong CProcStream::GetStreamPointer() const { if(!this->bOpened) { return 0; } if(pTellExProc != 0) { return pTellExProc(this->pUserData); } else if(pTellProc != 0) { return static_cast<hlULongLong>(pTellProc(this->pUserData)); } LastError.SetErrorMessage("pTellProc not set."); return 0; } hlULongLong CProcStream::Seek(hlLongLong iOffset, HLSeekMode eSeekMode) { if(!this->bOpened) { return 0; } if(pSeekExProc != 0) { return pSeekExProc(iOffset, eSeekMode, this->pUserData); } else if(pSeekProc != 0) { return static_cast<hlULongLong>(pSeekProc(iOffset, eSeekMode, this->pUserData)); } LastError.SetErrorMessage("pSeekProc not set."); return 0; } hlBool CProcStream::Read(hlChar &cChar) { if(!this->bOpened) { return hlFalse; } if((this->uiMode & HL_MODE_READ) == 0) { LastError.SetErrorMessage("Stream not in read mode."); return hlFalse; } if(pReadProc == 0) { LastError.SetErrorMessage("pReadProc not set."); return hlFalse; } hlUInt uiBytesRead = pReadProc(&cChar, 1, this->pUserData); if(uiBytesRead == 0) { LastError.SetErrorMessage("pReadProc() failed."); } return uiBytesRead == 1; } hlUInt CProcStream::Read(hlVoid *lpData, hlUInt uiBytes) { if(!this->bOpened) { return 0; } if((this->uiMode & HL_MODE_READ) == 0) { LastError.SetErrorMessage("Stream not in read mode."); return 0; } if(pReadProc == 0) { LastError.SetErrorMessage("pReadProc not set."); return 0; } hlUInt uiBytesRead = pReadProc(lpData, uiBytes, this->pUserData); if(uiBytesRead == 0) { LastError.SetErrorMessage("pReadProc() failed."); } return uiBytesRead; } hlBool CProcStream::Write(hlChar cChar) { if(!this->bOpened) { return hlFalse; } if((this->uiMode & HL_MODE_WRITE) == 0) { LastError.SetErrorMessage("Stream not in write mode."); return hlFalse; } if(pWriteProc == 0) { LastError.SetErrorMessage("pWriteProc not set."); return hlFalse; } hlUInt uiBytesWritten = pWriteProc(&cChar, 1, this->pUserData); if(uiBytesWritten == 0) { LastError.SetErrorMessage("pWriteProc() failed."); } return uiBytesWritten == 1; } hlUInt CProcStream::Write(const hlVoid *lpData, hlUInt uiBytes) { if(!this->bOpened) { return 0; } if((this->uiMode & HL_MODE_WRITE) == 0) { LastError.SetErrorMessage("Stream not in write mode."); return 0; } if(pWriteProc == 0) { LastError.SetErrorMessage("pWriteProc not set."); return 0; } hlUInt uiBytesWritten = pWriteProc(lpData, uiBytes, this->pUserData); if(uiBytesWritten == 0) { LastError.SetErrorMessage("pWriteProc() failed."); } return uiBytesWritten; } <commit_msg>Delete ProcStream.cpp<commit_after><|endoftext|>
<commit_before> #pragma once #include <cstdlib> #include <string> namespace principia { namespace base { #define STRINGIFY(X) #X #define STRINGIFY_EXPANSION(X) STRINGIFY(X) // See http://goo.gl/2EVxN4 for a partial overview of compiler detection and // version macros. We cannot use |COMPILER_MSVC| because it conflicts with // a macro in the benchmark library, so the macros have obnoxiously long names. // TODO(phl): See whether that |COMPILER_MSVC| macro can be removed from port.h. #if defined(_MSC_VER) && defined(__clang__) #define PRINCIPIA_COMPILER_CLANG_CL 1 char const* const CompilerName = "Clang-cl"; char const* const CompilerVersion = __VERSION__; #elif defined(__clang__) #define PRINCIPIA_COMPILER_CLANG 1 char const* const CompilerName = "Clang"; char const* const CompilerVersion = __VERSION__; #elif defined(_MSC_VER) #define PRINCIPIA_COMPILER_MSVC 1 char const* const CompilerName = "Microsoft Visual C++"; char const* const CompilerVersion = STRINGIFY_EXPANSION(_MSC_FULL_VER); # if _HAS_CXX20 # define PRINCIPIA_COMPILER_MSVC_HAS_CXX20 1 # endif #elif defined(__ICC) || defined(__INTEL_COMPILER) #define PRINCIPIA_COMPILER_ICC 1 char const* const CompilerName = "Intel C++ Compiler"; char const* const CompilerVersion = __VERSION__; #elif defined(__GNUC__) #define PRINCIPIA_COMPILER_GCC 1 char const* const CompilerName = "G++"; char const* const CompilerVersion = __VERSION__; #else #error "What is this, Borland C++?" #endif #if defined(__APPLE__) #define OS_MACOSX 1 char const* const OperatingSystem = "OS X"; #elif defined(__linux__) #define OS_LINUX 1 char const* const OperatingSystem = "Linux"; #elif defined(__FreeBSD__) #define OS_FREEBSD 1 char const* const OperatingSystem = "FreeBSD"; #elif defined(_WIN32) #define OS_WIN 1 char const* const OperatingSystem = "Windows"; #else #error "Try OS/360." #endif #if defined(__i386) || defined(_M_IX86) #define ARCH_CPU_X86_FAMILY 1 #define ARCH_CPU_X86 1 #define ARCH_CPU_32_BITS 1 #define ARCH_CPU_LITTLE_ENDIAN 1 char const* const Architecture = "x86"; #elif defined(_M_X64) || defined(__x86_64__) #define ARCH_CPU_X86_FAMILY 1 #define ARCH_CPU_X86_64 1 #define ARCH_CPU_64_BITS 1 #define ARCH_CPU_LITTLE_ENDIAN 1 char const* const Architecture = "x86-64"; #else #error "Have you tried a Cray-1?" #endif // DLL-exported functions for interfacing with Platform Invocation Services. #if defined(PRINCIPIA_DLL) # error "PRINCIPIA_DLL already defined" #else # if OS_WIN # if PRINCIPIA_DLL_IMPORT # define PRINCIPIA_DLL __declspec(dllimport) # else # define PRINCIPIA_DLL __declspec(dllexport) # endif # else # define PRINCIPIA_DLL __attribute__((visibility("default"))) # endif #endif // A function for use on control paths that don't return a value, typically // because they end with a |LOG(FATAL)|. #if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL [[noreturn]] #elif PRINCIPIA_COMPILER_MSVC __declspec(noreturn) #elif PRINCIPIA_COMPILER_ICC __attribute__((noreturn)) #else #error "What compiler is this?" #endif inline void noreturn() { std::exit(0); } // Used to force inlining. #if PRINCIPIA_COMPILER_CLANG || \ PRINCIPIA_COMPILER_CLANG_CL || \ PRINCIPIA_COMPILER_GCC # define FORCE_INLINE(specifiers) [[gnu::always_inline]] specifiers // NOLINT #elif PRINCIPIA_COMPILER_MSVC # define FORCE_INLINE(specifiers) specifiers __forceinline #elif PRINCIPIA_COMPILER_ICC # define FORCE_INLINE(specifiers) __attribute__((always_inline)) #else # error "What compiler is this?" #endif // Used to emit the function signature. #if PRINCIPIA_COMPILER_CLANG || \ PRINCIPIA_COMPILER_CLANG_CL || \ PRINCIPIA_COMPILER_GCC # define FUNCTION_SIGNATURE __PRETTY_FUNCTION__ #elif PRINCIPIA_COMPILER_MSVC # define FUNCTION_SIGNATURE __FUNCSIG__ #else # error "What compiler is this?" #endif // We assume that the processor is at least a Prescott since we only support // 64-bit architectures. #define PRINCIPIA_USE_SSE3_INTRINSICS !_DEBUG #define PRINCIPIA_USE_FMA_IF_AVAILABLE !_DEBUG // Set this to 1 to test analytical series based on piecewise Poisson series. #define PRINCIPIA_CONTINUOUS_TRAJECTORY_SUPPORTS_PIECEWISE_POISSON_SERIES 0 // Thread-safety analysis. #if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL # define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) # define EXCLUDES(...) \ THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) # define REQUIRES(...) \ THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) # define REQUIRES_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) #else # define EXCLUDES(x) # define REQUIRES(x) # define REQUIRES_SHARED(x) #endif // Unicode. #if OS_WIN # define UNICODE_PATH(x) u ## x #else # define UNICODE_PATH(x) u8 ## x #endif #define NAMED(expression) u8 ## #expression << ": " << (expression) // Needed to circumvent lint warnings in constexpr functions where CHECK_LT and // friends cannot be used. #define CONSTEXPR_CHECK(condition) CHECK(condition) #define CONSTEXPR_DCHECK(condition) DCHECK(condition) // Lexicographic comparison (v1, v2, v3) ≥ (w1, w2, w3). #define VERSION_GE(v1, v2, v3, w1, w2, w3) \ ((v1) > (w1) || ((v1) == (w1) && (v2) > (w2)) || \ ((v1) == (w1) && (v2) == (w2) && (v3) >= (w3))) #define CLANG_VERSION_GE(major, minor, patchlevel) \ VERSION_GE(__clang_major__, \ __clang_minor__, \ __clang_patchlevel__, \ major, \ minor, \ patchlevel) // Clang for some reason doesn't like FP arithmetic that yields infinities by // overflow (as opposed to division by zero, which the standard explicitly // prohibits) in constexpr code (MSVC and GCC are fine with that). This will be // fixed in Clang 9.0.0, all hail zygoloid. #if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL # if OS_MACOSX # define PRINCIPIA_MAY_SIGNAL_OVERFLOW_IN_CONSTEXPR_ARITHMETIC \ CLANG_VERSION_GE(11, 0, 3) # else # define PRINCIPIA_MAY_SIGNAL_OVERFLOW_IN_CONSTEXPR_ARITHMETIC \ CLANG_VERSION_GE(9, 0, 0) # endif #else # define PRINCIPIA_MAY_SIGNAL_OVERFLOW_IN_CONSTEXPR_ARITHMETIC 1 #endif #if PRINCIPIA_MAY_SIGNAL_OVERFLOW_IN_CONSTEXPR_ARITHMETIC # define CONSTEXPR_INFINITY constexpr #else # define CONSTEXPR_INFINITY const #endif #if PRINCIPIA_COMPILER_MSVC #define MSVC_ONLY_TEST(test_name) test_name #else #define MSVC_ONLY_TEST(test_name) DISABLED_##test_name #endif // For templates in macro parameters. #define TEMPLATE(...) template<__VA_ARGS__> // For circumventing // https://developercommunity.visualstudio.com/content/problem/1256363/operator-call-incorrectly-marked-as-ambiguous-with.html. #if PRINCIPIA_COMPILER_MSVC_HAS_CXX20 #define PRINCIPIA_MAX(l, r) ((l) > (r) ? (l) : (r)) #define PRINCIPIA_MAX3(x1, x2, x3) \ PRINCIPIA_MAX((x1), PRINCIPIA_MAX((x2), (x3))) #define PRINCIPIA_MAX4(x1, x2, x3, x4) \ PRINCIPIA_MAX((x1), PRINCIPIA_MAX((x2), PRINCIPIA_MAX((x3), (x4)))) #else #define PRINCIPIA_MAX(l, r) std::max((l), (r)) #define PRINCIPIA_MAX3(x1, x2, x3) std::max({(x1), (x2), (x3)}) #define PRINCIPIA_MAX4(x1, x2, x3, x4) std::max({(x1), (x2), (x3), (x4)}) #endif // Forward declaration of a class or struct declared in an internal namespace // according to #602. // Usage: // FORWARD_DECLARE_FROM(p1, struct, T); // FORWARD_DECLARE_FROM(p2, TEMPLATE(int i) class, U); #define FORWARD_DECLARE_FROM(package_name, \ template_and_class_key, \ declared_name) \ namespace internal_##package_name { \ template_and_class_key declared_name; \ } \ using internal_##package_name::declared_name #define FORWARD_DECLARE_FUNCTION_FROM(package_name, \ template_and_result, \ declared_name, \ parameters) \ namespace internal_##package_name { \ template_and_result declared_name parameters; \ } \ using internal_##package_name::declared_name } // namespace base } // namespace principia <commit_msg>Stoopid lint.<commit_after> #pragma once #include <cstdlib> #include <string> namespace principia { namespace base { #define STRINGIFY(X) #X #define STRINGIFY_EXPANSION(X) STRINGIFY(X) // See http://goo.gl/2EVxN4 for a partial overview of compiler detection and // version macros. We cannot use |COMPILER_MSVC| because it conflicts with // a macro in the benchmark library, so the macros have obnoxiously long names. // TODO(phl): See whether that |COMPILER_MSVC| macro can be removed from port.h. #if defined(_MSC_VER) && defined(__clang__) #define PRINCIPIA_COMPILER_CLANG_CL 1 char const* const CompilerName = "Clang-cl"; char const* const CompilerVersion = __VERSION__; #elif defined(__clang__) #define PRINCIPIA_COMPILER_CLANG 1 char const* const CompilerName = "Clang"; char const* const CompilerVersion = __VERSION__; #elif defined(_MSC_VER) #define PRINCIPIA_COMPILER_MSVC 1 char const* const CompilerName = "Microsoft Visual C++"; char const* const CompilerVersion = STRINGIFY_EXPANSION(_MSC_FULL_VER); # if _HAS_CXX20 # define PRINCIPIA_COMPILER_MSVC_HAS_CXX20 1 # endif #elif defined(__ICC) || defined(__INTEL_COMPILER) #define PRINCIPIA_COMPILER_ICC 1 char const* const CompilerName = "Intel C++ Compiler"; char const* const CompilerVersion = __VERSION__; #elif defined(__GNUC__) #define PRINCIPIA_COMPILER_GCC 1 char const* const CompilerName = "G++"; char const* const CompilerVersion = __VERSION__; #else #error "What is this, Borland C++?" #endif #if defined(__APPLE__) #define OS_MACOSX 1 char const* const OperatingSystem = "OS X"; #elif defined(__linux__) #define OS_LINUX 1 char const* const OperatingSystem = "Linux"; #elif defined(__FreeBSD__) #define OS_FREEBSD 1 char const* const OperatingSystem = "FreeBSD"; #elif defined(_WIN32) #define OS_WIN 1 char const* const OperatingSystem = "Windows"; #else #error "Try OS/360." #endif #if defined(__i386) || defined(_M_IX86) #define ARCH_CPU_X86_FAMILY 1 #define ARCH_CPU_X86 1 #define ARCH_CPU_32_BITS 1 #define ARCH_CPU_LITTLE_ENDIAN 1 char const* const Architecture = "x86"; #elif defined(_M_X64) || defined(__x86_64__) #define ARCH_CPU_X86_FAMILY 1 #define ARCH_CPU_X86_64 1 #define ARCH_CPU_64_BITS 1 #define ARCH_CPU_LITTLE_ENDIAN 1 char const* const Architecture = "x86-64"; #else #error "Have you tried a Cray-1?" #endif // DLL-exported functions for interfacing with Platform Invocation Services. #if defined(PRINCIPIA_DLL) # error "PRINCIPIA_DLL already defined" #else # if OS_WIN # if PRINCIPIA_DLL_IMPORT # define PRINCIPIA_DLL __declspec(dllimport) # else # define PRINCIPIA_DLL __declspec(dllexport) # endif # else # define PRINCIPIA_DLL __attribute__((visibility("default"))) # endif #endif // A function for use on control paths that don't return a value, typically // because they end with a |LOG(FATAL)|. #if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL [[noreturn]] #elif PRINCIPIA_COMPILER_MSVC __declspec(noreturn) #elif PRINCIPIA_COMPILER_ICC __attribute__((noreturn)) #else #error "What compiler is this?" #endif inline void noreturn() { std::exit(0); } // Used to force inlining. #if PRINCIPIA_COMPILER_CLANG || \ PRINCIPIA_COMPILER_CLANG_CL || \ PRINCIPIA_COMPILER_GCC # define FORCE_INLINE(specifiers) [[gnu::always_inline]] specifiers // NOLINT #elif PRINCIPIA_COMPILER_MSVC # define FORCE_INLINE(specifiers) specifiers __forceinline #elif PRINCIPIA_COMPILER_ICC # define FORCE_INLINE(specifiers) __attribute__((always_inline)) #else # error "What compiler is this?" #endif // Used to emit the function signature. #if PRINCIPIA_COMPILER_CLANG || \ PRINCIPIA_COMPILER_CLANG_CL || \ PRINCIPIA_COMPILER_GCC # define FUNCTION_SIGNATURE __PRETTY_FUNCTION__ #elif PRINCIPIA_COMPILER_MSVC # define FUNCTION_SIGNATURE __FUNCSIG__ #else # error "What compiler is this?" #endif // We assume that the processor is at least a Prescott since we only support // 64-bit architectures. #define PRINCIPIA_USE_SSE3_INTRINSICS !_DEBUG #define PRINCIPIA_USE_FMA_IF_AVAILABLE !_DEBUG // Set this to 1 to test analytical series based on piecewise Poisson series. #define PRINCIPIA_CONTINUOUS_TRAJECTORY_SUPPORTS_PIECEWISE_POISSON_SERIES 0 // Thread-safety analysis. #if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL # define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) # define EXCLUDES(...) \ THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) # define REQUIRES(...) \ THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) # define REQUIRES_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) #else # define EXCLUDES(x) # define REQUIRES(x) # define REQUIRES_SHARED(x) #endif // Unicode. #if OS_WIN # define UNICODE_PATH(x) u ## x #else # define UNICODE_PATH(x) u8 ## x #endif #define NAMED(expression) u8 ## #expression << ": " << (expression) // Needed to circumvent lint warnings in constexpr functions where CHECK_LT and // friends cannot be used. #define CONSTEXPR_CHECK(condition) CHECK(condition) #define CONSTEXPR_DCHECK(condition) DCHECK(condition) // Lexicographic comparison (v1, v2, v3) ≥ (w1, w2, w3). #define VERSION_GE(v1, v2, v3, w1, w2, w3) \ ((v1) > (w1) || ((v1) == (w1) && (v2) > (w2)) || \ ((v1) == (w1) && (v2) == (w2) && (v3) >= (w3))) #define CLANG_VERSION_GE(major, minor, patchlevel) \ VERSION_GE(__clang_major__, \ __clang_minor__, \ __clang_patchlevel__, \ major, \ minor, \ patchlevel) // Clang for some reason doesn't like FP arithmetic that yields infinities by // overflow (as opposed to division by zero, which the standard explicitly // prohibits) in constexpr code (MSVC and GCC are fine with that). This will be // fixed in Clang 9.0.0, all hail zygoloid. #if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL # if OS_MACOSX # define PRINCIPIA_MAY_SIGNAL_OVERFLOW_IN_CONSTEXPR_ARITHMETIC \ CLANG_VERSION_GE(11, 0, 3) # else # define PRINCIPIA_MAY_SIGNAL_OVERFLOW_IN_CONSTEXPR_ARITHMETIC \ CLANG_VERSION_GE(9, 0, 0) # endif #else # define PRINCIPIA_MAY_SIGNAL_OVERFLOW_IN_CONSTEXPR_ARITHMETIC 1 #endif #if PRINCIPIA_MAY_SIGNAL_OVERFLOW_IN_CONSTEXPR_ARITHMETIC # define CONSTEXPR_INFINITY constexpr #else # define CONSTEXPR_INFINITY const #endif #if PRINCIPIA_COMPILER_MSVC #define MSVC_ONLY_TEST(test_name) test_name #else #define MSVC_ONLY_TEST(test_name) DISABLED_##test_name #endif // For templates in macro parameters. #define TEMPLATE(...) template<__VA_ARGS__> // For circumventing // https://developercommunity.visualstudio.com/content/problem/1256363/operator-call-incorrectly-marked-as-ambiguous-with.html. #if PRINCIPIA_COMPILER_MSVC_HAS_CXX20 #define PRINCIPIA_MAX(l, r) ((l) > (r) ? (l) : (r)) #define PRINCIPIA_MAX3(x1, x2, x3) \ PRINCIPIA_MAX((x1), PRINCIPIA_MAX((x2), (x3))) #define PRINCIPIA_MAX4(x1, x2, x3, x4) \ PRINCIPIA_MAX((x1), PRINCIPIA_MAX((x2), PRINCIPIA_MAX((x3), (x4)))) #else #define PRINCIPIA_MAX(l, r) std::max((l), (r)) #define PRINCIPIA_MAX3(x1, x2, x3) std::max({(x1), (x2), (x3)}) #define PRINCIPIA_MAX4(x1, x2, x3, x4) std::max({(x1), (x2), (x3), (x4)}) #endif // Forward declaration of a class or struct declared in an internal namespace // according to #602. // Usage: // FORWARD_DECLARE_FROM(p1, struct, T); // FORWARD_DECLARE_FROM(p2, TEMPLATE(int i) class, U); #define FORWARD_DECLARE_FROM(package_name, \ template_and_class_key, \ declared_name) \ namespace internal_##package_name { \ template_and_class_key declared_name; \ } \ using internal_##package_name::declared_name #define FORWARD_DECLARE_FUNCTION_FROM(package_name, \ template_and_result, \ declared_name, \ parameters) \ namespace internal_##package_name { \ template_and_result declared_name parameters; \ } \ using internal_##package_name::declared_name } // namespace base } // namespace principia <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "OgreMaterialDefines.h" #include "CoreStringUtils.h" #include "LoggingFunctions.h" #include <Engine/Core/StringUtils.h> namespace Tundra { namespace Ogre { // MaterialBlock MaterialBlock::MaterialBlock(MaterialBlock *parent_, MaterialPart part_, int t, int p, int tu) : parent(parent_), part(part_), technique(t), pass(p), textureUnit(tu) { } MaterialBlock::~MaterialBlock() { for(uint i=0; i<blocks.Size(); ++i) delete blocks[i]; blocks.Clear(); } bool MaterialBlock::IsSupported() { return (part != MP_Unsupported); } uint MaterialBlock::NumChildren(MaterialPart part) const { uint num = 0; foreach(const MaterialBlock *block, blocks) { if (block->part == part) num++; } return num; } uint MaterialBlock::NumTechniques() const { return NumChildren(MP_Technique); } uint MaterialBlock::NumPasses() const { return NumChildren(MP_Pass); } uint MaterialBlock::NumTextureUnits() const { return NumChildren(MP_TextureUnit); } MaterialBlock *MaterialBlock::Technique(uint index) const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_Technique && block->technique == static_cast<int>(index)) return block; } return nullptr; } MaterialBlock *MaterialBlock::Pass(uint index) const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_Pass && block->pass == static_cast<int>(index)) return block; } return nullptr; } MaterialBlock *MaterialBlock::TextureUnit(uint index) const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_TextureUnit && block->textureUnit == static_cast<int>(index)) return block; } return nullptr; } MaterialBlock *MaterialBlock::VertexProgram() const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_VertexProgram) return block; } return nullptr; } MaterialBlock *MaterialBlock::FragmentProgram() const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_FragmentProgram) return block; } return nullptr; } uint MaterialBlock::Num(const StringHash &name) const { MaterialProperties::ConstIterator iter = properties.Find(name); if (iter != properties.End()) return iter->second_.Size(); return 0; } bool MaterialBlock::Has(const StringHash &name) const { return (Num(name) > 0); } String MaterialBlock::StringValue(const StringHash &name, const String &defaultValue, uint index) const { MaterialProperties::ConstIterator iter = properties.Find(name); if (iter != properties.End() && index < iter->second_.Size()) return iter->second_[index]; return defaultValue; } StringVector MaterialBlock::StringVectorValue(const StringHash &name, uint index) const { String value = StringValue(name, "", index).Trimmed(); StringVector parts = (!value.Empty() ? value.Split(' ') : StringVector()); // Remove empty parts to correctly parse "1.0 1.0 1.0 1.0" type of values for(auto iter = parts.Begin(); iter != parts.End();) { *iter = iter->Trimmed(); if (iter->Empty()) iter = parts.Erase(iter); else iter++; } return parts; } Urho3D::Vector2 MaterialBlock::Vector2Value(const StringHash &name, const Urho3D::Vector2 &defaultValue, uint index) const { StringVector parts = StringVectorValue(name, index); if (parts.Size() >= 2) return Urho3D::Vector2(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1])); return defaultValue; } Urho3D::Vector3 MaterialBlock::Vector3Value(const StringHash &name, const Urho3D::Vector3 &defaultValue, uint index) const { StringVector parts = StringVectorValue(name, index); if (parts.Size() >= 3) return Urho3D::Vector3(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2])); return defaultValue; } Urho3D::Vector4 MaterialBlock::Vector4Value(const StringHash &name, const Urho3D::Vector4 &defaultValue, uint index) const { StringVector parts = StringVectorValue(name, index); if (parts.Size() >= 4) return Urho3D::Vector4(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2]), Urho3D::ToFloat(parts[3])); return defaultValue; } Urho3D::Color MaterialBlock::ColorValue(const StringHash &name, const Urho3D::Color &defaultValue, uint index) const { StringVector parts = StringVectorValue(name, index); if (parts.Size() >= 3) { Urho3D::Color color(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2])); if (parts.Size() >= 4) color.a_ = Urho3D::ToFloat(parts[3]); return color; } return defaultValue; } bool MaterialBlock::BooleanValue(const StringHash &name, bool defaultValue, uint index) const { String value = StringValue(name, "", index).Trimmed(); if (value.Compare("on", false) == 0 || value.Compare("enabled", false) == 0 || value.Compare("true", false) == 0 || value.Compare("1", false) == 0) return true; else if (value.Compare("off", false) == 0 || value.Compare("disabled", false) == 0 || value.Compare("false", false) == 0 || value.Compare("0", false) == 0) return false; return defaultValue; } void MaterialBlock::Dump(bool recursive, uint indentation) { String ind = ""; while(ind.Length() < indentation) ind += " "; LogInfoF("%s%s '%s'", ind.CString(), MaterialPartToString(part).CString(), id.CString()); indentation += 2; while(ind.Length() < indentation) ind += " "; for (auto iter = properties.Begin(); iter != properties.End(); ++iter) { const StringVector &values = iter->second_; if (!values.Empty()) { for (uint vi=0; vi<values.Size(); ++vi) { if (vi == 0) LogInfoF("%s%s '%s'", ind.CString(), PadString(propertyNames[iter->first_], 20).CString(), values[vi].CString()); else LogInfoF("%s%s '%s'", ind.CString(), propertyNames[iter->first_].CString(), values[vi].CString()); } } } if (recursive) { for (auto iter = blocks.Begin(); iter != blocks.End(); ++iter) (*iter)->Dump(recursive, indentation); } indentation -= 2; if (indentation == 0) LogInfo(""); } // MaterialParser MaterialParser::MaterialParser() : root(0) { } MaterialParser::~MaterialParser() { SAFE_DELETE(root); } String MaterialParser::Error() const { return state.error; } bool MaterialParser::Parse(const char *data_, uint lenght_) { data = String(data_, lenght_); pos = 0; lineNum = 0; SAFE_DELETE(root); for(;;) { if (!ProcessLine()) break; } // Make root safe even on failure if (!root) root = new MaterialBlock(); return (state.error.Length() == 0); } void MaterialParser::Advance() { uint endPos = data.Find('\n', pos); if (endPos == String::NPOS || endPos < pos) { pos = String::NPOS; return; } // Empty line with only \n at the start else if (endPos == pos) { pos += 1; line = ""; return; } line = data.Substring(pos, endPos - pos - (data[endPos-1] == '\r' ? 1 : 0)).Trimmed(); pos = endPos + 1; lineNum++; } void MaterialParser::SkipBlock() { uint endPos = data.Find('}', pos); if (endPos == String::NPOS || endPos < pos) { state.error = Urho3D::ToString("Failed to find Block scope end '}', started looking from index %d", pos); pos = String::NPOS; return; } // There is a newline after found '}' advance over it. pos = endPos + 1; Advance(); } bool IsBlockIndentifier(const StringHash &hash) { return (hash == Material::Block::Material || hash == Material::Block::Technique || hash == Material::Block::Pass || hash == Material::Block::TextureUnit || hash == Material::Block::VertexProgram || hash == Material::Block::FragmentProgram || hash == Material::Block::DefaultParameters); } bool MaterialParser::ProcessLine() { // Read next line Advance(); // No more lines? if (pos == String::NPOS) return false; else if (line.Empty()) return true; /*if (lineNum < 10) PrintRaw(" " + String(lineNum) + " '" + line + "'\n"); else PrintRaw(String(lineNum) + " '" + line + "'\n");*/ // Filter comments. Spec only allows single line comments. if (line.Length() > 1 && line[0] == '/' && line[1] == '/') return true; // Block scope end if (line[0] == '}') { // Material not yet started if (!state.block) return true; // Store parsed block to parent if (state.block->parent) state.block->parent->blocks.Push(state.block); // If traversed back to root we are done. /// @todo If we want to parse multiple materials from a single file change this logic. state.block = state.block->parent; return (state.block != 0); } // Block scope start else if (line[0] == '{') { // Material not yet started if (!state.block) return true; // Skip invalid blocks if (!state.block || !state.block->IsSupported()) SkipBlock(); return true; } // Split to "<key> <value>" from the first space. // Note that value can contain spaces, it is stored as is. uint splitPos = line.Find(' '); String keyStr = (splitPos == String::NPOS ? line : line.Substring(0, splitPos).ToLower()); StringHash key(keyStr); String value = (splitPos == String::NPOS ? "" : line.Substring(splitPos+1)); // Do not begin default_params block if material not started yet if (key == Material::Block::DefaultParameters && !state.block) return true; // Is this a new block scope identifier? if (IsBlockIndentifier(key)) { MaterialPart part = MP_Unsupported; // Detect block type if (key == Material::Block::Material) { /// @todo http://www.ogre3d.org/docs/manual/manual_25.html#Script-Inheritance part = MP_Material; state.technique = -1; state.pass = -1; state.textureUnit = -1; } else if (key == Material::Block::Technique) { part = MP_Technique; state.technique++; state.pass = -1; state.textureUnit = -1; } else if (key == Material::Block::Pass) { part = MP_Pass; state.pass++; state.textureUnit = -1; } else if (key == Material::Block::TextureUnit) { part = MP_TextureUnit; state.textureUnit++; } else if (key == Material::Block::VertexProgram) part = MP_VertexProgram; else if (key == Material::Block::FragmentProgram) part = MP_FragmentProgram; else if (key == Material::Block::DefaultParameters) part = MP_DefaultParameters; state.block = new MaterialBlock(state.block, part, state.technique, state.pass, state.textureUnit); state.block->id = value; if (!root && part == MP_Material) root = state.block; //LogInfoF(" tech %d pass %d tu %d", state.block->technique, state.block->pass, state.block->textureUnit); return true; } else if (splitPos == String::NPOS) { state.error = Urho3D::ToString("Ogre::MaterialParser: Invalid script tokens '%s' on line %d before column %d", line.CString(), lineNum, pos); return false; } // Material not yet started if (!state.block) return true; // Add property to current block state.block->propertyNames[key] = keyStr; state.block->properties[key].Push(value); return true; } } } <commit_msg>MaterialParser: Allow invalid ogre material lines where there is no value for a key. These properties will be skipped but wont be a fatal error for the material as a whole.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "OgreMaterialDefines.h" #include "CoreStringUtils.h" #include "LoggingFunctions.h" #include <Engine/Core/StringUtils.h> namespace Tundra { namespace Ogre { // MaterialBlock MaterialBlock::MaterialBlock(MaterialBlock *parent_, MaterialPart part_, int t, int p, int tu) : parent(parent_), part(part_), technique(t), pass(p), textureUnit(tu) { } MaterialBlock::~MaterialBlock() { for(uint i=0; i<blocks.Size(); ++i) delete blocks[i]; blocks.Clear(); } bool MaterialBlock::IsSupported() { return (part != MP_Unsupported); } uint MaterialBlock::NumChildren(MaterialPart part) const { uint num = 0; foreach(const MaterialBlock *block, blocks) { if (block->part == part) num++; } return num; } uint MaterialBlock::NumTechniques() const { return NumChildren(MP_Technique); } uint MaterialBlock::NumPasses() const { return NumChildren(MP_Pass); } uint MaterialBlock::NumTextureUnits() const { return NumChildren(MP_TextureUnit); } MaterialBlock *MaterialBlock::Technique(uint index) const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_Technique && block->technique == static_cast<int>(index)) return block; } return nullptr; } MaterialBlock *MaterialBlock::Pass(uint index) const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_Pass && block->pass == static_cast<int>(index)) return block; } return nullptr; } MaterialBlock *MaterialBlock::TextureUnit(uint index) const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_TextureUnit && block->textureUnit == static_cast<int>(index)) return block; } return nullptr; } MaterialBlock *MaterialBlock::VertexProgram() const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_VertexProgram) return block; } return nullptr; } MaterialBlock *MaterialBlock::FragmentProgram() const { foreach(MaterialBlock *block, blocks) { if (block->part == MP_FragmentProgram) return block; } return nullptr; } uint MaterialBlock::Num(const StringHash &name) const { MaterialProperties::ConstIterator iter = properties.Find(name); if (iter != properties.End()) return iter->second_.Size(); return 0; } bool MaterialBlock::Has(const StringHash &name) const { return (Num(name) > 0); } String MaterialBlock::StringValue(const StringHash &name, const String &defaultValue, uint index) const { MaterialProperties::ConstIterator iter = properties.Find(name); if (iter != properties.End() && index < iter->second_.Size()) return iter->second_[index]; return defaultValue; } StringVector MaterialBlock::StringVectorValue(const StringHash &name, uint index) const { String value = StringValue(name, "", index).Trimmed(); StringVector parts = (!value.Empty() ? value.Split(' ') : StringVector()); // Remove empty parts to correctly parse "1.0 1.0 1.0 1.0" type of values for(auto iter = parts.Begin(); iter != parts.End();) { *iter = iter->Trimmed(); if (iter->Empty()) iter = parts.Erase(iter); else iter++; } return parts; } Urho3D::Vector2 MaterialBlock::Vector2Value(const StringHash &name, const Urho3D::Vector2 &defaultValue, uint index) const { StringVector parts = StringVectorValue(name, index); if (parts.Size() >= 2) return Urho3D::Vector2(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1])); return defaultValue; } Urho3D::Vector3 MaterialBlock::Vector3Value(const StringHash &name, const Urho3D::Vector3 &defaultValue, uint index) const { StringVector parts = StringVectorValue(name, index); if (parts.Size() >= 3) return Urho3D::Vector3(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2])); return defaultValue; } Urho3D::Vector4 MaterialBlock::Vector4Value(const StringHash &name, const Urho3D::Vector4 &defaultValue, uint index) const { StringVector parts = StringVectorValue(name, index); if (parts.Size() >= 4) return Urho3D::Vector4(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2]), Urho3D::ToFloat(parts[3])); return defaultValue; } Urho3D::Color MaterialBlock::ColorValue(const StringHash &name, const Urho3D::Color &defaultValue, uint index) const { StringVector parts = StringVectorValue(name, index); if (parts.Size() >= 3) { Urho3D::Color color(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2])); if (parts.Size() >= 4) color.a_ = Urho3D::ToFloat(parts[3]); return color; } return defaultValue; } bool MaterialBlock::BooleanValue(const StringHash &name, bool defaultValue, uint index) const { String value = StringValue(name, "", index).Trimmed(); if (value.Compare("on", false) == 0 || value.Compare("enabled", false) == 0 || value.Compare("true", false) == 0 || value.Compare("1", false) == 0) return true; else if (value.Compare("off", false) == 0 || value.Compare("disabled", false) == 0 || value.Compare("false", false) == 0 || value.Compare("0", false) == 0) return false; return defaultValue; } void MaterialBlock::Dump(bool recursive, uint indentation) { String ind = ""; while(ind.Length() < indentation) ind += " "; LogInfoF("%s%s '%s'", ind.CString(), MaterialPartToString(part).CString(), id.CString()); indentation += 2; while(ind.Length() < indentation) ind += " "; for (auto iter = properties.Begin(); iter != properties.End(); ++iter) { const StringVector &values = iter->second_; if (!values.Empty()) { for (uint vi=0; vi<values.Size(); ++vi) { if (vi == 0) LogInfoF("%s%s '%s'", ind.CString(), PadString(propertyNames[iter->first_], 20).CString(), values[vi].CString()); else LogInfoF("%s%s '%s'", ind.CString(), propertyNames[iter->first_].CString(), values[vi].CString()); } } } if (recursive) { for (auto iter = blocks.Begin(); iter != blocks.End(); ++iter) (*iter)->Dump(recursive, indentation); } indentation -= 2; if (indentation == 0) LogInfo(""); } // MaterialParser MaterialParser::MaterialParser() : root(0) { } MaterialParser::~MaterialParser() { SAFE_DELETE(root); } String MaterialParser::Error() const { return state.error; } bool MaterialParser::Parse(const char *data_, uint lenght_) { data = String(data_, lenght_); pos = 0; lineNum = 0; SAFE_DELETE(root); for(;;) { if (!ProcessLine()) break; } // Make root safe even on failure if (!root) root = new MaterialBlock(); return (state.error.Length() == 0); } void MaterialParser::Advance() { uint endPos = data.Find('\n', pos); if (endPos == String::NPOS || endPos < pos) { pos = String::NPOS; return; } // Empty line with only \n at the start else if (endPos == pos) { pos += 1; line = ""; return; } line = data.Substring(pos, endPos - pos - (data[endPos-1] == '\r' ? 1 : 0)).Trimmed(); pos = endPos + 1; lineNum++; } void MaterialParser::SkipBlock() { uint endPos = data.Find('}', pos); if (endPos == String::NPOS || endPos < pos) { state.error = Urho3D::ToString("Failed to find Block scope end '}', started looking from index %d", pos); pos = String::NPOS; return; } // There is a newline after found '}' advance over it. pos = endPos + 1; Advance(); } bool IsBlockIndentifier(const StringHash &hash) { return (hash == Material::Block::Material || hash == Material::Block::Technique || hash == Material::Block::Pass || hash == Material::Block::TextureUnit || hash == Material::Block::VertexProgram || hash == Material::Block::FragmentProgram || hash == Material::Block::DefaultParameters); } bool MaterialParser::ProcessLine() { // Read next line Advance(); // No more lines? if (pos == String::NPOS) return false; else if (line.Empty()) return true; /*if (lineNum < 10) PrintRaw(" " + String(lineNum) + " '" + line + "'\n"); else PrintRaw(String(lineNum) + " '" + line + "'\n");*/ // Filter comments. Spec only allows single line comments. if (line.Length() > 1 && line[0] == '/' && line[1] == '/') return true; // Block scope end if (line[0] == '}') { // Material not yet started if (!state.block) return true; // Store parsed block to parent if (state.block->parent) state.block->parent->blocks.Push(state.block); // If traversed back to root we are done. /// @todo If we want to parse multiple materials from a single file change this logic. state.block = state.block->parent; return (state.block != 0); } // Block scope start else if (line[0] == '{') { // Material not yet started if (!state.block) return true; // Skip invalid blocks if (!state.block || !state.block->IsSupported()) SkipBlock(); return true; } // Split to "<key> <value>" from the first space. // Note that value can contain spaces, it is stored as is. uint splitPos = line.Find(' '); String keyStr = (splitPos == String::NPOS ? line : line.Substring(0, splitPos).ToLower()); StringHash key(keyStr); String value = (splitPos == String::NPOS ? "" : line.Substring(splitPos+1)); // Do not begin default_params block if material not started yet if (key == Material::Block::DefaultParameters && !state.block) return true; // Is this a new block scope identifier? if (IsBlockIndentifier(key)) { MaterialPart part = MP_Unsupported; // Detect block type if (key == Material::Block::Material) { /// @todo http://www.ogre3d.org/docs/manual/manual_25.html#Script-Inheritance part = MP_Material; state.technique = -1; state.pass = -1; state.textureUnit = -1; } else if (key == Material::Block::Technique) { part = MP_Technique; state.technique++; state.pass = -1; state.textureUnit = -1; } else if (key == Material::Block::Pass) { part = MP_Pass; state.pass++; state.textureUnit = -1; } else if (key == Material::Block::TextureUnit) { part = MP_TextureUnit; state.textureUnit++; } else if (key == Material::Block::VertexProgram) part = MP_VertexProgram; else if (key == Material::Block::FragmentProgram) part = MP_FragmentProgram; else if (key == Material::Block::DefaultParameters) part = MP_DefaultParameters; state.block = new MaterialBlock(state.block, part, state.technique, state.pass, state.textureUnit); state.block->id = value; if (!root && part == MP_Material) root = state.block; //LogInfoF(" tech %d pass %d tu %d", state.block->technique, state.block->pass, state.block->textureUnit); return true; } else if (value.Empty()) { LogWarningF("Ogre::MaterialParser: Invalid script token '%s' without a value on line %d before column %d", keyStr.CString(), lineNum, pos); return true; } // Material not yet started if (!state.block) return true; // Add property to current block state.block->propertyNames[key] = keyStr; state.block->properties[key].Push(value); return true; } } } <|endoftext|>
<commit_before>#include <stdio.h> #include <errno.h> #include <string.h> #include <sys/time.h> #include <assert.h> #include <string> #include <vector> #include "crs_header.h" #define MKL_ILP64 #define FLEXCOMPLEX #define MKL_INT crs_idx_t #include <mkl.h> inline static float time_diff(struct timeval time1, struct timeval time2) { return time2.tv_sec - time1.tv_sec + ((float)(time2.tv_usec - time1.tv_usec))/1000000; } void test_spmv(const std::vector<crs_idx_t> &row_idxs, const std::vector<crs_idx_t> &col_vec, const std::vector<double> &val_vec, size_t num_rows, size_t num_cols) { printf("test SpMV\n"); std::vector<double> in_vec(num_cols); printf("init input vector of %ld entries\n", in_vec.size()); #pragma omp parallel for for (size_t i = 0; i < in_vec.size(); i++) in_vec[i] = 1; std::vector<double> out_vec(num_rows); printf("init output vector of %ld entries\n", out_vec.size()); crs_idx_t nrowA = num_rows; assert(col_vec.size() == val_vec.size()); assert(row_idxs.back() == val_vec.size()); struct timeval start, end; gettimeofday(&start, NULL); assert(nrowA == row_idxs.size() - 1); mkl_cspblas_dcsrgemv("N", &nrowA, val_vec.data(), row_idxs.data(), col_vec.data(), in_vec.data(), out_vec.data()); gettimeofday(&end, NULL); printf("SpMV takes %.3fs\n", time_diff(start, end)); assert(out_vec.size() == row_idxs.size() - 1); for (size_t i = 0; i < out_vec.size(); i++) { assert(out_vec[i] == row_idxs[i + 1] - row_idxs[i]); } } void test_spmm(const std::vector<crs_idx_t> &row_idxs, const std::vector<crs_idx_t> &col_vec, const std::vector<double> &val_vec, size_t num_rows, size_t num_cols, int num_vecs) { printf("test SpMM on %d vectors\n", num_vecs); std::vector<double> in_vec(num_cols * num_vecs); printf("init input vector of %ld entries\n", in_vec.size()); // The input matrix is organized in row major. #pragma omp parallel for for (size_t i = 0; i < in_vec.size(); i++) { size_t col_idx = i % num_vecs; in_vec[i] = col_idx + 1; } std::vector<double> out_vec(num_rows * num_vecs); printf("init output vector of %ld entries\n", out_vec.size()); assert(col_vec.size() == val_vec.size()); assert(row_idxs.back() == val_vec.size()); struct timeval start, end; gettimeofday(&start, NULL); crs_idx_t nrowA = num_rows; crs_idx_t ncolC = num_vecs; crs_idx_t ncolA = num_cols; double alpha = 1; double beta = 0; mkl_dcsrmm("N", &nrowA, &ncolC, &ncolA, &alpha, "G C", val_vec.data(), col_vec.data(), row_idxs.data(), row_idxs.data() + 1, in_vec.data(), &ncolC, &beta, out_vec.data(), &ncolC); gettimeofday(&end, NULL); printf("SpMM takes %.3fs\n", time_diff(start, end)); assert(out_vec.size() == (row_idxs.size() - 1) * num_vecs); // The output matrix is organized in row major. for (size_t i = 0; i < out_vec.size(); i++) { size_t col_idx = i % num_vecs; size_t row_idx = i / num_vecs; assert(out_vec[i] == (row_idxs[row_idx + 1] - row_idxs[row_idx]) * (col_idx + 1)); } } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "test-mkl_multiply crs_file\n"); exit(1); } std::string crs_file = argv[1]; FILE *f = fopen(crs_file.c_str(), "r"); if (f == NULL) { fprintf(stderr, "can't open %s: %s\n", crs_file.c_str(), strerror(errno)); exit(1); } crs_header header; size_t ret = fread(&header, sizeof(header), 1, f); if (ret == 0) { fprintf(stderr, "can't read header: %s\n", strerror(errno)); exit(1); } size_t num_rows = header.get_num_rows(); size_t num_cols = header.get_num_cols(); size_t nnz = header.get_num_non_zeros(); printf("There are %ld rows, %ld cols and %ld nnz\n", num_rows, num_cols, nnz); std::vector<crs_idx_t> row_idxs(num_rows + 1); std::vector<crs_idx_t> col_vec(nnz); printf("read CRS\n"); ret = fread(row_idxs.data(), row_idxs.size() * sizeof(row_idxs[0]), 1, f); if (ret == 0) { fprintf(stderr, "can't read row idxs: %s\n", strerror(errno)); exit(1); } ret = fread(col_vec.data(), col_vec.size() * sizeof(col_vec[0]), 1, f); if (ret == 0) { fprintf(stderr, "can't read col idxs: %s\n", strerror(errno)); exit(1); } for (size_t i = 0; i < col_vec.size(); i++) assert(col_vec[i] < num_cols); std::vector<double> val_vec(nnz); printf("Create value vector of %ld entries for the adj matrix\n", val_vec.size()); #pragma omp parallel for for (size_t i = 0; i < val_vec.size(); i++) val_vec[i] = 1; test_spmv(row_idxs, col_vec, val_vec, num_rows, num_cols); for (int num_vecs = 1; num_vecs <= 16; num_vecs *= 2) test_spmm(row_idxs, col_vec, val_vec, num_rows, num_cols, num_vecs); } <commit_msg>[Matrix]: improve MKL SpMM test.<commit_after>#include <stdio.h> #include <errno.h> #include <string.h> #include <sys/time.h> #include <assert.h> #include <string> #include <vector> #include "crs_header.h" #define MKL_ILP64 #define FLEXCOMPLEX #define MKL_INT crs_idx_t #include <mkl.h> inline static float time_diff(struct timeval time1, struct timeval time2) { return time2.tv_sec - time1.tv_sec + ((float)(time2.tv_usec - time1.tv_usec))/1000000; } void test_spmv(const std::vector<crs_idx_t> &row_idxs, const std::vector<crs_idx_t> &col_vec, const std::vector<double> &val_vec, size_t num_rows, size_t num_cols) { printf("test SpMV\n"); std::vector<double> in_vec(num_cols); printf("init input vector of %ld entries\n", in_vec.size()); #pragma omp parallel for for (size_t i = 0; i < in_vec.size(); i++) in_vec[i] = 1; std::vector<double> out_vec(num_rows); printf("init output vector of %ld entries\n", out_vec.size()); crs_idx_t nrowA = num_rows; assert(col_vec.size() == val_vec.size()); assert(row_idxs.back() == val_vec.size()); struct timeval start, end; gettimeofday(&start, NULL); assert(nrowA == row_idxs.size() - 1); mkl_cspblas_dcsrgemv("N", &nrowA, val_vec.data(), row_idxs.data(), col_vec.data(), in_vec.data(), out_vec.data()); gettimeofday(&end, NULL); printf("SpMV takes %.3fs\n", time_diff(start, end)); assert(out_vec.size() == row_idxs.size() - 1); for (size_t i = 0; i < out_vec.size(); i++) { assert(out_vec[i] == row_idxs[i + 1] - row_idxs[i]); } } void test_spmm(const std::vector<crs_idx_t> &row_idxs, const std::vector<crs_idx_t> &col_vec, const std::vector<double> &val_vec, size_t num_rows, size_t num_cols, int num_vecs) { printf("test SpMM on %d vectors\n", num_vecs); std::vector<double> in_vec(num_cols * num_vecs); printf("init input vector of %ld entries\n", in_vec.size()); // The input matrix is organized in row major. #pragma omp parallel for for (size_t i = 0; i < in_vec.size(); i++) { size_t col_idx = i % num_vecs; in_vec[i] = col_idx + 1; } std::vector<double> out_vec(num_rows * num_vecs); printf("init output vector of %ld entries\n", out_vec.size()); assert(col_vec.size() == val_vec.size()); assert(row_idxs.back() == val_vec.size()); struct timeval start, end; gettimeofday(&start, NULL); crs_idx_t nrowA = num_rows; crs_idx_t ncolC = num_vecs; crs_idx_t ncolA = num_cols; double alpha = 1; double beta = 0; mkl_dcsrmm("N", &nrowA, &ncolC, &ncolA, &alpha, "G C", val_vec.data(), col_vec.data(), row_idxs.data(), row_idxs.data() + 1, in_vec.data(), &ncolC, &beta, out_vec.data(), &ncolC); gettimeofday(&end, NULL); printf("SpMM takes %.3fs\n", time_diff(start, end)); assert(out_vec.size() == (row_idxs.size() - 1) * num_vecs); // The output matrix is organized in row major. #pragma omp parallel for for (size_t i = 0; i < out_vec.size(); i++) { size_t col_idx = i % num_vecs; size_t row_idx = i / num_vecs; assert(out_vec[i] == (row_idxs[row_idx + 1] - row_idxs[row_idx]) * (col_idx + 1)); } } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "test-mkl_multiply crs_file\n"); exit(1); } std::string crs_file = argv[1]; FILE *f = fopen(crs_file.c_str(), "r"); if (f == NULL) { fprintf(stderr, "can't open %s: %s\n", crs_file.c_str(), strerror(errno)); exit(1); } crs_header header; size_t ret = fread(&header, sizeof(header), 1, f); if (ret == 0) { fprintf(stderr, "can't read header: %s\n", strerror(errno)); exit(1); } size_t num_rows = header.get_num_rows(); size_t num_cols = header.get_num_cols(); size_t nnz = header.get_num_non_zeros(); printf("There are %ld rows, %ld cols and %ld nnz\n", num_rows, num_cols, nnz); std::vector<crs_idx_t> row_idxs(num_rows + 1); std::vector<crs_idx_t> col_vec(nnz); printf("read CRS\n"); ret = fread(row_idxs.data(), row_idxs.size() * sizeof(row_idxs[0]), 1, f); if (ret == 0) { fprintf(stderr, "can't read row idxs: %s\n", strerror(errno)); exit(1); } ret = fread(col_vec.data(), col_vec.size() * sizeof(col_vec[0]), 1, f); if (ret == 0) { fprintf(stderr, "can't read col idxs: %s\n", strerror(errno)); exit(1); } for (size_t i = 0; i < col_vec.size(); i++) assert(col_vec[i] < num_cols); std::vector<double> val_vec(nnz); printf("Create value vector of %ld entries for the adj matrix\n", val_vec.size()); #pragma omp parallel for for (size_t i = 0; i < val_vec.size(); i++) val_vec[i] = 1; for (size_t i = 0; i < 5; i++) test_spmv(row_idxs, col_vec, val_vec, num_rows, num_cols); for (int num_vecs = 2; num_vecs <= 128; num_vecs *= 2) { for (size_t i = 0; i < 5; i++) test_spmm(row_idxs, col_vec, val_vec, num_rows, num_cols, num_vecs); } } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SampleCode.h" #include "SkAnimTimer.h" #include "SkView.h" #include "SkCanvas.h" #include "SkDrawable.h" #include "SkPath.h" #include "SkRandom.h" #include "SkRSXform.h" #include "SkSurface.h" static SkImage* make_atlas(int atlasSize, int cellSize) { SkImageInfo info = SkImageInfo::MakeN32Premul(atlasSize, atlasSize); SkAutoTUnref<SkSurface> surface(SkSurface::NewRaster(info)); SkCanvas* canvas = surface->getCanvas(); SkPaint paint; paint.setAntiAlias(true); SkRandom rand; const SkScalar half = cellSize * SK_ScalarHalf; const char* s = "01234567890!@#$%^&*=+<>?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; paint.setTextSize(28); paint.setTextAlign(SkPaint::kCenter_Align); int i = 0; for (int y = 0; y < atlasSize; y += cellSize) { for (int x = 0; x < atlasSize; x += cellSize) { paint.setColor(rand.nextU()); paint.setAlpha(0xFF); int index = i % strlen(s); canvas->drawText(&s[index], 1, x + half, y + half + half/2, paint); i += 1; } } return surface->newImageSnapshot(); } class DrawAtlasDrawable : public SkDrawable { enum { kMaxScale = 2, kCellSize = 32, kAtlasSize = 512, }; struct Rec { SkPoint fCenter; SkVector fVelocity; SkScalar fScale; SkScalar fDScale; SkScalar fRadian; SkScalar fDRadian; SkScalar fAlpha; SkScalar fDAlpha; void advance(const SkRect& bounds) { fCenter += fVelocity; if (fCenter.fX > bounds.right()) { SkASSERT(fVelocity.fX > 0); fVelocity.fX = -fVelocity.fX; } else if (fCenter.fX < bounds.left()) { SkASSERT(fVelocity.fX < 0); fVelocity.fX = -fVelocity.fX; } if (fCenter.fY > bounds.bottom()) { if (fVelocity.fY > 0) { fVelocity.fY = -fVelocity.fY; } } else if (fCenter.fY < bounds.top()) { if (fVelocity.fY < 0) { fVelocity.fY = -fVelocity.fY; } } fScale += fDScale; if (fScale > 2 || fScale < SK_Scalar1/2) { fDScale = -fDScale; } fRadian += fDRadian; fRadian = SkScalarMod(fRadian, 2 * SK_ScalarPI); fAlpha += fDAlpha; if (fAlpha > 1) { fAlpha = 1; fDAlpha = -fDAlpha; } else if (fAlpha < 0) { fAlpha = 0; fDAlpha = -fDAlpha; } } SkRSXform asRSXform() const { return SkRSXform::MakeFromRadians(fScale, fRadian, fCenter.x(), fCenter.y(), SkScalarHalf(kCellSize), SkScalarHalf(kCellSize)); } }; enum { N = 256, }; SkAutoTUnref<SkImage> fAtlas; Rec fRec[N]; SkRect fTex[N]; SkRect fBounds; bool fUseColors; public: DrawAtlasDrawable(const SkRect& r) : fBounds(r), fUseColors(false) { SkRandom rand; fAtlas.reset(make_atlas(kAtlasSize, kCellSize)); const SkScalar kMaxSpeed = 5; const SkScalar cell = SkIntToScalar(kCellSize); int i = 0; for (int y = 0; y < kAtlasSize; y += kCellSize) { for (int x = 0; x < kAtlasSize; x += kCellSize) { const SkScalar sx = SkIntToScalar(x); const SkScalar sy = SkIntToScalar(y); fTex[i].setXYWH(sx, sy, cell, cell); fRec[i].fCenter.set(sx + cell/2, sy + 3*cell/4); fRec[i].fVelocity.fX = rand.nextSScalar1() * kMaxSpeed; fRec[i].fVelocity.fY = rand.nextSScalar1() * kMaxSpeed; fRec[i].fScale = 1; fRec[i].fDScale = rand.nextSScalar1() / 16; fRec[i].fRadian = 0; fRec[i].fDRadian = rand.nextSScalar1() / 8; fRec[i].fAlpha = rand.nextUScalar1(); fRec[i].fDAlpha = rand.nextSScalar1() / 10; i += 1; } } } void toggleUseColors() { fUseColors = !fUseColors; } protected: void onDraw(SkCanvas* canvas) override { SkRSXform xform[N]; SkColor colors[N]; for (int i = 0; i < N; ++i) { fRec[i].advance(fBounds); xform[i] = fRec[i].asRSXform(); if (fUseColors) { colors[i] = SkColorSetARGB((int)(fRec[i].fAlpha * 0xFF), 0xFF, 0xFF, 0xFF); } } SkPaint paint; paint.setFilterQuality(kLow_SkFilterQuality); const SkRect cull = this->getBounds(); const SkColor* colorsPtr = fUseColors ? colors : NULL; canvas->drawAtlas(fAtlas, xform, fTex, colorsPtr, N, SkXfermode::kModulate_Mode, &cull, &paint); } SkRect onGetBounds() override { const SkScalar border = kMaxScale * kCellSize; SkRect r = fBounds; r.outset(border, border); return r; } private: typedef SkDrawable INHERITED; }; class DrawAtlasView : public SampleView { DrawAtlasDrawable* fDrawable; public: DrawAtlasView() { fDrawable = new DrawAtlasDrawable(SkRect::MakeWH(640, 480)); } ~DrawAtlasView() override { fDrawable->unref(); } protected: bool onQuery(SkEvent* evt) override { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "DrawAtlas"); return true; } SkUnichar uni; if (SampleCode::CharQ(*evt, &uni)) { switch (uni) { case 'C': fDrawable->toggleUseColors(); this->inval(NULL); return true; default: break; } } return this->INHERITED::onQuery(evt); } void onDrawContent(SkCanvas* canvas) override { canvas->drawDrawable(fDrawable); this->inval(NULL); } #if 0 // TODO: switch over to use this for our animation bool onAnimate(const SkAnimTimer& timer) override { SkScalar angle = SkDoubleToScalar(fmod(timer.secs() * 360 / 24, 360)); fAnimatingDrawable->setSweep(angle); return true; } #endif private: typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new DrawAtlasView; } static SkViewRegister reg(MyFactory); <commit_msg>simulate drawatlas<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SampleCode.h" #include "SkAnimTimer.h" #include "SkView.h" #include "SkCanvas.h" #include "SkDrawable.h" #include "SkPath.h" #include "SkRandom.h" #include "SkRSXform.h" #include "SkSurface.h" typedef void (*DrawAtlasProc)(SkCanvas*, SkImage*, const SkRSXform[], const SkRect[], const SkColor[], int, const SkRect*, const SkPaint*); static void draw_atlas(SkCanvas* canvas, SkImage* atlas, const SkRSXform xform[], const SkRect tex[], const SkColor colors[], int count, const SkRect* cull, const SkPaint* paint) { canvas->drawAtlas(atlas, xform, tex, colors, count, SkXfermode::kModulate_Mode, cull, paint); } static void draw_atlas_sim(SkCanvas* canvas, SkImage* atlas, const SkRSXform xform[], const SkRect tex[], const SkColor colors[], int count, const SkRect* cull, const SkPaint* paint) { for (int i = 0; i < count; ++i) { SkMatrix matrix; matrix.setRSXform(xform[i]); canvas->save(); canvas->concat(matrix); canvas->drawImageRect(atlas, &tex[i], tex[i].makeOffset(-tex[i].x(), -tex[i].y()), paint); canvas->restore(); } } static SkImage* make_atlas(int atlasSize, int cellSize) { SkImageInfo info = SkImageInfo::MakeN32Premul(atlasSize, atlasSize); SkAutoTUnref<SkSurface> surface(SkSurface::NewRaster(info)); SkCanvas* canvas = surface->getCanvas(); SkPaint paint; paint.setAntiAlias(true); SkRandom rand; const SkScalar half = cellSize * SK_ScalarHalf; const char* s = "01234567890!@#$%^&*=+<>?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; paint.setTextSize(28); paint.setTextAlign(SkPaint::kCenter_Align); int i = 0; for (int y = 0; y < atlasSize; y += cellSize) { for (int x = 0; x < atlasSize; x += cellSize) { paint.setColor(rand.nextU()); paint.setAlpha(0xFF); int index = i % strlen(s); canvas->drawText(&s[index], 1, x + half, y + half + half/2, paint); i += 1; } } return surface->newImageSnapshot(); } class DrawAtlasDrawable : public SkDrawable { enum { kMaxScale = 2, kCellSize = 32, kAtlasSize = 512, }; struct Rec { SkPoint fCenter; SkVector fVelocity; SkScalar fScale; SkScalar fDScale; SkScalar fRadian; SkScalar fDRadian; SkScalar fAlpha; SkScalar fDAlpha; void advance(const SkRect& bounds) { fCenter += fVelocity; if (fCenter.fX > bounds.right()) { SkASSERT(fVelocity.fX > 0); fVelocity.fX = -fVelocity.fX; } else if (fCenter.fX < bounds.left()) { SkASSERT(fVelocity.fX < 0); fVelocity.fX = -fVelocity.fX; } if (fCenter.fY > bounds.bottom()) { if (fVelocity.fY > 0) { fVelocity.fY = -fVelocity.fY; } } else if (fCenter.fY < bounds.top()) { if (fVelocity.fY < 0) { fVelocity.fY = -fVelocity.fY; } } fScale += fDScale; if (fScale > 2 || fScale < SK_Scalar1/2) { fDScale = -fDScale; } fRadian += fDRadian; fRadian = SkScalarMod(fRadian, 2 * SK_ScalarPI); fAlpha += fDAlpha; if (fAlpha > 1) { fAlpha = 1; fDAlpha = -fDAlpha; } else if (fAlpha < 0) { fAlpha = 0; fDAlpha = -fDAlpha; } } SkRSXform asRSXform() const { return SkRSXform::MakeFromRadians(fScale, fRadian, fCenter.x(), fCenter.y(), SkScalarHalf(kCellSize), SkScalarHalf(kCellSize)); } }; DrawAtlasProc fProc; enum { N = 256, }; SkAutoTUnref<SkImage> fAtlas; Rec fRec[N]; SkRect fTex[N]; SkRect fBounds; bool fUseColors; public: DrawAtlasDrawable(DrawAtlasProc proc, const SkRect& r) : fProc(proc), fBounds(r), fUseColors(false) { SkRandom rand; fAtlas.reset(make_atlas(kAtlasSize, kCellSize)); const SkScalar kMaxSpeed = 5; const SkScalar cell = SkIntToScalar(kCellSize); int i = 0; for (int y = 0; y < kAtlasSize; y += kCellSize) { for (int x = 0; x < kAtlasSize; x += kCellSize) { const SkScalar sx = SkIntToScalar(x); const SkScalar sy = SkIntToScalar(y); fTex[i].setXYWH(sx, sy, cell, cell); fRec[i].fCenter.set(sx + cell/2, sy + 3*cell/4); fRec[i].fVelocity.fX = rand.nextSScalar1() * kMaxSpeed; fRec[i].fVelocity.fY = rand.nextSScalar1() * kMaxSpeed; fRec[i].fScale = 1; fRec[i].fDScale = rand.nextSScalar1() / 16; fRec[i].fRadian = 0; fRec[i].fDRadian = rand.nextSScalar1() / 8; fRec[i].fAlpha = rand.nextUScalar1(); fRec[i].fDAlpha = rand.nextSScalar1() / 10; i += 1; } } } void toggleUseColors() { fUseColors = !fUseColors; } protected: void onDraw(SkCanvas* canvas) override { SkRSXform xform[N]; SkColor colors[N]; for (int i = 0; i < N; ++i) { fRec[i].advance(fBounds); xform[i] = fRec[i].asRSXform(); if (fUseColors) { colors[i] = SkColorSetARGB((int)(fRec[i].fAlpha * 0xFF), 0xFF, 0xFF, 0xFF); } } SkPaint paint; paint.setFilterQuality(kLow_SkFilterQuality); const SkRect cull = this->getBounds(); const SkColor* colorsPtr = fUseColors ? colors : NULL; fProc(canvas, fAtlas, xform, fTex, colorsPtr, N, &cull, &paint); } SkRect onGetBounds() override { const SkScalar border = kMaxScale * kCellSize; SkRect r = fBounds; r.outset(border, border); return r; } private: typedef SkDrawable INHERITED; }; class DrawAtlasView : public SampleView { const char* fName; DrawAtlasDrawable* fDrawable; public: DrawAtlasView(const char name[], DrawAtlasProc proc) : fName(name) { fDrawable = new DrawAtlasDrawable(proc, SkRect::MakeWH(640, 480)); } ~DrawAtlasView() override { fDrawable->unref(); } protected: bool onQuery(SkEvent* evt) override { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, fName); return true; } SkUnichar uni; if (SampleCode::CharQ(*evt, &uni)) { switch (uni) { case 'C': fDrawable->toggleUseColors(); this->inval(NULL); return true; default: break; } } return this->INHERITED::onQuery(evt); } void onDrawContent(SkCanvas* canvas) override { canvas->drawDrawable(fDrawable); this->inval(NULL); } #if 0 // TODO: switch over to use this for our animation bool onAnimate(const SkAnimTimer& timer) override { SkScalar angle = SkDoubleToScalar(fmod(timer.secs() * 360 / 24, 360)); fAnimatingDrawable->setSweep(angle); return true; } #endif private: typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_SAMPLE( return new DrawAtlasView("DrawAtlas", draw_atlas); ) DEF_SAMPLE( return new DrawAtlasView("DrawAtlasSim", draw_atlas_sim); ) <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_util.h" #include "media/filters/adaptive_demuxer.h" namespace media { // // AdaptiveDemuxerStream // AdaptiveDemuxerStream::AdaptiveDemuxerStream( StreamVector const& streams, int initial_stream) : streams_(streams), current_stream_index_(initial_stream), bitstream_converter_enabled_(false) { DCheckSanity(); } void AdaptiveDemuxerStream::DCheckSanity() { // We only carry out sanity checks in debug mode. if (!logging::DEBUG_MODE) return; DCHECK(streams_[current_stream_index_].get()); bool non_null_stream_seen = false; Type type; const MediaFormat* media_format = NULL; for (size_t i = 0; i < streams_.size(); ++i) { if (!streams_[i]) continue; if (!non_null_stream_seen) { non_null_stream_seen = true; type = streams_[i]->type(); media_format = &streams_[i]->media_format(); } else { DCHECK_EQ(streams_[i]->type(), type); DCHECK(streams_[i]->media_format() == *media_format); } } } AdaptiveDemuxerStream::~AdaptiveDemuxerStream() { base::AutoLock auto_lock(lock_); current_stream_index_ = -1; streams_.clear(); } DemuxerStream* AdaptiveDemuxerStream::current_stream() { base::AutoLock auto_lock(lock_); return streams_[current_stream_index_]; } void AdaptiveDemuxerStream::Read(Callback1<Buffer*>::Type* read_callback) { current_stream()->Read(read_callback); } AVStream* AdaptiveDemuxerStream::GetAVStream() { return current_stream()->GetAVStream(); } DemuxerStream::Type AdaptiveDemuxerStream::type() { return current_stream()->type(); } const MediaFormat& AdaptiveDemuxerStream::media_format() { return current_stream()->media_format(); } void AdaptiveDemuxerStream::EnableBitstreamConverter() { { base::AutoLock auto_lock(lock_); bitstream_converter_enabled_ = true; } current_stream()->EnableBitstreamConverter(); } void AdaptiveDemuxerStream::ChangeCurrentStream(int index) { bool needs_bitstream_converter_enabled; { base::AutoLock auto_lock(lock_); current_stream_index_ = index; DCHECK(streams_[current_stream_index_]); needs_bitstream_converter_enabled = bitstream_converter_enabled_; } if (needs_bitstream_converter_enabled) EnableBitstreamConverter(); } // // AdaptiveDemuxer // AdaptiveDemuxer::AdaptiveDemuxer(DemuxerVector const& demuxers, int initial_audio_demuxer_index, int initial_video_demuxer_index) : demuxers_(demuxers), current_audio_demuxer_index_(initial_audio_demuxer_index), current_video_demuxer_index_(initial_video_demuxer_index) { DCHECK(!demuxers_.empty()); DCHECK_GE(current_audio_demuxer_index_, -1); DCHECK_GE(current_video_demuxer_index_, -1); DCHECK_LT(current_audio_demuxer_index_, static_cast<int>(demuxers_.size())); DCHECK_LT(current_video_demuxer_index_, static_cast<int>(demuxers_.size())); DCHECK(current_audio_demuxer_index_ != -1 || current_video_demuxer_index_ != -1); AdaptiveDemuxerStream::StreamVector audio_streams, video_streams; for (size_t i = 0; i < demuxers_.size(); ++i) { audio_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::AUDIO)); video_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::VIDEO)); } if (current_audio_demuxer_index_ >= 0) { audio_stream_ = new AdaptiveDemuxerStream( audio_streams, current_audio_demuxer_index_); } if (current_video_demuxer_index_ >= 0) { video_stream_ = new AdaptiveDemuxerStream( video_streams, current_video_demuxer_index_); } // TODO(fischman): any streams in the underlying demuxers that aren't being // consumed currently need to be sent to /dev/null or else FFmpegDemuxer will // hold data for them in memory, waiting for them to get drained by a // non-existent decoder. } AdaptiveDemuxer::~AdaptiveDemuxer() {} void AdaptiveDemuxer::ChangeCurrentDemuxer(int audio_index, int video_index) { // TODO(fischman): this is currently broken because when a new Demuxer is to // be used we need to set_host(host()) it, and we need to set_host(NULL) the // current Demuxer if it's no longer being used. // TODO(fischman): remember to Stop active demuxers that are being abandoned. base::AutoLock auto_lock(lock_); current_audio_demuxer_index_ = audio_index; current_video_demuxer_index_ = video_index; if (audio_stream_) audio_stream_->ChangeCurrentStream(audio_index); if (video_stream_) video_stream_->ChangeCurrentStream(video_index); } Demuxer* AdaptiveDemuxer::current_demuxer(DemuxerStream::Type type) { base::AutoLock auto_lock(lock_); switch (type) { case DemuxerStream::AUDIO: return (current_audio_demuxer_index_ < 0) ? NULL : demuxers_[current_audio_demuxer_index_]; case DemuxerStream::VIDEO: return (current_video_demuxer_index_ < 0) ? NULL : demuxers_[current_video_demuxer_index_]; default: LOG(DFATAL) << "Unexpected type: " << type; return NULL; } } // Helper class that wraps a FilterCallback and expects to get called a set // number of times, after which the wrapped callback is fired (and deleted). class CountingCallback { public: CountingCallback(int count, FilterCallback* orig_cb) : remaining_count_(count), orig_cb_(orig_cb) { DCHECK_GT(remaining_count_, 0); DCHECK(orig_cb); } FilterCallback* GetACallback() { return NewCallback(this, &CountingCallback::OnChildCallbackDone); } private: void OnChildCallbackDone() { bool fire_orig_cb = false; { base::AutoLock auto_lock(lock_); if (--remaining_count_ == 0) fire_orig_cb = true; } if (fire_orig_cb) { orig_cb_->Run(); delete this; } } base::Lock lock_; int remaining_count_; scoped_ptr<FilterCallback> orig_cb_; }; void AdaptiveDemuxer::Stop(FilterCallback* callback) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0); CountingCallback* wrapper = new CountingCallback(count, callback); if (audio) audio->Stop(wrapper->GetACallback()); if (video && audio != video) video->Stop(wrapper->GetACallback()); } void AdaptiveDemuxer::Seek(base::TimeDelta time, FilterCallback* callback) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0); CountingCallback* wrapper = new CountingCallback(count, callback); if (audio) audio->Seek(time, wrapper->GetACallback()); if (video && audio != video) video->Seek(time, wrapper->GetACallback()); } void AdaptiveDemuxer::OnAudioRendererDisabled() { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); if (audio) audio->OnAudioRendererDisabled(); if (video && audio != video) video->OnAudioRendererDisabled(); // TODO(fischman): propagate to other demuxers if/when they're selected. } void AdaptiveDemuxer::set_host(FilterHost* filter_host) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); if (audio) audio->set_host(filter_host); if (video && audio != video) video->set_host(filter_host); } scoped_refptr<DemuxerStream> AdaptiveDemuxer::GetStream( DemuxerStream::Type type) { switch (type) { case DemuxerStream::AUDIO: return audio_stream_; case DemuxerStream::VIDEO: return video_stream_; default: LOG(DFATAL) << "Unexpected type " << type; return NULL; } } // // AdaptiveDemuxerFactory // AdaptiveDemuxerFactory::AdaptiveDemuxerFactory( DemuxerFactory* delegate_factory) : delegate_factory_(delegate_factory) { DCHECK(delegate_factory); } AdaptiveDemuxerFactory::~AdaptiveDemuxerFactory() {} DemuxerFactory* AdaptiveDemuxerFactory::Clone() const { return new AdaptiveDemuxerFactory(delegate_factory_->Clone()); } // See AdaptiveDemuxerFactory's class-level comment for |url|'s format. bool ParseAdaptiveUrl( const std::string& url, int* audio_index, int* video_index, std::vector<std::string>* urls) { urls->clear(); if (url.empty()) return false; if (!StartsWithASCII(url, "x-adaptive:", false)) { return ParseAdaptiveUrl( "x-adaptive:0:0:" + url, audio_index, video_index, urls); } std::vector<std::string> parts; base::SplitStringDontTrim(url, ':', &parts); if (parts.size() < 4 || parts[0] != "x-adaptive" || !base::StringToInt(parts[1], audio_index) || !base::StringToInt(parts[2], video_index) || *audio_index < -1 || *video_index < -1) { return false; } std::string::size_type first_url_pos = parts[0].size() + 1 + parts[1].size() + 1 + parts[2].size() + 1; std::string urls_str = url.substr(first_url_pos); if (urls_str.empty()) return false; base::SplitStringDontTrim(urls_str, '^', urls); if (urls->empty() || *audio_index >= static_cast<int>(urls->size()) || *video_index >= static_cast<int>(urls->size())) { return false; } return true; } // Wrapper for a BuildCallback which accumulates the Demuxer's returned by a // number of DemuxerFactory::Build() calls and eventually constructs an // AdaptiveDemuxer and returns it to the |orig_cb| (or errors out if any // individual Demuxer fails construction). class DemuxerAccumulator { public: // Takes ownership of |orig_cb|. DemuxerAccumulator(int audio_index, int video_index, int count, DemuxerFactory::BuildCallback* orig_cb) : audio_index_(audio_index), video_index_(video_index), remaining_count_(count), orig_cb_(orig_cb), demuxers_(count, static_cast<Demuxer*>(NULL)), statuses_(count, PIPELINE_OK) { DCHECK_GT(remaining_count_, 0); DCHECK(orig_cb_.get()); } DemuxerFactory::BuildCallback* GetNthCallback(int n) { return new IndividualCallback(this, n); } private: // Wrapper for a BuildCallback that can carry one extra piece of data: the // index of this callback in the original list of outstanding requests. struct IndividualCallback : public DemuxerFactory::BuildCallback { IndividualCallback(DemuxerAccumulator* accumulator, int index) : accumulator_(accumulator), index_(index) {} virtual void RunWithParams(const Tuple2<PipelineStatus, Demuxer*>& params) { accumulator_->Run(index_, params.a, params.b); } DemuxerAccumulator* accumulator_; int index_; }; // When an individual callback is fired, it calls this method. void Run(int index, PipelineStatus status, Demuxer* demuxer) { bool fire_orig_cb = false; { base::AutoLock auto_lock(lock_); DCHECK(!demuxers_[index]); demuxers_[index] = demuxer; statuses_[index] = status; if (--remaining_count_ == 0) fire_orig_cb = true; } if (fire_orig_cb) DoneAccumulating(); } void DoneAccumulating() { PipelineStatus overall_status = PIPELINE_OK; for (size_t i = 0; i < statuses_.size(); ++i) { if (statuses_[i] != PIPELINE_OK) { overall_status = statuses_[i]; break; } } if (overall_status == PIPELINE_OK) { orig_cb_->Run( PIPELINE_OK, new AdaptiveDemuxer(demuxers_, audio_index_, video_index_)); } else { orig_cb_->Run(overall_status, static_cast<Demuxer*>(NULL)); } delete this; } // Self-delete in DoneAccumulating() only. ~DemuxerAccumulator() {} int audio_index_; int video_index_; int remaining_count_; scoped_ptr<DemuxerFactory::BuildCallback> orig_cb_; base::Lock lock_; // Guards vectors of results below. AdaptiveDemuxer::DemuxerVector demuxers_; std::vector<PipelineStatus> statuses_; DISALLOW_IMPLICIT_CONSTRUCTORS(DemuxerAccumulator); }; void AdaptiveDemuxerFactory::Build(const std::string& url, BuildCallback* cb) { std::vector<std::string> urls; int audio_index, video_index; if (!ParseAdaptiveUrl(url, &audio_index, &video_index, &urls)) { cb->Run(Tuple2<PipelineStatus, Demuxer*>( DEMUXER_ERROR_COULD_NOT_OPEN, NULL)); delete cb; return; } DemuxerAccumulator* accumulator = new DemuxerAccumulator( audio_index, video_index, urls.size(), cb); for (size_t i = 0; i < urls.size(); ++i) delegate_factory_->Build(urls[i], accumulator->GetNthCallback(i)); } } // namespace media <commit_msg>Fix an uninitialized variable compiler warning on some systems. BUG=none TEST=none Review URL: http://codereview.chromium.org/6677123<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_util.h" #include "media/filters/adaptive_demuxer.h" namespace media { // // AdaptiveDemuxerStream // AdaptiveDemuxerStream::AdaptiveDemuxerStream( StreamVector const& streams, int initial_stream) : streams_(streams), current_stream_index_(initial_stream), bitstream_converter_enabled_(false) { DCheckSanity(); } void AdaptiveDemuxerStream::DCheckSanity() { // We only carry out sanity checks in debug mode. if (!logging::DEBUG_MODE) return; DCHECK(streams_[current_stream_index_].get()); bool non_null_stream_seen = false; Type type = DemuxerStream::UNKNOWN; const MediaFormat* media_format = NULL; for (size_t i = 0; i < streams_.size(); ++i) { if (!streams_[i]) continue; if (!non_null_stream_seen) { non_null_stream_seen = true; type = streams_[i]->type(); media_format = &streams_[i]->media_format(); } else { DCHECK_EQ(streams_[i]->type(), type); DCHECK(streams_[i]->media_format() == *media_format); } } } AdaptiveDemuxerStream::~AdaptiveDemuxerStream() { base::AutoLock auto_lock(lock_); current_stream_index_ = -1; streams_.clear(); } DemuxerStream* AdaptiveDemuxerStream::current_stream() { base::AutoLock auto_lock(lock_); return streams_[current_stream_index_]; } void AdaptiveDemuxerStream::Read(Callback1<Buffer*>::Type* read_callback) { current_stream()->Read(read_callback); } AVStream* AdaptiveDemuxerStream::GetAVStream() { return current_stream()->GetAVStream(); } DemuxerStream::Type AdaptiveDemuxerStream::type() { return current_stream()->type(); } const MediaFormat& AdaptiveDemuxerStream::media_format() { return current_stream()->media_format(); } void AdaptiveDemuxerStream::EnableBitstreamConverter() { { base::AutoLock auto_lock(lock_); bitstream_converter_enabled_ = true; } current_stream()->EnableBitstreamConverter(); } void AdaptiveDemuxerStream::ChangeCurrentStream(int index) { bool needs_bitstream_converter_enabled; { base::AutoLock auto_lock(lock_); current_stream_index_ = index; DCHECK(streams_[current_stream_index_]); needs_bitstream_converter_enabled = bitstream_converter_enabled_; } if (needs_bitstream_converter_enabled) EnableBitstreamConverter(); } // // AdaptiveDemuxer // AdaptiveDemuxer::AdaptiveDemuxer(DemuxerVector const& demuxers, int initial_audio_demuxer_index, int initial_video_demuxer_index) : demuxers_(demuxers), current_audio_demuxer_index_(initial_audio_demuxer_index), current_video_demuxer_index_(initial_video_demuxer_index) { DCHECK(!demuxers_.empty()); DCHECK_GE(current_audio_demuxer_index_, -1); DCHECK_GE(current_video_demuxer_index_, -1); DCHECK_LT(current_audio_demuxer_index_, static_cast<int>(demuxers_.size())); DCHECK_LT(current_video_demuxer_index_, static_cast<int>(demuxers_.size())); DCHECK(current_audio_demuxer_index_ != -1 || current_video_demuxer_index_ != -1); AdaptiveDemuxerStream::StreamVector audio_streams, video_streams; for (size_t i = 0; i < demuxers_.size(); ++i) { audio_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::AUDIO)); video_streams.push_back(demuxers_[i]->GetStream(DemuxerStream::VIDEO)); } if (current_audio_demuxer_index_ >= 0) { audio_stream_ = new AdaptiveDemuxerStream( audio_streams, current_audio_demuxer_index_); } if (current_video_demuxer_index_ >= 0) { video_stream_ = new AdaptiveDemuxerStream( video_streams, current_video_demuxer_index_); } // TODO(fischman): any streams in the underlying demuxers that aren't being // consumed currently need to be sent to /dev/null or else FFmpegDemuxer will // hold data for them in memory, waiting for them to get drained by a // non-existent decoder. } AdaptiveDemuxer::~AdaptiveDemuxer() {} void AdaptiveDemuxer::ChangeCurrentDemuxer(int audio_index, int video_index) { // TODO(fischman): this is currently broken because when a new Demuxer is to // be used we need to set_host(host()) it, and we need to set_host(NULL) the // current Demuxer if it's no longer being used. // TODO(fischman): remember to Stop active demuxers that are being abandoned. base::AutoLock auto_lock(lock_); current_audio_demuxer_index_ = audio_index; current_video_demuxer_index_ = video_index; if (audio_stream_) audio_stream_->ChangeCurrentStream(audio_index); if (video_stream_) video_stream_->ChangeCurrentStream(video_index); } Demuxer* AdaptiveDemuxer::current_demuxer(DemuxerStream::Type type) { base::AutoLock auto_lock(lock_); switch (type) { case DemuxerStream::AUDIO: return (current_audio_demuxer_index_ < 0) ? NULL : demuxers_[current_audio_demuxer_index_]; case DemuxerStream::VIDEO: return (current_video_demuxer_index_ < 0) ? NULL : demuxers_[current_video_demuxer_index_]; default: LOG(DFATAL) << "Unexpected type: " << type; return NULL; } } // Helper class that wraps a FilterCallback and expects to get called a set // number of times, after which the wrapped callback is fired (and deleted). class CountingCallback { public: CountingCallback(int count, FilterCallback* orig_cb) : remaining_count_(count), orig_cb_(orig_cb) { DCHECK_GT(remaining_count_, 0); DCHECK(orig_cb); } FilterCallback* GetACallback() { return NewCallback(this, &CountingCallback::OnChildCallbackDone); } private: void OnChildCallbackDone() { bool fire_orig_cb = false; { base::AutoLock auto_lock(lock_); if (--remaining_count_ == 0) fire_orig_cb = true; } if (fire_orig_cb) { orig_cb_->Run(); delete this; } } base::Lock lock_; int remaining_count_; scoped_ptr<FilterCallback> orig_cb_; }; void AdaptiveDemuxer::Stop(FilterCallback* callback) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0); CountingCallback* wrapper = new CountingCallback(count, callback); if (audio) audio->Stop(wrapper->GetACallback()); if (video && audio != video) video->Stop(wrapper->GetACallback()); } void AdaptiveDemuxer::Seek(base::TimeDelta time, FilterCallback* callback) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); int count = (audio ? 1 : 0) + (video && audio != video ? 1 : 0); CountingCallback* wrapper = new CountingCallback(count, callback); if (audio) audio->Seek(time, wrapper->GetACallback()); if (video && audio != video) video->Seek(time, wrapper->GetACallback()); } void AdaptiveDemuxer::OnAudioRendererDisabled() { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); if (audio) audio->OnAudioRendererDisabled(); if (video && audio != video) video->OnAudioRendererDisabled(); // TODO(fischman): propagate to other demuxers if/when they're selected. } void AdaptiveDemuxer::set_host(FilterHost* filter_host) { Demuxer* audio = current_demuxer(DemuxerStream::AUDIO); Demuxer* video = current_demuxer(DemuxerStream::VIDEO); if (audio) audio->set_host(filter_host); if (video && audio != video) video->set_host(filter_host); } scoped_refptr<DemuxerStream> AdaptiveDemuxer::GetStream( DemuxerStream::Type type) { switch (type) { case DemuxerStream::AUDIO: return audio_stream_; case DemuxerStream::VIDEO: return video_stream_; default: LOG(DFATAL) << "Unexpected type " << type; return NULL; } } // // AdaptiveDemuxerFactory // AdaptiveDemuxerFactory::AdaptiveDemuxerFactory( DemuxerFactory* delegate_factory) : delegate_factory_(delegate_factory) { DCHECK(delegate_factory); } AdaptiveDemuxerFactory::~AdaptiveDemuxerFactory() {} DemuxerFactory* AdaptiveDemuxerFactory::Clone() const { return new AdaptiveDemuxerFactory(delegate_factory_->Clone()); } // See AdaptiveDemuxerFactory's class-level comment for |url|'s format. bool ParseAdaptiveUrl( const std::string& url, int* audio_index, int* video_index, std::vector<std::string>* urls) { urls->clear(); if (url.empty()) return false; if (!StartsWithASCII(url, "x-adaptive:", false)) { return ParseAdaptiveUrl( "x-adaptive:0:0:" + url, audio_index, video_index, urls); } std::vector<std::string> parts; base::SplitStringDontTrim(url, ':', &parts); if (parts.size() < 4 || parts[0] != "x-adaptive" || !base::StringToInt(parts[1], audio_index) || !base::StringToInt(parts[2], video_index) || *audio_index < -1 || *video_index < -1) { return false; } std::string::size_type first_url_pos = parts[0].size() + 1 + parts[1].size() + 1 + parts[2].size() + 1; std::string urls_str = url.substr(first_url_pos); if (urls_str.empty()) return false; base::SplitStringDontTrim(urls_str, '^', urls); if (urls->empty() || *audio_index >= static_cast<int>(urls->size()) || *video_index >= static_cast<int>(urls->size())) { return false; } return true; } // Wrapper for a BuildCallback which accumulates the Demuxer's returned by a // number of DemuxerFactory::Build() calls and eventually constructs an // AdaptiveDemuxer and returns it to the |orig_cb| (or errors out if any // individual Demuxer fails construction). class DemuxerAccumulator { public: // Takes ownership of |orig_cb|. DemuxerAccumulator(int audio_index, int video_index, int count, DemuxerFactory::BuildCallback* orig_cb) : audio_index_(audio_index), video_index_(video_index), remaining_count_(count), orig_cb_(orig_cb), demuxers_(count, static_cast<Demuxer*>(NULL)), statuses_(count, PIPELINE_OK) { DCHECK_GT(remaining_count_, 0); DCHECK(orig_cb_.get()); } DemuxerFactory::BuildCallback* GetNthCallback(int n) { return new IndividualCallback(this, n); } private: // Wrapper for a BuildCallback that can carry one extra piece of data: the // index of this callback in the original list of outstanding requests. struct IndividualCallback : public DemuxerFactory::BuildCallback { IndividualCallback(DemuxerAccumulator* accumulator, int index) : accumulator_(accumulator), index_(index) {} virtual void RunWithParams(const Tuple2<PipelineStatus, Demuxer*>& params) { accumulator_->Run(index_, params.a, params.b); } DemuxerAccumulator* accumulator_; int index_; }; // When an individual callback is fired, it calls this method. void Run(int index, PipelineStatus status, Demuxer* demuxer) { bool fire_orig_cb = false; { base::AutoLock auto_lock(lock_); DCHECK(!demuxers_[index]); demuxers_[index] = demuxer; statuses_[index] = status; if (--remaining_count_ == 0) fire_orig_cb = true; } if (fire_orig_cb) DoneAccumulating(); } void DoneAccumulating() { PipelineStatus overall_status = PIPELINE_OK; for (size_t i = 0; i < statuses_.size(); ++i) { if (statuses_[i] != PIPELINE_OK) { overall_status = statuses_[i]; break; } } if (overall_status == PIPELINE_OK) { orig_cb_->Run( PIPELINE_OK, new AdaptiveDemuxer(demuxers_, audio_index_, video_index_)); } else { orig_cb_->Run(overall_status, static_cast<Demuxer*>(NULL)); } delete this; } // Self-delete in DoneAccumulating() only. ~DemuxerAccumulator() {} int audio_index_; int video_index_; int remaining_count_; scoped_ptr<DemuxerFactory::BuildCallback> orig_cb_; base::Lock lock_; // Guards vectors of results below. AdaptiveDemuxer::DemuxerVector demuxers_; std::vector<PipelineStatus> statuses_; DISALLOW_IMPLICIT_CONSTRUCTORS(DemuxerAccumulator); }; void AdaptiveDemuxerFactory::Build(const std::string& url, BuildCallback* cb) { std::vector<std::string> urls; int audio_index, video_index; if (!ParseAdaptiveUrl(url, &audio_index, &video_index, &urls)) { cb->Run(Tuple2<PipelineStatus, Demuxer*>( DEMUXER_ERROR_COULD_NOT_OPEN, NULL)); delete cb; return; } DemuxerAccumulator* accumulator = new DemuxerAccumulator( audio_index, video_index, urls.size(), cb); for (size_t i = 0; i < urls.size(); ++i) delegate_factory_->Build(urls[i], accumulator->GetNthCallback(i)); } } // namespace media <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file main.cpp * @author Gav Wood <[email protected]> * @date 2014 * Ethereum client. */ #include <thread> #include <chrono> #include <fstream> #include "Defaults.h" #include "Client.h" #include "PeerNetwork.h" #include "BlockChain.h" #include "State.h" #include "FileSystem.h" #include "Instruction.h" #include "BuildInfo.h" using namespace std; using namespace eth; using eth::Instruction; using eth::c_instructionInfo; bool isTrue(std::string const& _m) { return _m == "on" || _m == "yes" || _m == "true" || _m == "1"; } bool isFalse(std::string const& _m) { return _m == "off" || _m == "no" || _m == "false" || _m == "0"; } void help() { cout << "Usage eth [OPTIONS] <remote-host>" << endl << "Options:" << endl << " -a,--address <addr> Set the coinbase (mining payout) address to addr (default: auto)." << endl << " -c,--client-name <name> Add a name to your client's version string (default: blank)." << endl << " -d,--db-path <path> Load database from path (default: ~/.ethereum " << endl << " <APPDATA>/Etherum or Library/Application Support/Ethereum)." << endl << " -h,--help Show this help message and exit." << endl << " -i,--interactive Enter interactive mode (default: non-interactive)." << endl << " -l,--listen <port> Listen on the given port for incoming connected (default: 30303)." << endl << " -m,--mining <on/off/number> Enable mining, optionally for a specified number of blocks (Default: off)" << endl << " -n,--upnp <on/off> Use upnp for NAT (default: on)." << endl << " -o,--mode <full/peer> Start a full node or a peer node (Default: full)." << endl << " -p,--port <port> Connect to remote port (default: 30303)." << endl << " -r,--remote <host> Connect to remote host (default: none)." << endl << " -s,--secret <secretkeyhex> Set the secret key for use with send command (default: auto)." << endl << " -u,--public-ip <ip> Force public ip to given (default; auto)." << endl << " -v,--verbosity <0 - 9> Set the log verbosity from 0 to 9 (Default: 8)." << endl << " -x,--peers <number> Attempt to connect to given number of peers (Default: 5)." << endl << " -V,--version Show the version and exit." << endl; exit(0); } void interactiveHelp() { cout << "Commands:" << endl << " netstart <port> Starts the network sybsystem on a specific port." << endl << " netstop Stops the network subsystem." << endl << " connect <addr> <port> Connects to a specific peer." << endl << " minestart Starts mining." << endl << " minestop Stops mining." << endl << " address Gives the current address." << endl << " secret Gives the current secret" << endl << " block Gives the current block height." << endl << " balance Gives the current balance." << endl << " transact <secret> <dest> <amount> Executes a given transaction." << endl << " send <dest> <amount> Executes a given transaction with current secret." << endl << " inspect <contract> Dumps a contract to <APPDATA>/<contract>.evm." << endl << " exit Exits the application." << endl; } void version() { cout << "eth version " << ETH_QUOTED(ETH_VERSION) << endl; cout << "Build: " << ETH_QUOTED(ETH_BUILD_PLATFORM) << "/" << ETH_QUOTED(ETH_BUILD_TYPE) << endl; exit(0); } int main(int argc, char** argv) { unsigned short listenPort = 30303; string remoteHost; unsigned short remotePort = 30303; bool interactive = false; string dbPath; eth::uint mining = ~(eth::uint)0; NodeMode mode = NodeMode::Full; unsigned peers = 5; string publicIP; bool upnp = true; string clientName; // Init defaults Defaults::get(); // Our address. KeyPair us = KeyPair::create(); Address coinbase = us.address(); string configFile = getDataDir() + "/config.rlp"; bytes b = contents(configFile); if (b.size()) { RLP config(b); us = KeyPair(config[0].toHash<Secret>()); coinbase = config[1].toHash<Address>(); } else { RLPStream config(2); config << us.secret() << coinbase; writeFile(configFile, config.out()); } for (int i = 1; i < argc; ++i) { string arg = argv[i]; if ((arg == "-l" || arg == "--listen" || arg == "--listen-port") && i + 1 < argc) listenPort = (short)atoi(argv[++i]); else if ((arg == "-u" || arg == "--public-ip" || arg == "--public") && i + 1 < argc) publicIP = argv[++i]; else if ((arg == "-r" || arg == "--remote") && i + 1 < argc) remoteHost = argv[++i]; else if ((arg == "-p" || arg == "--port") && i + 1 < argc) remotePort = (short)atoi(argv[++i]); else if ((arg == "-n" || arg == "--upnp") && i + 1 < argc) { string m = argv[++i]; if (isTrue(m)) upnp = true; else if (isFalse(m)) upnp = false; else { cerr << "Invalid UPnP option: " << m << endl; return -1; } } else if ((arg == "-c" || arg == "--client-name") && i + 1 < argc) clientName = argv[++i]; else if ((arg == "-a" || arg == "--address" || arg == "--coinbase-address") && i + 1 < argc) coinbase = h160(fromHex(argv[++i])); else if ((arg == "-s" || arg == "--secret") && i + 1 < argc) us = KeyPair(h256(fromHex(argv[++i]))); else if (arg == "-i" || arg == "--interactive") interactive = true; else if ((arg == "-d" || arg == "--path" || arg == "--db-path") && i + 1 < argc) dbPath = argv[++i]; else if ((arg == "-m" || arg == "--mining") && i + 1 < argc) { string m = argv[++i]; if (isTrue(m)) mining = ~(eth::uint)0; else if (isFalse(m)) mining = 0; else if (int i = stoi(m)) mining = i; else { cerr << "Unknown mining option: " << m << endl; return -1; } } else if ((arg == "-v" || arg == "--verbosity") && i + 1 < argc) g_logVerbosity = atoi(argv[++i]); else if ((arg == "-x" || arg == "--peers") && i + 1 < argc) peers = atoi(argv[++i]); else if ((arg == "-o" || arg == "--mode") && i + 1 < argc) { string m = argv[++i]; if (m == "full") mode = NodeMode::Full; else if (m == "peer") mode = NodeMode::PeerServer; else { cerr << "Unknown mode: " << m << endl; return -1; } } else if (arg == "-h" || arg == "--help") help(); else if (arg == "-V" || arg == "--version") version(); else remoteHost = argv[i]; } if (!clientName.empty()) clientName += "/"; Client c("Ethereum(++)/" + clientName + "v" ETH_QUOTED(ETH_VERSION) "/" ETH_QUOTED(ETH_BUILD_TYPE) "/" ETH_QUOTED(ETH_BUILD_PLATFORM), coinbase, dbPath); if (interactive) { cout << "Ethereum (++)" << endl; cout << " Code by Gav Wood, (c) 2013, 2014." << endl; cout << " Based on a design by Vitalik Buterin." << endl << endl; while (true) { cout << "> " << flush; std::string cmd; cin >> cmd; if (cmd == "netstart") { eth::uint port; cin >> port; c.startNetwork((short)port); } else if (cmd == "connect") { string addr; eth::uint port; cin >> addr >> port; c.connect(addr, (short)port); } else if (cmd == "netstop") { c.stopNetwork(); } else if (cmd == "minestart") { c.startMining(); } else if (cmd == "minestop") { c.stopMining(); } else if (cmd == "address") { cout << endl; cout << "Current address: " + toHex(us.address().asArray()) << endl; cout << "===" << endl; } else if (cmd == "secret") { cout << endl; cout << "Current secret: " + toHex(us.secret().asArray()) << endl; cout << "===" << endl; } else if (cmd == "block") { eth::uint n = c.blockChain().details().number; cout << endl; cout << "Current block # " << n << endl; cout << "===" << endl; } else if (cmd == "balance") { u256 balance = c.state().balance(us.address()); cout << endl; cout << "Current balance: "; cout << balance << endl; cout << "===" << endl; } else if (cmd == "transact") { string sechex; string rechex; u256 amount; cin >> sechex >> rechex >> amount; Secret secret = h256(fromHex(sechex)); Address dest = h160(fromHex(rechex)); c.transact(secret, dest, amount); } else if (cmd == "send") { string rechex; u256 amount; cin >> rechex >> amount; Address dest = h160(fromHex(rechex)); c.transact(us.secret(), dest, amount); } else if (cmd == "inspect") { string rechex; cin >> rechex; c.lock(); auto h = h160(fromHex(rechex)); stringstream s; auto mem = c.state().contractMemory(h); u256 next = 0; unsigned numerics = 0; bool unexpectedNumeric = false; for (auto i: mem) { if (next < i.first) { unsigned j; for (j = 0; j <= numerics && next + j < i.first; ++j) s << (j < numerics || unexpectedNumeric ? " 0" : " STOP"); unexpectedNumeric = false; numerics -= min(numerics, j); if (next + j < i.first) s << "\n@" << showbase << hex << i.first << " "; } else if (!next) { s << "@" << showbase << hex << i.first << " "; } auto iit = c_instructionInfo.find((Instruction)(unsigned)i.second); if (numerics || iit == c_instructionInfo.end() || (u256)(unsigned)iit->first != i.second) // not an instruction or expecting an argument... { if (numerics) numerics--; else unexpectedNumeric = true; s << " " << showbase << hex << i.second; } else { auto const& ii = iit->second; s << " " << ii.name; numerics = ii.additional; } next = i.first + 1; } string outFile = getDataDir() + "/" + rechex + ".evm"; ofstream ofs; ofs.open(outFile, ofstream::binary); ofs.write(s.str().c_str(), s.str().length()); ofs.close(); c.unlock(); } else if (cmd == "help") { interactiveHelp(); } else if (cmd == "exit") { break; } } } else { cout << "Address: " << endl << toHex(us.address().asArray()) << endl; c.startNetwork(listenPort, remoteHost, remotePort, mode, peers, publicIP, upnp); eth::uint n = c.blockChain().details().number; if (mining) c.startMining(); while (true) { if (c.blockChain().details().number - n == mining) c.stopMining(); this_thread::sleep_for(chrono::milliseconds(100)); } } return 0; } <commit_msg>connect with settings in interactive mode<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file main.cpp * @author Gav Wood <[email protected]> * @date 2014 * Ethereum client. */ #include <thread> #include <chrono> #include <fstream> #include "Defaults.h" #include "Client.h" #include "PeerNetwork.h" #include "BlockChain.h" #include "State.h" #include "FileSystem.h" #include "Instruction.h" #include "BuildInfo.h" using namespace std; using namespace eth; using eth::Instruction; using eth::c_instructionInfo; bool isTrue(std::string const& _m) { return _m == "on" || _m == "yes" || _m == "true" || _m == "1"; } bool isFalse(std::string const& _m) { return _m == "off" || _m == "no" || _m == "false" || _m == "0"; } void help() { cout << "Usage eth [OPTIONS] <remote-host>" << endl << "Options:" << endl << " -a,--address <addr> Set the coinbase (mining payout) address to addr (default: auto)." << endl << " -c,--client-name <name> Add a name to your client's version string (default: blank)." << endl << " -d,--db-path <path> Load database from path (default: ~/.ethereum " << endl << " <APPDATA>/Etherum or Library/Application Support/Ethereum)." << endl << " -h,--help Show this help message and exit." << endl << " -i,--interactive Enter interactive mode (default: non-interactive)." << endl << " -l,--listen <port> Listen on the given port for incoming connected (default: 30303)." << endl << " -m,--mining <on/off/number> Enable mining, optionally for a specified number of blocks (Default: off)" << endl << " -n,--upnp <on/off> Use upnp for NAT (default: on)." << endl << " -o,--mode <full/peer> Start a full node or a peer node (Default: full)." << endl << " -p,--port <port> Connect to remote port (default: 30303)." << endl << " -r,--remote <host> Connect to remote host (default: none)." << endl << " -s,--secret <secretkeyhex> Set the secret key for use with send command (default: auto)." << endl << " -u,--public-ip <ip> Force public ip to given (default; auto)." << endl << " -v,--verbosity <0 - 9> Set the log verbosity from 0 to 9 (Default: 8)." << endl << " -x,--peers <number> Attempt to connect to given number of peers (Default: 5)." << endl << " -V,--version Show the version and exit." << endl; exit(0); } void interactiveHelp() { cout << "Commands:" << endl << " netstart <port> Starts the network sybsystem on a specific port." << endl << " netstop Stops the network subsystem." << endl << " connect <addr> <port> Connects to a specific peer." << endl << " minestart Starts mining." << endl << " minestop Stops mining." << endl << " address Gives the current address." << endl << " secret Gives the current secret" << endl << " block Gives the current block height." << endl << " balance Gives the current balance." << endl << " transact <secret> <dest> <amount> Executes a given transaction." << endl << " send <dest> <amount> Executes a given transaction with current secret." << endl << " inspect <contract> Dumps a contract to <APPDATA>/<contract>.evm." << endl << " exit Exits the application." << endl; } void version() { cout << "eth version " << ETH_QUOTED(ETH_VERSION) << endl; cout << "Build: " << ETH_QUOTED(ETH_BUILD_PLATFORM) << "/" << ETH_QUOTED(ETH_BUILD_TYPE) << endl; exit(0); } int main(int argc, char** argv) { unsigned short listenPort = 30303; string remoteHost; unsigned short remotePort = 30303; bool interactive = false; string dbPath; eth::uint mining = ~(eth::uint)0; NodeMode mode = NodeMode::Full; unsigned peers = 5; string publicIP; bool upnp = true; string clientName; // Init defaults Defaults::get(); // Our address. KeyPair us = KeyPair::create(); Address coinbase = us.address(); string configFile = getDataDir() + "/config.rlp"; bytes b = contents(configFile); if (b.size()) { RLP config(b); us = KeyPair(config[0].toHash<Secret>()); coinbase = config[1].toHash<Address>(); } else { RLPStream config(2); config << us.secret() << coinbase; writeFile(configFile, config.out()); } for (int i = 1; i < argc; ++i) { string arg = argv[i]; if ((arg == "-l" || arg == "--listen" || arg == "--listen-port") && i + 1 < argc) listenPort = (short)atoi(argv[++i]); else if ((arg == "-u" || arg == "--public-ip" || arg == "--public") && i + 1 < argc) publicIP = argv[++i]; else if ((arg == "-r" || arg == "--remote") && i + 1 < argc) remoteHost = argv[++i]; else if ((arg == "-p" || arg == "--port") && i + 1 < argc) remotePort = (short)atoi(argv[++i]); else if ((arg == "-n" || arg == "--upnp") && i + 1 < argc) { string m = argv[++i]; if (isTrue(m)) upnp = true; else if (isFalse(m)) upnp = false; else { cerr << "Invalid UPnP option: " << m << endl; return -1; } } else if ((arg == "-c" || arg == "--client-name") && i + 1 < argc) clientName = argv[++i]; else if ((arg == "-a" || arg == "--address" || arg == "--coinbase-address") && i + 1 < argc) coinbase = h160(fromHex(argv[++i])); else if ((arg == "-s" || arg == "--secret") && i + 1 < argc) us = KeyPair(h256(fromHex(argv[++i]))); else if (arg == "-i" || arg == "--interactive") interactive = true; else if ((arg == "-d" || arg == "--path" || arg == "--db-path") && i + 1 < argc) dbPath = argv[++i]; else if ((arg == "-m" || arg == "--mining") && i + 1 < argc) { string m = argv[++i]; if (isTrue(m)) mining = ~(eth::uint)0; else if (isFalse(m)) mining = 0; else if (int i = stoi(m)) mining = i; else { cerr << "Unknown mining option: " << m << endl; return -1; } } else if ((arg == "-v" || arg == "--verbosity") && i + 1 < argc) g_logVerbosity = atoi(argv[++i]); else if ((arg == "-x" || arg == "--peers") && i + 1 < argc) peers = atoi(argv[++i]); else if ((arg == "-o" || arg == "--mode") && i + 1 < argc) { string m = argv[++i]; if (m == "full") mode = NodeMode::Full; else if (m == "peer") mode = NodeMode::PeerServer; else { cerr << "Unknown mode: " << m << endl; return -1; } } else if (arg == "-h" || arg == "--help") help(); else if (arg == "-V" || arg == "--version") version(); else remoteHost = argv[i]; } if (!clientName.empty()) clientName += "/"; Client c("Ethereum(++)/" + clientName + "v" ETH_QUOTED(ETH_VERSION) "/" ETH_QUOTED(ETH_BUILD_TYPE) "/" ETH_QUOTED(ETH_BUILD_PLATFORM), coinbase, dbPath); if (interactive) { cout << "Ethereum (++)" << endl; cout << " Code by Gav Wood, (c) 2013, 2014." << endl; cout << " Based on a design by Vitalik Buterin." << endl << endl; if (!remoteHost.empty()) c.startNetwork(listenPort, remoteHost, remotePort, mode, peers, publicIP, upnp); while (true) { cout << "> " << flush; std::string cmd; cin >> cmd; if (cmd == "netstart") { eth::uint port; cin >> port; c.startNetwork((short)port); } else if (cmd == "connect") { string addr; eth::uint port; cin >> addr >> port; c.connect(addr, (short)port); } else if (cmd == "netstop") { c.stopNetwork(); } else if (cmd == "minestart") { c.startMining(); } else if (cmd == "minestop") { c.stopMining(); } else if (cmd == "address") { cout << endl; cout << "Current address: " + toHex(us.address().asArray()) << endl; cout << "===" << endl; } else if (cmd == "secret") { cout << endl; cout << "Current secret: " + toHex(us.secret().asArray()) << endl; cout << "===" << endl; } else if (cmd == "block") { eth::uint n = c.blockChain().details().number; cout << endl; cout << "Current block # " << n << endl; cout << "===" << endl; } else if (cmd == "balance") { u256 balance = c.state().balance(us.address()); cout << endl; cout << "Current balance: "; cout << balance << endl; cout << "===" << endl; } else if (cmd == "transact") { string sechex; string rechex; u256 amount; cin >> sechex >> rechex >> amount; Secret secret = h256(fromHex(sechex)); Address dest = h160(fromHex(rechex)); c.transact(secret, dest, amount); } else if (cmd == "send") { string rechex; u256 amount; cin >> rechex >> amount; Address dest = h160(fromHex(rechex)); c.transact(us.secret(), dest, amount); } else if (cmd == "inspect") { string rechex; cin >> rechex; c.lock(); auto h = h160(fromHex(rechex)); stringstream s; auto mem = c.state().contractMemory(h); u256 next = 0; unsigned numerics = 0; bool unexpectedNumeric = false; for (auto i: mem) { if (next < i.first) { unsigned j; for (j = 0; j <= numerics && next + j < i.first; ++j) s << (j < numerics || unexpectedNumeric ? " 0" : " STOP"); unexpectedNumeric = false; numerics -= min(numerics, j); if (next + j < i.first) s << "\n@" << showbase << hex << i.first << " "; } else if (!next) { s << "@" << showbase << hex << i.first << " "; } auto iit = c_instructionInfo.find((Instruction)(unsigned)i.second); if (numerics || iit == c_instructionInfo.end() || (u256)(unsigned)iit->first != i.second) // not an instruction or expecting an argument... { if (numerics) numerics--; else unexpectedNumeric = true; s << " " << showbase << hex << i.second; } else { auto const& ii = iit->second; s << " " << ii.name; numerics = ii.additional; } next = i.first + 1; } string outFile = getDataDir() + "/" + rechex + ".evm"; ofstream ofs; ofs.open(outFile, ofstream::binary); ofs.write(s.str().c_str(), s.str().length()); ofs.close(); c.unlock(); } else if (cmd == "help") { interactiveHelp(); } else if (cmd == "exit") { break; } } } else { cout << "Address: " << endl << toHex(us.address().asArray()) << endl; c.startNetwork(listenPort, remoteHost, remotePort, mode, peers, publicIP, upnp); eth::uint n = c.blockChain().details().number; if (mining) c.startMining(); while (true) { if (c.blockChain().details().number - n == mining) c.stopMining(); this_thread::sleep_for(chrono::milliseconds(100)); } } return 0; } <|endoftext|>
<commit_before>/*************************************************************************/ /* progress_bar.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "progress_bar.h" Size2 ProgressBar::get_minimum_size() const { Ref<StyleBox> bg = get_stylebox("bg"); Ref<StyleBox> fg = get_stylebox("fg"); Ref<Font> font = get_font("font"); Size2 minimum_size = bg->get_minimum_size(); minimum_size.height = MAX(minimum_size.height, fg->get_minimum_size().height); minimum_size.width = MAX(minimum_size.width, fg->get_minimum_size().width); //if (percent_visible) { this is needed, else the progressbar will collapse minimum_size.height = MAX(minimum_size.height, bg->get_minimum_size().height + font->get_height()); //} return minimum_size; } void ProgressBar::_notification(int p_what) { if (p_what == NOTIFICATION_DRAW) { Ref<StyleBox> bg = get_stylebox("bg"); Ref<StyleBox> fg = get_stylebox("fg"); Ref<Font> font = get_font("font"); Color font_color = get_color("font_color"); draw_style_box(bg, Rect2(Point2(), get_size())); float r = get_as_ratio(); int mp = fg->get_minimum_size().width; int p = r * get_size().width - mp; if (p > 0) { draw_style_box(fg, Rect2(Point2(), Size2(p + fg->get_minimum_size().width, get_size().height))); } if (percent_visible) { String txt = itos(int(get_as_ratio() * 100)) + "%"; font->draw_halign(get_canvas_item(), Point2(0, font->get_ascent() + (get_size().height - font->get_height()) / 2), HALIGN_CENTER, get_size().width, txt, font_color); } } } void ProgressBar::set_percent_visible(bool p_visible) { percent_visible = p_visible; update(); } bool ProgressBar::is_percent_visible() const { return percent_visible; } void ProgressBar::_bind_methods() { ClassDB::bind_method(D_METHOD("set_percent_visible", "visible"), &ProgressBar::set_percent_visible); ClassDB::bind_method(D_METHOD("is_percent_visible"), &ProgressBar::is_percent_visible); ADD_GROUP("Percent", "percent_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "percent_visible"), "set_percent_visible", "is_percent_visible"); } ProgressBar::ProgressBar() { set_v_size_flags(0); percent_visible = true; } <commit_msg>ProgressBar: Set default step to 0.01<commit_after>/*************************************************************************/ /* progress_bar.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "progress_bar.h" Size2 ProgressBar::get_minimum_size() const { Ref<StyleBox> bg = get_stylebox("bg"); Ref<StyleBox> fg = get_stylebox("fg"); Ref<Font> font = get_font("font"); Size2 minimum_size = bg->get_minimum_size(); minimum_size.height = MAX(minimum_size.height, fg->get_minimum_size().height); minimum_size.width = MAX(minimum_size.width, fg->get_minimum_size().width); //if (percent_visible) { this is needed, else the progressbar will collapse minimum_size.height = MAX(minimum_size.height, bg->get_minimum_size().height + font->get_height()); //} return minimum_size; } void ProgressBar::_notification(int p_what) { if (p_what == NOTIFICATION_DRAW) { Ref<StyleBox> bg = get_stylebox("bg"); Ref<StyleBox> fg = get_stylebox("fg"); Ref<Font> font = get_font("font"); Color font_color = get_color("font_color"); draw_style_box(bg, Rect2(Point2(), get_size())); float r = get_as_ratio(); int mp = fg->get_minimum_size().width; int p = r * get_size().width - mp; if (p > 0) { draw_style_box(fg, Rect2(Point2(), Size2(p + fg->get_minimum_size().width, get_size().height))); } if (percent_visible) { String txt = itos(int(get_as_ratio() * 100)) + "%"; font->draw_halign(get_canvas_item(), Point2(0, font->get_ascent() + (get_size().height - font->get_height()) / 2), HALIGN_CENTER, get_size().width, txt, font_color); } } } void ProgressBar::set_percent_visible(bool p_visible) { percent_visible = p_visible; update(); } bool ProgressBar::is_percent_visible() const { return percent_visible; } void ProgressBar::_bind_methods() { ClassDB::bind_method(D_METHOD("set_percent_visible", "visible"), &ProgressBar::set_percent_visible); ClassDB::bind_method(D_METHOD("is_percent_visible"), &ProgressBar::is_percent_visible); ADD_GROUP("Percent", "percent_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "percent_visible"), "set_percent_visible", "is_percent_visible"); } ProgressBar::ProgressBar() { set_v_size_flags(0); set_step(0.01); percent_visible = true; } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2011-2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "molecule.h" #include "elements.h" #include <cassert> #include <algorithm> namespace Avogadro { namespace Core { Molecule::Molecule() : m_graphDirty(false) { } Molecule::~Molecule() { } size_t Molecule::size() const { return m_atomicNumbers.size(); } bool Molecule::isEmpty() const { return m_atomicNumbers.empty(); } void Molecule::setData(const std::string &name, const Variant &value) { m_data.setValue(name, value); } Variant Molecule::data(const std::string &name) const { return m_data.value(name); } void Molecule::setDataMap(const VariantMap &map) { m_data = map; } const VariantMap &Molecule::dataMap() const { return m_data; } VariantMap &Molecule::dataMap() { return m_data; } std::vector<unsigned char>& Molecule::atomicNumbers() { return m_atomicNumbers; } const std::vector<unsigned char>& Molecule::atomicNumbers() const { return m_atomicNumbers; } std::vector<Vector2>& Molecule::atomPositions2d() { return m_positions2d; } const std::vector<Vector2>& Molecule::atomPositions2d() const { return m_positions2d; } std::vector<Vector3>& Molecule::atomPositions3d() { return m_positions3d; } const std::vector<Vector3>& Molecule::atomPositions3d() const { return m_positions3d; } std::vector<std::pair<size_t, size_t> >& Molecule::bondPairs() { return m_bondPairs; } const std::vector<std::pair<size_t, size_t> >& Molecule::bondPairs() const { return m_bondPairs; } std::vector<unsigned char>& Molecule::bondOrders() { return m_bondOrders; } const std::vector<unsigned char>& Molecule::bondOrders() const { return m_bondOrders; } Graph& Molecule::graph() { updateGraph(); return m_graph; } const Graph& Molecule::graph() const { updateGraph(); return m_graph; } Atom Molecule::addAtom(unsigned char atomicNumber) { // Mark the graph as dirty. m_graphDirty = true; // Add the atomic number. m_atomicNumbers.push_back(atomicNumber); return Atom(this, m_atomicNumbers.size() - 1); } Atom Molecule::atom(size_t index) const { assert(index < size()); return Atom(const_cast<Molecule*>(this), index); } size_t Molecule::atomCount() const { return m_atomicNumbers.size(); } namespace { // Make an std::pair where the lower index is always first in the pair. This // offers us the guarantee that any given pair of atoms will always result in // a pair that is the same no matter what the order of the atoms given. std::pair<size_t, size_t> makeBondPair(const Atom &a, const Atom &b) { return std::make_pair(a.index() < b.index() ? a.index() : b.index(), a.index() < b.index() ? b.index() : a.index()); } } Bond Molecule::addBond(const Atom &a, const Atom &b, unsigned char bondOrder) { assert(a.isValid() && a.molecule() == this); assert(b.isValid() && b.molecule() == this); m_graphDirty = true; m_bondPairs.push_back(makeBondPair(a, b)); m_bondOrders.push_back(bondOrder); return Bond(this, m_bondPairs.size() - 1); } Bond Molecule::bond(size_t index) const { assert(index < bondCount()); return Bond(const_cast<Molecule*>(this), index); } Bond Molecule::bond(const Atom &a, const Atom &b) const { assert(a.isValid() && a.molecule() == this); assert(b.isValid() && b.molecule() == this); std::pair<size_t, size_t> bondPair = makeBondPair(a, b); std::vector<std::pair<size_t, size_t> >::const_iterator iter = std::find(m_bondPairs.begin(), m_bondPairs.end(), bondPair); if (iter == m_bondPairs.end()) return Bond(); size_t index = static_cast<size_t>(std::distance(m_bondPairs.begin(), iter)); return Bond(const_cast<Molecule *>(this), index); } std::vector<Bond> Molecule::bonds(const Atom &a) { if (!a.isValid()) return std::vector<Bond>(); std::vector<Bond> atomBonds; size_t atomIndex = a.index(); for (size_t i = 0; i < m_bondPairs.size(); ++i) if (m_bondPairs[i].first == atomIndex || m_bondPairs[i].second == atomIndex) atomBonds.push_back(Bond(this, i)); return atomBonds; } size_t Molecule::bondCount() const { return m_bondPairs.size(); } std::string Molecule::formula() const { // Adapted from chemkit: // A map of atomic symbols to their quantity. std::map<unsigned char, size_t> composition; for (std::vector<unsigned char>::const_iterator it = m_atomicNumbers.begin(), itEnd = m_atomicNumbers.end(); it != itEnd; ++it) { composition[*it]++; } std::stringstream result; std::map<unsigned char, size_t>::iterator iter; // Carbons first iter = composition.find(6); if (iter != composition.end()) { result << "C" << iter->second; composition.erase(iter); // If carbon is present, hydrogens are next. iter = composition.find(1); if (iter != composition.end()) { result << "H" << iter->second; composition.erase(iter); } } // The rest: iter = composition.begin(); while (iter != composition.end()) result << Elements::symbol(iter->first) << iter->second, ++iter; return result.str(); } // bond perception code ported from VTK's vtkSimpleBondPerceiver class void Molecule::perceiveBondsSimple() { // check for coordinates if (m_positions3d.size() != atomCount()) return; // the tolerance used in the comparisons double tolerance = 0.45; // cache atomic radii std::vector<double> radii(atomCount()); for (size_t i = 0; i < radii.size(); i++) radii[i] = Elements::radiusCovalent(m_atomicNumbers[i]); // check for bonds for (size_t i = 0; i < atomCount(); i++) { Vector3 ipos = m_positions3d[i]; for (size_t j = i + 1; j < atomCount(); j++) { double cutoff = radii[i] + radii[j] + tolerance; Vector3 jpos = m_positions3d[j]; Vector3 diff = jpos - ipos; if (std::fabs(diff[0]) > cutoff || std::fabs(diff[1]) > cutoff || std::fabs(diff[2]) > cutoff || (m_atomicNumbers[i] == 1 && m_atomicNumbers[j] == 1)) continue; // check radius and add bond if needed double cutoffSq = cutoff * cutoff; double diffsq = diff.squaredNorm(); if (diffsq < cutoffSq && diffsq > 0.1) addBond(atom(i), atom(j), 1); } } } void Molecule::updateGraph() const { if (!m_graphDirty) return; m_graphDirty = false; m_graph.clear(); m_graph.setSize(atomCount()); for (std::vector<std::pair<size_t, size_t> >::const_iterator it = m_bondPairs.begin(); it != m_bondPairs.end(); ++it) { m_graph.addEdge(it->first, it->second); } } } // end Core namespace } // end Avogadro namespace <commit_msg>Fix Molecule::formula for single atom cases.<commit_after>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2011-2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "molecule.h" #include "elements.h" #include <cassert> #include <algorithm> namespace Avogadro { namespace Core { Molecule::Molecule() : m_graphDirty(false) { } Molecule::~Molecule() { } size_t Molecule::size() const { return m_atomicNumbers.size(); } bool Molecule::isEmpty() const { return m_atomicNumbers.empty(); } void Molecule::setData(const std::string &name, const Variant &value) { m_data.setValue(name, value); } Variant Molecule::data(const std::string &name) const { return m_data.value(name); } void Molecule::setDataMap(const VariantMap &map) { m_data = map; } const VariantMap &Molecule::dataMap() const { return m_data; } VariantMap &Molecule::dataMap() { return m_data; } std::vector<unsigned char>& Molecule::atomicNumbers() { return m_atomicNumbers; } const std::vector<unsigned char>& Molecule::atomicNumbers() const { return m_atomicNumbers; } std::vector<Vector2>& Molecule::atomPositions2d() { return m_positions2d; } const std::vector<Vector2>& Molecule::atomPositions2d() const { return m_positions2d; } std::vector<Vector3>& Molecule::atomPositions3d() { return m_positions3d; } const std::vector<Vector3>& Molecule::atomPositions3d() const { return m_positions3d; } std::vector<std::pair<size_t, size_t> >& Molecule::bondPairs() { return m_bondPairs; } const std::vector<std::pair<size_t, size_t> >& Molecule::bondPairs() const { return m_bondPairs; } std::vector<unsigned char>& Molecule::bondOrders() { return m_bondOrders; } const std::vector<unsigned char>& Molecule::bondOrders() const { return m_bondOrders; } Graph& Molecule::graph() { updateGraph(); return m_graph; } const Graph& Molecule::graph() const { updateGraph(); return m_graph; } Atom Molecule::addAtom(unsigned char atomicNumber) { // Mark the graph as dirty. m_graphDirty = true; // Add the atomic number. m_atomicNumbers.push_back(atomicNumber); return Atom(this, m_atomicNumbers.size() - 1); } Atom Molecule::atom(size_t index) const { assert(index < size()); return Atom(const_cast<Molecule*>(this), index); } size_t Molecule::atomCount() const { return m_atomicNumbers.size(); } namespace { // Make an std::pair where the lower index is always first in the pair. This // offers us the guarantee that any given pair of atoms will always result in // a pair that is the same no matter what the order of the atoms given. std::pair<size_t, size_t> makeBondPair(const Atom &a, const Atom &b) { return std::make_pair(a.index() < b.index() ? a.index() : b.index(), a.index() < b.index() ? b.index() : a.index()); } } Bond Molecule::addBond(const Atom &a, const Atom &b, unsigned char bondOrder) { assert(a.isValid() && a.molecule() == this); assert(b.isValid() && b.molecule() == this); m_graphDirty = true; m_bondPairs.push_back(makeBondPair(a, b)); m_bondOrders.push_back(bondOrder); return Bond(this, m_bondPairs.size() - 1); } Bond Molecule::bond(size_t index) const { assert(index < bondCount()); return Bond(const_cast<Molecule*>(this), index); } Bond Molecule::bond(const Atom &a, const Atom &b) const { assert(a.isValid() && a.molecule() == this); assert(b.isValid() && b.molecule() == this); std::pair<size_t, size_t> bondPair = makeBondPair(a, b); std::vector<std::pair<size_t, size_t> >::const_iterator iter = std::find(m_bondPairs.begin(), m_bondPairs.end(), bondPair); if (iter == m_bondPairs.end()) return Bond(); size_t index = static_cast<size_t>(std::distance(m_bondPairs.begin(), iter)); return Bond(const_cast<Molecule *>(this), index); } std::vector<Bond> Molecule::bonds(const Atom &a) { if (!a.isValid()) return std::vector<Bond>(); std::vector<Bond> atomBonds; size_t atomIndex = a.index(); for (size_t i = 0; i < m_bondPairs.size(); ++i) if (m_bondPairs[i].first == atomIndex || m_bondPairs[i].second == atomIndex) atomBonds.push_back(Bond(this, i)); return atomBonds; } size_t Molecule::bondCount() const { return m_bondPairs.size(); } std::string Molecule::formula() const { // Adapted from chemkit: // A map of atomic symbols to their quantity. std::map<unsigned char, size_t> composition; for (std::vector<unsigned char>::const_iterator it = m_atomicNumbers.begin(), itEnd = m_atomicNumbers.end(); it != itEnd; ++it) { composition[*it]++; } std::stringstream result; std::map<unsigned char, size_t>::iterator iter; // Carbons first iter = composition.find(6); if (iter != composition.end()) { result << "C"; if (iter->second > 1) result << iter->second; composition.erase(iter); // If carbon is present, hydrogens are next. iter = composition.find(1); if (iter != composition.end()) { result << "H"; if (iter->second > 1) result << iter->second; composition.erase(iter); } } // The rest: iter = composition.begin(); while (iter != composition.end()) { result << Elements::symbol(iter->first); if (iter->second > 1) result << iter->second; ++iter; } return result.str(); } // bond perception code ported from VTK's vtkSimpleBondPerceiver class void Molecule::perceiveBondsSimple() { // check for coordinates if (m_positions3d.size() != atomCount()) return; // the tolerance used in the comparisons double tolerance = 0.45; // cache atomic radii std::vector<double> radii(atomCount()); for (size_t i = 0; i < radii.size(); i++) radii[i] = Elements::radiusCovalent(m_atomicNumbers[i]); // check for bonds for (size_t i = 0; i < atomCount(); i++) { Vector3 ipos = m_positions3d[i]; for (size_t j = i + 1; j < atomCount(); j++) { double cutoff = radii[i] + radii[j] + tolerance; Vector3 jpos = m_positions3d[j]; Vector3 diff = jpos - ipos; if (std::fabs(diff[0]) > cutoff || std::fabs(diff[1]) > cutoff || std::fabs(diff[2]) > cutoff || (m_atomicNumbers[i] == 1 && m_atomicNumbers[j] == 1)) continue; // check radius and add bond if needed double cutoffSq = cutoff * cutoff; double diffsq = diff.squaredNorm(); if (diffsq < cutoffSq && diffsq > 0.1) addBond(atom(i), atom(j), 1); } } } void Molecule::updateGraph() const { if (!m_graphDirty) return; m_graphDirty = false; m_graph.clear(); m_graph.setSize(atomCount()); for (std::vector<std::pair<size_t, size_t> >::const_iterator it = m_bondPairs.begin(); it != m_bondPairs.end(); ++it) { m_graph.addEdge(it->first, it->second); } } } // end Core namespace } // end Avogadro namespace <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include <osl/diagnose.h> #include <rtl/tencinfo.h> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/xml/sax/XAttributeList.hpp> #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/io/XSeekable.hpp> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #include <cppuhelper/supportsservice.hxx> #include <writerperfect/DocumentHandler.hxx> #include <writerperfect/WPXSvInputStream.hxx> #include <xmloff/attrlist.hxx> #include <sfx2/passwd.hxx> #include <ucbhelper/content.hxx> #include <libodfgen/libodfgen.hxx> #include <libwpd/libwpd.h> #include <libwpg/libwpg.h> #include "WordPerfectImportFilter.hxx" using ::ucbhelper::Content; using com::sun::star::uno::Sequence; using com::sun::star::uno::Reference; using com::sun::star::uno::Any; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::XInterface; using com::sun::star::uno::Exception; using com::sun::star::uno::RuntimeException; using com::sun::star::uno::XComponentContext; using com::sun::star::beans::PropertyValue; using com::sun::star::document::XFilter; using com::sun::star::document::XExtendedFilterDetection; using com::sun::star::ucb::XCommandEnvironment; using com::sun::star::io::XInputStream; using com::sun::star::document::XImporter; using com::sun::star::xml::sax::InputSource; using com::sun::star::xml::sax::XAttributeList; using com::sun::star::xml::sax::XDocumentHandler; using com::sun::star::xml::sax::XParser; using writerperfect::DocumentHandler; using writerperfect::WPXSvInputStream; static bool handleEmbeddedWPGObject(const librevenge::RVNGBinaryData &data, OdfDocumentHandler *pHandler, const OdfStreamType streamType) { OdgGenerator exporter; exporter.addDocumentHandler(pHandler, streamType); libwpg::WPGFileFormat fileFormat = libwpg::WPG_AUTODETECT; if (!libwpg::WPGraphics::isSupported(data.getDataStream())) fileFormat = libwpg::WPG_WPG1; return libwpg::WPGraphics::parse(data.getDataStream(), &exporter, fileFormat); } static bool handleEmbeddedWPGImage(const librevenge::RVNGBinaryData &input, librevenge::RVNGBinaryData &output) { libwpg::WPGFileFormat fileFormat = libwpg::WPG_AUTODETECT; if (!libwpg::WPGraphics::isSupported(input.getDataStream())) fileFormat = libwpg::WPG_WPG1; librevenge::RVNGStringVector svgOutput; librevenge::RVNGSVGDrawingGenerator aSVGGenerator(svgOutput, ""); if (!libwpg::WPGraphics::parse(input.getDataStream(), &aSVGGenerator, fileFormat)) return false; assert(1 == svgOutput.size()); output.clear(); output.append(reinterpret_cast<const unsigned char *>(svgOutput[0].cstr()), svgOutput[0].size()); return true; } bool SAL_CALL WordPerfectImportFilter::importImpl(const Sequence< ::com::sun::star::beans::PropertyValue > &aDescriptor) throw (RuntimeException, std::exception) { sal_Int32 nLength = aDescriptor.getLength(); const PropertyValue *pValue = aDescriptor.getConstArray(); Reference < XInputStream > xInputStream; for (sal_Int32 i = 0 ; i < nLength; i++) { if (pValue[i].Name == "InputStream") pValue[i].Value >>= xInputStream; } if (!xInputStream.is()) { OSL_ASSERT(false); return false; } WPXSvInputStream input(xInputStream); OString aUtf8Passwd; libwpd::WPDConfidence confidence = libwpd::WPDocument::isFileFormatSupported(&input); if (libwpd::WPD_CONFIDENCE_SUPPORTED_ENCRYPTION == confidence) { int unsuccessfulAttempts = 0; while (true) { ScopedVclPtrInstance< SfxPasswordDialog > aPasswdDlg(nullptr); aPasswdDlg->SetMinLen(0); if (!aPasswdDlg->Execute()) return false; OUString aPasswd = aPasswdDlg->GetPassword(); aUtf8Passwd = OUStringToOString(aPasswd, RTL_TEXTENCODING_UTF8); if (libwpd::WPD_PASSWORD_MATCH_OK == libwpd::WPDocument::verifyPassword(&input, aUtf8Passwd.getStr())) break; else unsuccessfulAttempts++; if (unsuccessfulAttempts == 3) // timeout after 3 password atempts return false; } } // An XML import service: what we push sax messages to.. Reference < XDocumentHandler > xInternalHandler( mxContext->getServiceManager()->createInstanceWithContext( "com.sun.star.comp.Writer.XMLOasisImporter", mxContext), css::uno::UNO_QUERY_THROW); // The XImporter sets up an empty target document for XDocumentHandler to write to.. Reference < XImporter > xImporter(xInternalHandler, UNO_QUERY); xImporter->setTargetDocument(mxDoc); // OO Document Handler: abstract class to handle document SAX messages, concrete implementation here // writes to in-memory target doc DocumentHandler xHandler(xInternalHandler); OdtGenerator collector; collector.addDocumentHandler(&xHandler, ODF_FLAT_XML); collector.registerEmbeddedObjectHandler("image/x-wpg", &handleEmbeddedWPGObject); collector.registerEmbeddedImageHandler("image/x-wpg", &handleEmbeddedWPGImage); if (libwpd::WPD_OK == libwpd::WPDocument::parse(&input, &collector, aUtf8Passwd.isEmpty() ? 0 : aUtf8Passwd.getStr())) return true; return false; } sal_Bool SAL_CALL WordPerfectImportFilter::filter(const Sequence< ::com::sun::star::beans::PropertyValue > &aDescriptor) throw (RuntimeException, std::exception) { return importImpl(aDescriptor); } void SAL_CALL WordPerfectImportFilter::cancel() throw (RuntimeException, std::exception) { } // XImporter void SAL_CALL WordPerfectImportFilter::setTargetDocument(const Reference< ::com::sun::star::lang::XComponent > &xDoc) throw (::com::sun::star::lang::IllegalArgumentException, RuntimeException, std::exception) { mxDoc = xDoc; } // XExtendedFilterDetection OUString SAL_CALL WordPerfectImportFilter::detect(Sequence< PropertyValue > &Descriptor) throw(RuntimeException, std::exception) { libwpd::WPDConfidence confidence = libwpd::WPD_CONFIDENCE_NONE; OUString sTypeName; sal_Int32 nLength = Descriptor.getLength(); sal_Int32 location = nLength; const PropertyValue *pValue = Descriptor.getConstArray(); Reference < XInputStream > xInputStream; for (sal_Int32 i = 0 ; i < nLength; i++) { if (pValue[i].Name == "TypeName") location=i; else if (pValue[i].Name == "InputStream") pValue[i].Value >>= xInputStream; } if (!xInputStream.is()) return OUString(); WPXSvInputStream input(xInputStream); confidence = libwpd::WPDocument::isFileFormatSupported(&input); if (confidence == libwpd::WPD_CONFIDENCE_EXCELLENT || confidence == libwpd::WPD_CONFIDENCE_SUPPORTED_ENCRYPTION) sTypeName = "writer_WordPerfect_Document"; if (!sTypeName.isEmpty()) { if (location == nLength) { Descriptor.realloc(nLength+1); Descriptor[location].Name = "TypeName"; } Descriptor[location].Value <<=sTypeName; } return sTypeName; } // XInitialization void SAL_CALL WordPerfectImportFilter::initialize(const Sequence< Any > &aArguments) throw (Exception, RuntimeException, std::exception) { Sequence < PropertyValue > aAnySeq; sal_Int32 nLength = aArguments.getLength(); if (nLength && (aArguments[0] >>= aAnySeq)) { const PropertyValue *pValue = aAnySeq.getConstArray(); nLength = aAnySeq.getLength(); for (sal_Int32 i = 0 ; i < nLength; i++) { if (pValue[i].Name == "Type") { pValue[i].Value >>= msFilterName; break; } } } } OUString WordPerfectImportFilter_getImplementationName() throw (RuntimeException) { return OUString("com.sun.star.comp.Writer.WordPerfectImportFilter"); } Sequence< OUString > SAL_CALL WordPerfectImportFilter_getSupportedServiceNames() throw (RuntimeException) { Sequence < OUString > aRet(2); OUString *pArray = aRet.getArray(); pArray[0] = "com.sun.star.document.ImportFilter"; pArray[1] = "com.sun.star.document.ExtendedTypeDetection"; return aRet; } Reference< XInterface > SAL_CALL WordPerfectImportFilter_createInstance(const Reference< XComponentContext > &rContext) throw(Exception) { return (cppu::OWeakObject *) new WordPerfectImportFilter(rContext); } // XServiceInfo OUString SAL_CALL WordPerfectImportFilter::getImplementationName() throw (RuntimeException, std::exception) { return WordPerfectImportFilter_getImplementationName(); } sal_Bool SAL_CALL WordPerfectImportFilter::supportsService(const OUString &rServiceName) throw (RuntimeException, std::exception) { return cppu::supportsService(this, rServiceName); } Sequence< OUString > SAL_CALL WordPerfectImportFilter::getSupportedServiceNames() throw (RuntimeException, std::exception) { return WordPerfectImportFilter_getSupportedServiceNames(); } WordPerfectImportFilterDialog::WordPerfectImportFilterDialog(const Reference< XComponentContext > &rContext) : mxContext(rContext) {} WordPerfectImportFilterDialog::~WordPerfectImportFilterDialog() { } void SAL_CALL WordPerfectImportFilterDialog::setTitle(const OUString &) throw (RuntimeException, std::exception) { } sal_Int16 SAL_CALL WordPerfectImportFilterDialog::execute() throw (RuntimeException, std::exception) { WPXSvInputStream input(mxInputStream); OString aUtf8Passwd; libwpd::WPDConfidence confidence = libwpd::WPDocument::isFileFormatSupported(&input); if (libwpd::WPD_CONFIDENCE_SUPPORTED_ENCRYPTION == confidence) { int unsuccessfulAttempts = 0; while (true) { ScopedVclPtrInstance< SfxPasswordDialog > aPasswdDlg(0); aPasswdDlg->SetMinLen(0); if (!aPasswdDlg->Execute()) return com::sun::star::ui::dialogs::ExecutableDialogResults::CANCEL; msPassword = aPasswdDlg->GetPassword().getStr(); aUtf8Passwd = OUStringToOString(msPassword, RTL_TEXTENCODING_UTF8); if (libwpd::WPD_PASSWORD_MATCH_OK == libwpd::WPDocument::verifyPassword(&input, aUtf8Passwd.getStr())) break; else unsuccessfulAttempts++; if (unsuccessfulAttempts == 3) // timeout after 3 password atempts return com::sun::star::ui::dialogs::ExecutableDialogResults::CANCEL; } } return com::sun::star::ui::dialogs::ExecutableDialogResults::OK; } Sequence<PropertyValue> SAL_CALL WordPerfectImportFilterDialog::getPropertyValues() throw(RuntimeException, std::exception) { Sequence<PropertyValue> aRet(1); PropertyValue *pArray = aRet.getArray(); pArray[0].Name = "Password"; pArray[0].Value <<= msPassword; return aRet; } void SAL_CALL WordPerfectImportFilterDialog::setPropertyValues(const Sequence<PropertyValue> &aProps) throw(com::sun::star::beans::UnknownPropertyException, com::sun::star::beans::PropertyVetoException, com::sun::star::lang::IllegalArgumentException, com::sun::star::lang::WrappedTargetException, RuntimeException, std::exception) { const PropertyValue *pPropArray = aProps.getConstArray(); long nPropCount = aProps.getLength(); for (long i = 0; i < nPropCount; i++) { const PropertyValue &rProp = pPropArray[i]; OUString aPropName = rProp.Name; if (aPropName == "Password") rProp.Value >>= msPassword; else if (aPropName == "InputStream") rProp.Value >>= mxInputStream; } } // XServiceInfo OUString SAL_CALL WordPerfectImportFilterDialog::getImplementationName() throw (RuntimeException, std::exception) { return WordPerfectImportFilterDialog_getImplementationName(); } sal_Bool SAL_CALL WordPerfectImportFilterDialog::supportsService(const OUString &rServiceName) throw (RuntimeException, std::exception) { return cppu::supportsService(this, rServiceName); } Sequence< OUString > SAL_CALL WordPerfectImportFilterDialog::getSupportedServiceNames() throw (RuntimeException, std::exception) { return WordPerfectImportFilterDialog_getSupportedServiceNames(); } OUString WordPerfectImportFilterDialog_getImplementationName() throw (RuntimeException) { return OUString("com.sun.star.comp.Writer.WordPerfectImportFilterDialog"); } Sequence< OUString > SAL_CALL WordPerfectImportFilterDialog_getSupportedServiceNames() throw (RuntimeException) { Sequence < OUString > aRet(1); OUString *pArray = aRet.getArray(); pArray[0] = "com.sun.star.ui.dialogs.FilterOptionsDialog"; return aRet; } Reference< XInterface > SAL_CALL WordPerfectImportFilterDialog_createInstance(const Reference< XComponentContext > &rContext) throw(Exception) { return (cppu::OWeakObject *) new WordPerfectImportFilterDialog(rContext); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>missing nullptr.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include <osl/diagnose.h> #include <rtl/tencinfo.h> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/xml/sax/XAttributeList.hpp> #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/io/XSeekable.hpp> #include <com/sun/star/uno/Reference.h> #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #include <cppuhelper/supportsservice.hxx> #include <writerperfect/DocumentHandler.hxx> #include <writerperfect/WPXSvInputStream.hxx> #include <xmloff/attrlist.hxx> #include <sfx2/passwd.hxx> #include <ucbhelper/content.hxx> #include <libodfgen/libodfgen.hxx> #include <libwpd/libwpd.h> #include <libwpg/libwpg.h> #include "WordPerfectImportFilter.hxx" using ::ucbhelper::Content; using com::sun::star::uno::Sequence; using com::sun::star::uno::Reference; using com::sun::star::uno::Any; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::XInterface; using com::sun::star::uno::Exception; using com::sun::star::uno::RuntimeException; using com::sun::star::uno::XComponentContext; using com::sun::star::beans::PropertyValue; using com::sun::star::document::XFilter; using com::sun::star::document::XExtendedFilterDetection; using com::sun::star::ucb::XCommandEnvironment; using com::sun::star::io::XInputStream; using com::sun::star::document::XImporter; using com::sun::star::xml::sax::InputSource; using com::sun::star::xml::sax::XAttributeList; using com::sun::star::xml::sax::XDocumentHandler; using com::sun::star::xml::sax::XParser; using writerperfect::DocumentHandler; using writerperfect::WPXSvInputStream; static bool handleEmbeddedWPGObject(const librevenge::RVNGBinaryData &data, OdfDocumentHandler *pHandler, const OdfStreamType streamType) { OdgGenerator exporter; exporter.addDocumentHandler(pHandler, streamType); libwpg::WPGFileFormat fileFormat = libwpg::WPG_AUTODETECT; if (!libwpg::WPGraphics::isSupported(data.getDataStream())) fileFormat = libwpg::WPG_WPG1; return libwpg::WPGraphics::parse(data.getDataStream(), &exporter, fileFormat); } static bool handleEmbeddedWPGImage(const librevenge::RVNGBinaryData &input, librevenge::RVNGBinaryData &output) { libwpg::WPGFileFormat fileFormat = libwpg::WPG_AUTODETECT; if (!libwpg::WPGraphics::isSupported(input.getDataStream())) fileFormat = libwpg::WPG_WPG1; librevenge::RVNGStringVector svgOutput; librevenge::RVNGSVGDrawingGenerator aSVGGenerator(svgOutput, ""); if (!libwpg::WPGraphics::parse(input.getDataStream(), &aSVGGenerator, fileFormat)) return false; assert(1 == svgOutput.size()); output.clear(); output.append(reinterpret_cast<const unsigned char *>(svgOutput[0].cstr()), svgOutput[0].size()); return true; } bool SAL_CALL WordPerfectImportFilter::importImpl(const Sequence< ::com::sun::star::beans::PropertyValue > &aDescriptor) throw (RuntimeException, std::exception) { sal_Int32 nLength = aDescriptor.getLength(); const PropertyValue *pValue = aDescriptor.getConstArray(); Reference < XInputStream > xInputStream; for (sal_Int32 i = 0 ; i < nLength; i++) { if (pValue[i].Name == "InputStream") pValue[i].Value >>= xInputStream; } if (!xInputStream.is()) { OSL_ASSERT(false); return false; } WPXSvInputStream input(xInputStream); OString aUtf8Passwd; libwpd::WPDConfidence confidence = libwpd::WPDocument::isFileFormatSupported(&input); if (libwpd::WPD_CONFIDENCE_SUPPORTED_ENCRYPTION == confidence) { int unsuccessfulAttempts = 0; while (true) { ScopedVclPtrInstance< SfxPasswordDialog > aPasswdDlg(nullptr); aPasswdDlg->SetMinLen(0); if (!aPasswdDlg->Execute()) return false; OUString aPasswd = aPasswdDlg->GetPassword(); aUtf8Passwd = OUStringToOString(aPasswd, RTL_TEXTENCODING_UTF8); if (libwpd::WPD_PASSWORD_MATCH_OK == libwpd::WPDocument::verifyPassword(&input, aUtf8Passwd.getStr())) break; else unsuccessfulAttempts++; if (unsuccessfulAttempts == 3) // timeout after 3 password atempts return false; } } // An XML import service: what we push sax messages to.. Reference < XDocumentHandler > xInternalHandler( mxContext->getServiceManager()->createInstanceWithContext( "com.sun.star.comp.Writer.XMLOasisImporter", mxContext), css::uno::UNO_QUERY_THROW); // The XImporter sets up an empty target document for XDocumentHandler to write to.. Reference < XImporter > xImporter(xInternalHandler, UNO_QUERY); xImporter->setTargetDocument(mxDoc); // OO Document Handler: abstract class to handle document SAX messages, concrete implementation here // writes to in-memory target doc DocumentHandler xHandler(xInternalHandler); OdtGenerator collector; collector.addDocumentHandler(&xHandler, ODF_FLAT_XML); collector.registerEmbeddedObjectHandler("image/x-wpg", &handleEmbeddedWPGObject); collector.registerEmbeddedImageHandler("image/x-wpg", &handleEmbeddedWPGImage); if (libwpd::WPD_OK == libwpd::WPDocument::parse(&input, &collector, aUtf8Passwd.isEmpty() ? 0 : aUtf8Passwd.getStr())) return true; return false; } sal_Bool SAL_CALL WordPerfectImportFilter::filter(const Sequence< ::com::sun::star::beans::PropertyValue > &aDescriptor) throw (RuntimeException, std::exception) { return importImpl(aDescriptor); } void SAL_CALL WordPerfectImportFilter::cancel() throw (RuntimeException, std::exception) { } // XImporter void SAL_CALL WordPerfectImportFilter::setTargetDocument(const Reference< ::com::sun::star::lang::XComponent > &xDoc) throw (::com::sun::star::lang::IllegalArgumentException, RuntimeException, std::exception) { mxDoc = xDoc; } // XExtendedFilterDetection OUString SAL_CALL WordPerfectImportFilter::detect(Sequence< PropertyValue > &Descriptor) throw(RuntimeException, std::exception) { libwpd::WPDConfidence confidence = libwpd::WPD_CONFIDENCE_NONE; OUString sTypeName; sal_Int32 nLength = Descriptor.getLength(); sal_Int32 location = nLength; const PropertyValue *pValue = Descriptor.getConstArray(); Reference < XInputStream > xInputStream; for (sal_Int32 i = 0 ; i < nLength; i++) { if (pValue[i].Name == "TypeName") location=i; else if (pValue[i].Name == "InputStream") pValue[i].Value >>= xInputStream; } if (!xInputStream.is()) return OUString(); WPXSvInputStream input(xInputStream); confidence = libwpd::WPDocument::isFileFormatSupported(&input); if (confidence == libwpd::WPD_CONFIDENCE_EXCELLENT || confidence == libwpd::WPD_CONFIDENCE_SUPPORTED_ENCRYPTION) sTypeName = "writer_WordPerfect_Document"; if (!sTypeName.isEmpty()) { if (location == nLength) { Descriptor.realloc(nLength+1); Descriptor[location].Name = "TypeName"; } Descriptor[location].Value <<=sTypeName; } return sTypeName; } // XInitialization void SAL_CALL WordPerfectImportFilter::initialize(const Sequence< Any > &aArguments) throw (Exception, RuntimeException, std::exception) { Sequence < PropertyValue > aAnySeq; sal_Int32 nLength = aArguments.getLength(); if (nLength && (aArguments[0] >>= aAnySeq)) { const PropertyValue *pValue = aAnySeq.getConstArray(); nLength = aAnySeq.getLength(); for (sal_Int32 i = 0 ; i < nLength; i++) { if (pValue[i].Name == "Type") { pValue[i].Value >>= msFilterName; break; } } } } OUString WordPerfectImportFilter_getImplementationName() throw (RuntimeException) { return OUString("com.sun.star.comp.Writer.WordPerfectImportFilter"); } Sequence< OUString > SAL_CALL WordPerfectImportFilter_getSupportedServiceNames() throw (RuntimeException) { Sequence < OUString > aRet(2); OUString *pArray = aRet.getArray(); pArray[0] = "com.sun.star.document.ImportFilter"; pArray[1] = "com.sun.star.document.ExtendedTypeDetection"; return aRet; } Reference< XInterface > SAL_CALL WordPerfectImportFilter_createInstance(const Reference< XComponentContext > &rContext) throw(Exception) { return (cppu::OWeakObject *) new WordPerfectImportFilter(rContext); } // XServiceInfo OUString SAL_CALL WordPerfectImportFilter::getImplementationName() throw (RuntimeException, std::exception) { return WordPerfectImportFilter_getImplementationName(); } sal_Bool SAL_CALL WordPerfectImportFilter::supportsService(const OUString &rServiceName) throw (RuntimeException, std::exception) { return cppu::supportsService(this, rServiceName); } Sequence< OUString > SAL_CALL WordPerfectImportFilter::getSupportedServiceNames() throw (RuntimeException, std::exception) { return WordPerfectImportFilter_getSupportedServiceNames(); } WordPerfectImportFilterDialog::WordPerfectImportFilterDialog(const Reference< XComponentContext > &rContext) : mxContext(rContext) {} WordPerfectImportFilterDialog::~WordPerfectImportFilterDialog() { } void SAL_CALL WordPerfectImportFilterDialog::setTitle(const OUString &) throw (RuntimeException, std::exception) { } sal_Int16 SAL_CALL WordPerfectImportFilterDialog::execute() throw (RuntimeException, std::exception) { WPXSvInputStream input(mxInputStream); OString aUtf8Passwd; libwpd::WPDConfidence confidence = libwpd::WPDocument::isFileFormatSupported(&input); if (libwpd::WPD_CONFIDENCE_SUPPORTED_ENCRYPTION == confidence) { int unsuccessfulAttempts = 0; while (true) { ScopedVclPtrInstance< SfxPasswordDialog > aPasswdDlg(nullptr); aPasswdDlg->SetMinLen(0); if (!aPasswdDlg->Execute()) return com::sun::star::ui::dialogs::ExecutableDialogResults::CANCEL; msPassword = aPasswdDlg->GetPassword().getStr(); aUtf8Passwd = OUStringToOString(msPassword, RTL_TEXTENCODING_UTF8); if (libwpd::WPD_PASSWORD_MATCH_OK == libwpd::WPDocument::verifyPassword(&input, aUtf8Passwd.getStr())) break; else unsuccessfulAttempts++; if (unsuccessfulAttempts == 3) // timeout after 3 password atempts return com::sun::star::ui::dialogs::ExecutableDialogResults::CANCEL; } } return com::sun::star::ui::dialogs::ExecutableDialogResults::OK; } Sequence<PropertyValue> SAL_CALL WordPerfectImportFilterDialog::getPropertyValues() throw(RuntimeException, std::exception) { Sequence<PropertyValue> aRet(1); PropertyValue *pArray = aRet.getArray(); pArray[0].Name = "Password"; pArray[0].Value <<= msPassword; return aRet; } void SAL_CALL WordPerfectImportFilterDialog::setPropertyValues(const Sequence<PropertyValue> &aProps) throw(com::sun::star::beans::UnknownPropertyException, com::sun::star::beans::PropertyVetoException, com::sun::star::lang::IllegalArgumentException, com::sun::star::lang::WrappedTargetException, RuntimeException, std::exception) { const PropertyValue *pPropArray = aProps.getConstArray(); long nPropCount = aProps.getLength(); for (long i = 0; i < nPropCount; i++) { const PropertyValue &rProp = pPropArray[i]; OUString aPropName = rProp.Name; if (aPropName == "Password") rProp.Value >>= msPassword; else if (aPropName == "InputStream") rProp.Value >>= mxInputStream; } } // XServiceInfo OUString SAL_CALL WordPerfectImportFilterDialog::getImplementationName() throw (RuntimeException, std::exception) { return WordPerfectImportFilterDialog_getImplementationName(); } sal_Bool SAL_CALL WordPerfectImportFilterDialog::supportsService(const OUString &rServiceName) throw (RuntimeException, std::exception) { return cppu::supportsService(this, rServiceName); } Sequence< OUString > SAL_CALL WordPerfectImportFilterDialog::getSupportedServiceNames() throw (RuntimeException, std::exception) { return WordPerfectImportFilterDialog_getSupportedServiceNames(); } OUString WordPerfectImportFilterDialog_getImplementationName() throw (RuntimeException) { return OUString("com.sun.star.comp.Writer.WordPerfectImportFilterDialog"); } Sequence< OUString > SAL_CALL WordPerfectImportFilterDialog_getSupportedServiceNames() throw (RuntimeException) { Sequence < OUString > aRet(1); OUString *pArray = aRet.getArray(); pArray[0] = "com.sun.star.ui.dialogs.FilterOptionsDialog"; return aRet; } Reference< XInterface > SAL_CALL WordPerfectImportFilterDialog_createInstance(const Reference< XComponentContext > &rContext) throw(Exception) { return (cppu::OWeakObject *) new WordPerfectImportFilterDialog(rContext); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <iostream> #include <fstream> #include <stdexcept> #include <mapnik/geom_util.hpp> // boost #include <boost/version.hpp> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <boost/filesystem/operations.hpp> #include "shape_featureset.hpp" #include "shape_index_featureset.hpp" #include "shape.hpp" DATASOURCE_PLUGIN(shape_datasource) using mapnik::String; using mapnik::Double; using mapnik::Integer; using mapnik::datasource_exception; using mapnik::filter_in_box; using mapnik::filter_at_point; using mapnik::attribute_descriptor; shape_datasource::shape_datasource(const parameters &params, bool bind) : datasource (params), type_(datasource::Vector), file_length_(0), indexed_(false), desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")) { boost::optional<std::string> file = params.get<std::string>("file"); if (!file) throw datasource_exception("Shape Plugin: missing <file> parameter"); boost::optional<std::string> base = params.get<std::string>("base"); if (base) shape_name_ = *base + "/" + *file; else shape_name_ = *file; boost::algorithm::ireplace_last(shape_name_,".shp",""); if (bind) { this->bind(); } } void shape_datasource::bind() const { if (is_bound_) return; if (!boost::filesystem::exists(shape_name_ + ".shp")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".shp' does not exist"); } if (boost::filesystem::is_directory(shape_name_ + ".shp")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".shp' appears to be a directory not a file"); } try { boost::shared_ptr<shape_io> shape_ref = boost::shared_ptr<shape_io>(new shape_io(shape_name_)); init(*shape_ref); for (int i=0;i<shape_ref->dbf().num_fields();++i) { field_descriptor const& fd=shape_ref->dbf().descriptor(i); std::string fld_name=fd.name_; switch (fd.type_) { case 'C': case 'D': case 'M': case 'L': desc_.add_descriptor(attribute_descriptor(fld_name, String)); break; case 'N': case 'F': { if (fd.dec_>0) { desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8)); } else { desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4)); } break; } default: #ifdef MAPNIK_DEBUG std::clog << "Shape Plugin: unknown type " << fd.type_ << std::endl; #endif break; } } // for indexed shapefiles we keep open the file descriptor for fast reads if (indexed_) { shape_ = shape_ref; } } catch (datasource_exception& ex) { std::clog << "Shape Plugin: error processing field attributes, " << ex.what() << std::endl; throw; } catch (...) // exception: pipe_select_interrupter: Too many open files { std::clog << "Shape Plugin: error processing field attributes" << std::endl; throw; } is_bound_ = true; } shape_datasource::~shape_datasource() {} void shape_datasource::init(shape_io& shape) const { //first read header from *.shp int file_code=shape.shp().read_xdr_integer(); if (file_code!=9994) { //invalid file code throw datasource_exception("Shape Plugin: " + (boost::format("wrong file code : %d") % file_code).str()); } shape.shp().skip(5*4); file_length_=shape.shp().read_xdr_integer(); int version=shape.shp().read_ndr_integer(); if (version!=1000) { //invalid version number throw datasource_exception("Shape Plugin: " + (boost::format("invalid version number: %d") % version).str()); } #ifdef MAPNIK_DEBUG int shape_type = shape.shp().read_ndr_integer(); #else shape.shp().skip(4); #endif shape.shp().read_envelope(extent_); #ifdef MAPNIK_DEBUG double zmin = shape.shp().read_double(); double zmax = shape.shp().read_double(); double mmin = shape.shp().read_double(); double mmax = shape.shp().read_double(); std::clog << "Shape Plugin: Z min/max " << zmin << "," << zmax << std::endl; std::clog << "Shape Plugin: M min/max " << mmin << "," << mmax << "\n"; #else shape.shp().skip(4*8); #endif // check if we have an index file around indexed_ = shape.has_index(); //std::string index_name(shape_name_+".index"); //std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary); //if (file) //{ // indexed_=true; // file.close(); //} //else //{ // std::clog << "### Notice: no .index file found for " + shape_name_ + ".shp, use the 'shapeindex' program to build an index for faster rendering\n"; //} #ifdef MAPNIK_DEBUG std::clog << "Shape Plugin: extent=" << extent_ << std::endl; std::clog << "Shape Plugin: file_length=" << file_length_ << std::endl; std::clog << "Shape Plugin: shape_type=" << shape_type << std::endl; #endif } std::string shape_datasource::name() { return "shape"; } int shape_datasource::type() const { return type_; } layer_descriptor shape_datasource::get_descriptor() const { if (!is_bound_) bind(); return desc_; } featureset_ptr shape_datasource::features(const query& q) const { if (!is_bound_) bind(); filter_in_box filter(q.get_bbox()); if (indexed_) { shape_->shp().seek(0); return featureset_ptr (new shape_index_featureset<filter_in_box>(filter, *shape_, q.property_names(), desc_.get_encoding())); } else { return featureset_ptr (new shape_featureset<filter_in_box>(filter, shape_name_, q.property_names(), desc_.get_encoding(), file_length_)); } } featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const { if (!is_bound_) bind(); filter_at_point filter(pt); // collect all attribute names std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors(); std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin(); std::vector<attribute_descriptor>::const_iterator end = desc_vector.end(); std::set<std::string> names; while (itr != end) { names.insert(itr->get_name()); ++itr; } if (indexed_) { shape_->shp().seek(0); return featureset_ptr (new shape_index_featureset<filter_at_point>(filter, *shape_, names, desc_.get_encoding())); } else { return featureset_ptr (new shape_featureset<filter_at_point>(filter, shape_name_, names, desc_.get_encoding(), file_length_)); } } box2d<double> shape_datasource::envelope() const { if (!is_bound_) bind(); return extent_; } <commit_msg>shape.input: check if .dbf exists and throw up front if not rather than letting shape_io fail<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <iostream> #include <fstream> #include <stdexcept> #include <mapnik/geom_util.hpp> // boost #include <boost/version.hpp> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <boost/filesystem/operations.hpp> #include "shape_featureset.hpp" #include "shape_index_featureset.hpp" #include "shape.hpp" DATASOURCE_PLUGIN(shape_datasource) using mapnik::String; using mapnik::Double; using mapnik::Integer; using mapnik::datasource_exception; using mapnik::filter_in_box; using mapnik::filter_at_point; using mapnik::attribute_descriptor; shape_datasource::shape_datasource(const parameters &params, bool bind) : datasource (params), type_(datasource::Vector), file_length_(0), indexed_(false), desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")) { boost::optional<std::string> file = params.get<std::string>("file"); if (!file) throw datasource_exception("Shape Plugin: missing <file> parameter"); boost::optional<std::string> base = params.get<std::string>("base"); if (base) shape_name_ = *base + "/" + *file; else shape_name_ = *file; boost::algorithm::ireplace_last(shape_name_,".shp",""); if (bind) { this->bind(); } } void shape_datasource::bind() const { if (is_bound_) return; if (!boost::filesystem::exists(shape_name_ + ".shp")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".shp' does not exist"); } if (boost::filesystem::is_directory(shape_name_ + ".shp")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".shp' appears to be a directory not a file"); } if (!boost::filesystem::exists(shape_name_ + ".dbf")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".dbf' does not exist"); } try { boost::shared_ptr<shape_io> shape_ref = boost::shared_ptr<shape_io>(new shape_io(shape_name_)); init(*shape_ref); for (int i=0;i<shape_ref->dbf().num_fields();++i) { field_descriptor const& fd=shape_ref->dbf().descriptor(i); std::string fld_name=fd.name_; switch (fd.type_) { case 'C': case 'D': case 'M': case 'L': desc_.add_descriptor(attribute_descriptor(fld_name, String)); break; case 'N': case 'F': { if (fd.dec_>0) { desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8)); } else { desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4)); } break; } default: #ifdef MAPNIK_DEBUG std::clog << "Shape Plugin: unknown type " << fd.type_ << std::endl; #endif break; } } // for indexed shapefiles we keep open the file descriptor for fast reads if (indexed_) { shape_ = shape_ref; } } catch (const datasource_exception& ex) { std::clog << "Shape Plugin: error processing field attributes, " << ex.what() << std::endl; throw; } catch (const std::exception& ex) { std::clog << "Shape Plugin: error processing field attributes, " << ex.what() << std::endl; throw; } catch (...) // exception: pipe_select_interrupter: Too many open files { std::clog << "Shape Plugin: error processing field attributes" << std::endl; throw; } is_bound_ = true; } shape_datasource::~shape_datasource() {} void shape_datasource::init(shape_io& shape) const { //first read header from *.shp int file_code=shape.shp().read_xdr_integer(); if (file_code!=9994) { //invalid file code throw datasource_exception("Shape Plugin: " + (boost::format("wrong file code : %d") % file_code).str()); } shape.shp().skip(5*4); file_length_=shape.shp().read_xdr_integer(); int version=shape.shp().read_ndr_integer(); if (version!=1000) { //invalid version number throw datasource_exception("Shape Plugin: " + (boost::format("invalid version number: %d") % version).str()); } #ifdef MAPNIK_DEBUG int shape_type = shape.shp().read_ndr_integer(); #else shape.shp().skip(4); #endif shape.shp().read_envelope(extent_); #ifdef MAPNIK_DEBUG double zmin = shape.shp().read_double(); double zmax = shape.shp().read_double(); double mmin = shape.shp().read_double(); double mmax = shape.shp().read_double(); std::clog << "Shape Plugin: Z min/max " << zmin << "," << zmax << std::endl; std::clog << "Shape Plugin: M min/max " << mmin << "," << mmax << "\n"; #else shape.shp().skip(4*8); #endif // check if we have an index file around indexed_ = shape.has_index(); //std::string index_name(shape_name_+".index"); //std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary); //if (file) //{ // indexed_=true; // file.close(); //} //else //{ // std::clog << "### Notice: no .index file found for " + shape_name_ + ".shp, use the 'shapeindex' program to build an index for faster rendering\n"; //} #ifdef MAPNIK_DEBUG std::clog << "Shape Plugin: extent=" << extent_ << std::endl; std::clog << "Shape Plugin: file_length=" << file_length_ << std::endl; std::clog << "Shape Plugin: shape_type=" << shape_type << std::endl; #endif } std::string shape_datasource::name() { return "shape"; } int shape_datasource::type() const { return type_; } layer_descriptor shape_datasource::get_descriptor() const { if (!is_bound_) bind(); return desc_; } featureset_ptr shape_datasource::features(const query& q) const { if (!is_bound_) bind(); filter_in_box filter(q.get_bbox()); if (indexed_) { shape_->shp().seek(0); return featureset_ptr (new shape_index_featureset<filter_in_box>(filter, *shape_, q.property_names(), desc_.get_encoding())); } else { return featureset_ptr (new shape_featureset<filter_in_box>(filter, shape_name_, q.property_names(), desc_.get_encoding(), file_length_)); } } featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const { if (!is_bound_) bind(); filter_at_point filter(pt); // collect all attribute names std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors(); std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin(); std::vector<attribute_descriptor>::const_iterator end = desc_vector.end(); std::set<std::string> names; while (itr != end) { names.insert(itr->get_name()); ++itr; } if (indexed_) { shape_->shp().seek(0); return featureset_ptr (new shape_index_featureset<filter_at_point>(filter, *shape_, names, desc_.get_encoding())); } else { return featureset_ptr (new shape_featureset<filter_at_point>(filter, shape_name_, names, desc_.get_encoding(), file_length_)); } } box2d<double> shape_datasource::envelope() const { if (!is_bound_) bind(); return extent_; } <|endoftext|>
<commit_before>/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <thread> #include "src/cpp/server/rpc_service_method.h" #include "test/cpp/util/echo.pb.h" #include "net/util/netutil.h" #include <grpc++/channel_interface.h> #include <grpc++/client_context.h> #include <grpc++/create_channel.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc++/server_context.h> #include <grpc++/status.h> #include <grpc++/stream.h> #include <gtest/gtest.h> #include <grpc/grpc.h> #include <grpc/support/thd.h> using grpc::cpp::test::util::EchoRequest; using grpc::cpp::test::util::EchoResponse; using grpc::cpp::test::util::TestService; namespace grpc { class TestServiceImpl : public TestService::Service { public: Status Echo(ServerContext* context, const EchoRequest* request, EchoResponse* response) { response->set_message(request->message()); return Status::OK; } // Unimplemented is left unimplemented to test the returned error. Status RequestStream(ServerContext* context, ServerReader<EchoRequest>* reader, EchoResponse* response) { EchoRequest request; response->set_message(""); while (reader->Read(&request)) { response->mutable_message()->append(request.message()); } return Status::OK; } // Return 3 messages. // TODO(yangg) make it generic by adding a parameter into EchoRequest Status ResponseStream(ServerContext* context, const EchoRequest* request, ServerWriter<EchoResponse>* writer) { EchoResponse response; response.set_message(request->message() + "0"); writer->Write(response); response.set_message(request->message() + "1"); writer->Write(response); response.set_message(request->message() + "2"); writer->Write(response); return Status::OK; } Status BidiStream(ServerContext* context, ServerReaderWriter<EchoResponse, EchoRequest>* stream) { EchoRequest request; EchoResponse response; while (stream->Read(&request)) { gpr_log(GPR_INFO, "recv msg %s", request.message().c_str()); response.set_message(request.message()); stream->Write(response); } return Status::OK; } }; class End2endTest : public ::testing::Test { protected: void SetUp() override { int port = PickUnusedPortOrDie(); server_address_ << "localhost:" << port; // Setup server ServerBuilder builder; builder.AddPort(server_address_.str()); builder.RegisterService(service_.service()); server_ = builder.BuildAndStart(); } void TearDown() override { server_->Shutdown(); } std::unique_ptr<Server> server_; std::ostringstream server_address_; TestServiceImpl service_; }; static void SendRpc(const grpc::string& server_address, int num_rpcs) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; request.set_message("Hello"); for (int i = 0; i < num_rpcs; ++i) { ClientContext context; Status s = stub->Echo(&context, request, &response); EXPECT_EQ(response.message(), request.message()); EXPECT_TRUE(s.IsOk()); } delete stub; } TEST_F(End2endTest, SimpleRpc) { SendRpc(server_address_.str(), 1); } TEST_F(End2endTest, MultipleRpcs) { vector<std::thread*> threads; for (int i = 0; i < 10; ++i) { threads.push_back(new std::thread(SendRpc, server_address_.str(), 10)); } for (int i = 0; i < 10; ++i) { threads[i]->join(); delete threads[i]; } } TEST_F(End2endTest, UnimplementedRpc) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; request.set_message("Hello"); ClientContext context; Status s = stub->Unimplemented(&context, request, &response); EXPECT_FALSE(s.IsOk()); EXPECT_EQ(s.code(), grpc::StatusCode::UNIMPLEMENTED); EXPECT_EQ(s.details(), ""); EXPECT_EQ(response.message(), ""); delete stub; } TEST_F(End2endTest, RequestStreamOneRequest) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; ClientContext context; ClientWriter<EchoRequest>* stream = stub->RequestStream(&context, &response); request.set_message("hello"); EXPECT_TRUE(stream->Write(request)); stream->WritesDone(); Status s = stream->Wait(); EXPECT_EQ(response.message(), request.message()); EXPECT_TRUE(s.IsOk()); delete stream; delete stub; } TEST_F(End2endTest, RequestStreamTwoRequests) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; ClientContext context; ClientWriter<EchoRequest>* stream = stub->RequestStream(&context, &response); request.set_message("hello"); EXPECT_TRUE(stream->Write(request)); EXPECT_TRUE(stream->Write(request)); stream->WritesDone(); Status s = stream->Wait(); EXPECT_EQ(response.message(), "hellohello"); EXPECT_TRUE(s.IsOk()); delete stream; delete stub; } TEST_F(End2endTest, ResponseStream) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; ClientContext context; request.set_message("hello"); ClientReader<EchoResponse>* stream = stub->ResponseStream(&context, &request); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message() + "0"); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message() + "1"); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message() + "2"); EXPECT_FALSE(stream->Read(&response)); Status s = stream->Wait(); EXPECT_TRUE(s.IsOk()); delete stream; delete stub; } TEST_F(End2endTest, BidiStream) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; ClientContext context; grpc::string msg("hello"); ClientReaderWriter<EchoRequest, EchoResponse>* stream = stub->BidiStream(&context); request.set_message(msg + "0"); EXPECT_TRUE(stream->Write(request)); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message()); request.set_message(msg + "1"); EXPECT_TRUE(stream->Write(request)); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message()); request.set_message(msg + "2"); EXPECT_TRUE(stream->Write(request)); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message()); stream->WritesDone(); EXPECT_FALSE(stream->Read(&response)); Status s = stream->Wait(); EXPECT_TRUE(s.IsOk()); delete stream; delete stub; } } // namespace grpc int main(int argc, char** argv) { grpc_init(); ::testing::InitGoogleTest(&argc, argv); int result = RUN_ALL_TESTS(); grpc_shutdown(); return result; } <commit_msg>Add a test where client side sees a deadline expired status.<commit_after>/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <thread> #include "src/cpp/server/rpc_service_method.h" #include "test/cpp/util/echo.pb.h" #include "net/util/netutil.h" #include <grpc++/channel_interface.h> #include <grpc++/client_context.h> #include <grpc++/create_channel.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc++/server_context.h> #include <grpc++/status.h> #include <grpc++/stream.h> #include <gtest/gtest.h> #include <grpc/grpc.h> #include <grpc/support/thd.h> using grpc::cpp::test::util::EchoRequest; using grpc::cpp::test::util::EchoResponse; using grpc::cpp::test::util::TestService; namespace grpc { class TestServiceImpl : public TestService::Service { public: Status Echo(ServerContext* context, const EchoRequest* request, EchoResponse* response) { response->set_message(request->message()); return Status::OK; } // Unimplemented is left unimplemented to test the returned error. Status RequestStream(ServerContext* context, ServerReader<EchoRequest>* reader, EchoResponse* response) { EchoRequest request; response->set_message(""); while (reader->Read(&request)) { response->mutable_message()->append(request.message()); } return Status::OK; } // Return 3 messages. // TODO(yangg) make it generic by adding a parameter into EchoRequest Status ResponseStream(ServerContext* context, const EchoRequest* request, ServerWriter<EchoResponse>* writer) { EchoResponse response; response.set_message(request->message() + "0"); writer->Write(response); response.set_message(request->message() + "1"); writer->Write(response); response.set_message(request->message() + "2"); writer->Write(response); return Status::OK; } Status BidiStream(ServerContext* context, ServerReaderWriter<EchoResponse, EchoRequest>* stream) { EchoRequest request; EchoResponse response; while (stream->Read(&request)) { gpr_log(GPR_INFO, "recv msg %s", request.message().c_str()); response.set_message(request.message()); stream->Write(response); } return Status::OK; } }; class End2endTest : public ::testing::Test { protected: void SetUp() override { int port = PickUnusedPortOrDie(); server_address_ << "localhost:" << port; // Setup server ServerBuilder builder; builder.AddPort(server_address_.str()); builder.RegisterService(service_.service()); server_ = builder.BuildAndStart(); } void TearDown() override { server_->Shutdown(); } std::unique_ptr<Server> server_; std::ostringstream server_address_; TestServiceImpl service_; }; static void SendRpc(const grpc::string& server_address, int num_rpcs) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; request.set_message("Hello"); for (int i = 0; i < num_rpcs; ++i) { ClientContext context; Status s = stub->Echo(&context, request, &response); EXPECT_EQ(response.message(), request.message()); EXPECT_TRUE(s.IsOk()); } delete stub; } TEST_F(End2endTest, SimpleRpc) { SendRpc(server_address_.str(), 1); } TEST_F(End2endTest, MultipleRpcs) { vector<std::thread*> threads; for (int i = 0; i < 10; ++i) { threads.push_back(new std::thread(SendRpc, server_address_.str(), 10)); } for (int i = 0; i < 10; ++i) { threads[i]->join(); delete threads[i]; } } // Set a 10us deadline and make sure proper error is returned. TEST_F(End2endTest, RpcDeadlineExpires) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; request.set_message("Hello"); ClientContext context; std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + std::chrono::microseconds(10); context.set_absolute_deadline(deadline); Status s = stub->Echo(&context, request, &response); // TODO(yangg) use correct error code when b/18793983 is fixed. // EXPECT_EQ(StatusCode::DEADLINE_EXCEEDED, s.code()); EXPECT_EQ(StatusCode::CANCELLED, s.code()); delete stub; } TEST_F(End2endTest, UnimplementedRpc) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; request.set_message("Hello"); ClientContext context; Status s = stub->Unimplemented(&context, request, &response); EXPECT_FALSE(s.IsOk()); EXPECT_EQ(s.code(), grpc::StatusCode::UNIMPLEMENTED); EXPECT_EQ(s.details(), ""); EXPECT_EQ(response.message(), ""); delete stub; } TEST_F(End2endTest, RequestStreamOneRequest) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; ClientContext context; ClientWriter<EchoRequest>* stream = stub->RequestStream(&context, &response); request.set_message("hello"); EXPECT_TRUE(stream->Write(request)); stream->WritesDone(); Status s = stream->Wait(); EXPECT_EQ(response.message(), request.message()); EXPECT_TRUE(s.IsOk()); delete stream; delete stub; } TEST_F(End2endTest, RequestStreamTwoRequests) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; ClientContext context; ClientWriter<EchoRequest>* stream = stub->RequestStream(&context, &response); request.set_message("hello"); EXPECT_TRUE(stream->Write(request)); EXPECT_TRUE(stream->Write(request)); stream->WritesDone(); Status s = stream->Wait(); EXPECT_EQ(response.message(), "hellohello"); EXPECT_TRUE(s.IsOk()); delete stream; delete stub; } TEST_F(End2endTest, ResponseStream) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; ClientContext context; request.set_message("hello"); ClientReader<EchoResponse>* stream = stub->ResponseStream(&context, &request); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message() + "0"); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message() + "1"); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message() + "2"); EXPECT_FALSE(stream->Read(&response)); Status s = stream->Wait(); EXPECT_TRUE(s.IsOk()); delete stream; delete stub; } TEST_F(End2endTest, BidiStream) { std::shared_ptr<ChannelInterface> channel = CreateChannel(server_address_.str()); TestService::Stub* stub = TestService::NewStub(channel); EchoRequest request; EchoResponse response; ClientContext context; grpc::string msg("hello"); ClientReaderWriter<EchoRequest, EchoResponse>* stream = stub->BidiStream(&context); request.set_message(msg + "0"); EXPECT_TRUE(stream->Write(request)); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message()); request.set_message(msg + "1"); EXPECT_TRUE(stream->Write(request)); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message()); request.set_message(msg + "2"); EXPECT_TRUE(stream->Write(request)); EXPECT_TRUE(stream->Read(&response)); EXPECT_EQ(response.message(), request.message()); stream->WritesDone(); EXPECT_FALSE(stream->Read(&response)); Status s = stream->Wait(); EXPECT_TRUE(s.IsOk()); delete stream; delete stub; } } // namespace grpc int main(int argc, char** argv) { grpc_init(); ::testing::InitGoogleTest(&argc, argv); int result = RUN_ALL_TESTS(); grpc_shutdown(); return result; } <|endoftext|>
<commit_before>#include "barrier.h" #include "thread.h" #include "stream.h" Stream::Stream() : Thread(), buffer(NULL), active(true), established(false) { buffer = new char[BUFFER_SIZE]; for (unsigned i = 0; i < BUFFER_SIZE; ++i) { buffer[i] = 'A'; } } Stream::~Stream() { stop(); delete[] buffer; } void Stream::stop() { active = false; } bool Stream::is_active() { return active && established; // TODO: Override this in client and server } <commit_msg>shared buffer<commit_after>#include "barrier.h" #include "thread.h" #include "stream.h" static char buffer[BUFFER_SIZE]; Stream::Stream() : Thread(), buffer(::buffer), active(true), established(false) { } Stream::~Stream() { stop(); } void Stream::stop() { active = false; } bool Stream::is_active() { return active && established; // TODO: Override this in client and server } <|endoftext|>
<commit_before><commit_msg>Removed `floyd_warshall_shader_CSV_float_compute_task`.<commit_after><|endoftext|>
<commit_before>#include "Bitmap.h" #include "Config.h" #include "SettingData.h" #include "ImageData.h" //#include "Image.h" #include "Symbol.h" #include "SymbolMgr.h" #include "FileType.h" #include "FileHelper.h" #include "Exception.h" #include "Snapshoot.h" #include "ImageTrim.h" #include <gl/glew.h> //#include <wx/filename.h> //#include <easyimage.h> namespace ee { static const int SMALL_SIZE = 24; static const float MAX_WIDTH = 150.0f; static const float SCALE = 0.5f; Bitmap::Bitmap() : m_bmp_large(NULL) , m_bmp_small(NULL) { } Bitmap::~Bitmap() { BitmapMgr::Instance()->RemoveItem(m_filename); delete m_bmp_large; } bool Bitmap::LoadFromFile(const std::string& filepath) { if (!Config::Instance()->GetSettings().load_image) { return true; } if (!FileHelper::IsFileExist(filepath)) { throw Exception("File: %s don't exist!", filepath.c_str()); } m_filename = filepath; const GLubyte* test = glGetString(GL_VERSION); if (!test) { return true; } static bool inited = false; if (!inited) { wxInitAllImageHandlers(); inited = true; } if (filepath.find("pvr") != std::string::npos) { ImageData* img_data = ImageDataMgr::Instance()->GetItem(filepath); wxImage image(img_data->GetWidth(), img_data->GetHeight(), (unsigned char*)(img_data->GetPixelData()), true); // image.SetData((unsigned char*)(img_data->GetPixelData()), img_data->GetWidth(), img_data->GetHeight()); InitBmp(image, true); } else if (FileType::IsType(filepath, FileType::e_image)) { wxImage image; GetImage(filepath, image); InitBmp(image, true); } else if (FileType::IsType(filepath, FileType::e_terrain2d)) { ; } else { Symbol* symbol = SymbolMgr::Instance()->FetchSymbol(filepath); Rect rect = symbol->GetSize(); float w = std::max(1.0f, rect.Width()), h = std::max(1.0f, rect.Height()); float scale = w > (MAX_WIDTH / SCALE) ? (MAX_WIDTH / w) : SCALE; w *= scale; h *= scale; Snapshoot ss(w, h); unsigned char* rgba = ss.OutputToMemory(symbol, true, scale); unsigned char* rgb = TransRGBA2RGB(rgba, w, h); delete[] rgba; wxImage image(w, h, rgb, true); InitBmp(image, false); delete[] rgb; symbol->Release(); } return true; } void Bitmap::InitBmp(const wxImage& image, bool need_scale) { { if (m_bmp_large) { delete m_bmp_large; } float w = image.GetWidth(), h = image.GetHeight(); float scale = 1; if (need_scale) { scale = w > (MAX_WIDTH / SCALE) ? (MAX_WIDTH / w) : SCALE; } w = std::max(1.0f, w * scale); h = std::max(1.0f, h * scale); m_bmp_large = new wxBitmap(image.Scale(w, h)); } { if (m_bmp_small) { delete m_bmp_small; } float w = image.GetWidth(), h = image.GetHeight(); float scale = (float)SMALL_SIZE / w; w = std::max(1.0f, w * scale); h = std::max(1.0f, h * scale); m_bmp_small = new wxBitmap(image.Scale(w, h)); } } unsigned char* Bitmap::TransRGBA2RGB(unsigned char* rgba, int width, int height) { unsigned char* rgb = new unsigned char[width*height*3]; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { int src = (i*width+j)*4; int dst = (i*width+j)*3; memcpy(&rgb[dst], &rgba[src], sizeof(unsigned char) * 3); } } return rgb; } void Bitmap::GetImage(const std::string& filepath, wxImage& dst_img) { ImageData* img_data = ImageDataMgr::Instance()->GetItem(filepath); int h = img_data->GetHeight(); ImageTrim trim(*img_data); Rect trim_r = trim.Trim(); img_data->Release(); if (trim_r.IsValid()) { wxImage wx_img; wx_img.LoadFile(filepath); wxRect wx_rect; wx_rect.SetLeft(trim_r.xmin); wx_rect.SetRight(trim_r.xmax - 1); wx_rect.SetTop(h - trim_r.ymax); wx_rect.SetBottom(h - trim_r.ymin - 1); dst_img = wx_img.GetSubImage(wx_rect); } else { dst_img.LoadFile(filepath); } } }<commit_msg>[FIXED] load bitmap with size less than 1<commit_after>#include "Bitmap.h" #include "Config.h" #include "SettingData.h" #include "ImageData.h" //#include "Image.h" #include "Symbol.h" #include "SymbolMgr.h" #include "FileType.h" #include "FileHelper.h" #include "Exception.h" #include "Snapshoot.h" #include "ImageTrim.h" #include <gl/glew.h> //#include <wx/filename.h> //#include <easyimage.h> namespace ee { static const int SMALL_SIZE = 24; static const float MAX_WIDTH = 150.0f; static const float SCALE = 0.5f; Bitmap::Bitmap() : m_bmp_large(NULL) , m_bmp_small(NULL) { } Bitmap::~Bitmap() { BitmapMgr::Instance()->RemoveItem(m_filename); delete m_bmp_large; } bool Bitmap::LoadFromFile(const std::string& filepath) { if (!Config::Instance()->GetSettings().load_image) { return true; } if (!FileHelper::IsFileExist(filepath)) { throw Exception("File: %s don't exist!", filepath.c_str()); } m_filename = filepath; const GLubyte* test = glGetString(GL_VERSION); if (!test) { return true; } static bool inited = false; if (!inited) { wxInitAllImageHandlers(); inited = true; } if (filepath.find("pvr") != std::string::npos) { ImageData* img_data = ImageDataMgr::Instance()->GetItem(filepath); wxImage image(img_data->GetWidth(), img_data->GetHeight(), (unsigned char*)(img_data->GetPixelData()), true); // image.SetData((unsigned char*)(img_data->GetPixelData()), img_data->GetWidth(), img_data->GetHeight()); InitBmp(image, true); } else if (FileType::IsType(filepath, FileType::e_image)) { wxImage image; GetImage(filepath, image); InitBmp(image, true); } else if (FileType::IsType(filepath, FileType::e_terrain2d)) { ; } else { Symbol* symbol = SymbolMgr::Instance()->FetchSymbol(filepath); Rect rect = symbol->GetSize(); float w = std::max(1.0f, rect.Width()), h = std::max(1.0f, rect.Height()); float scale = w > (MAX_WIDTH / SCALE) ? (MAX_WIDTH / w) : SCALE; w *= scale; h *= scale; w = std::max(1.0f, w); h = std::max(1.0f, h); Snapshoot ss(w, h); unsigned char* rgba = ss.OutputToMemory(symbol, true, scale); unsigned char* rgb = TransRGBA2RGB(rgba, w, h); delete[] rgba; wxImage image(w, h, rgb, true); InitBmp(image, false); delete[] rgb; symbol->Release(); } return true; } void Bitmap::InitBmp(const wxImage& image, bool need_scale) { { if (m_bmp_large) { delete m_bmp_large; } float w = image.GetWidth(), h = image.GetHeight(); float scale = 1; if (need_scale) { scale = w > (MAX_WIDTH / SCALE) ? (MAX_WIDTH / w) : SCALE; } w = std::max(1.0f, w * scale); h = std::max(1.0f, h * scale); m_bmp_large = new wxBitmap(image.Scale(w, h)); } { if (m_bmp_small) { delete m_bmp_small; } float w = image.GetWidth(), h = image.GetHeight(); float scale = (float)SMALL_SIZE / w; w = std::max(1.0f, w * scale); h = std::max(1.0f, h * scale); m_bmp_small = new wxBitmap(image.Scale(w, h)); } } unsigned char* Bitmap::TransRGBA2RGB(unsigned char* rgba, int width, int height) { unsigned char* rgb = new unsigned char[width*height*3]; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { int src = (i*width+j)*4; int dst = (i*width+j)*3; memcpy(&rgb[dst], &rgba[src], sizeof(unsigned char) * 3); } } return rgb; } void Bitmap::GetImage(const std::string& filepath, wxImage& dst_img) { ImageData* img_data = ImageDataMgr::Instance()->GetItem(filepath); int h = img_data->GetHeight(); ImageTrim trim(*img_data); Rect trim_r = trim.Trim(); img_data->Release(); if (trim_r.IsValid()) { wxImage wx_img; wx_img.LoadFile(filepath); wxRect wx_rect; wx_rect.SetLeft(trim_r.xmin); wx_rect.SetRight(trim_r.xmax - 1); wx_rect.SetTop(h - trim_r.ymax); wx_rect.SetBottom(h - trim_r.ymin - 1); dst_img = wx_img.GetSubImage(wx_rect); } else { dst_img.LoadFile(filepath); } } }<|endoftext|>
<commit_before>/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2014 Soumyajit De * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <shogun/lib/config.h> #ifdef HAVE_LINALG_LIB #include <shogun/mathematics/Math.h> #include <shogun/mathematics/linalg/linalg.h> #include <shogun/lib/SGMatrix.h> #include <gtest/gtest.h> #ifdef HAVE_EIGEN3 #include <shogun/mathematics/eigen3.h> #endif // HAVE_EIGEN3 #ifdef HAVE_VIENNACL #include <shogun/lib/GPUMatrix.h> #endif using namespace shogun; #ifdef HAVE_EIGEN3 TEST(MatrixElementwiseSquare, SGMatrix_eigen3_backend) { const index_t m=2; const index_t n=3; SGMatrix<float64_t> mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } SGMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::EIGEN3>(mat); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) EXPECT_NEAR(sq(i,j), CMath::sq(mat(i,j)), 1E-15); } } TEST(MatrixElementwiseSquare, Eigen3_Matrix_eigen3_backend) { const index_t m=2; const index_t n=3; Eigen::MatrixXd mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } SGMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::EIGEN3>(mat); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) EXPECT_NEAR(sq(i,j), CMath::sq(mat(i,j)), 1E-15); } } TEST(MatrixElementwiseSquare, SGMatrix_block_eigen3_backend) { const index_t m=2; const index_t n=3; SGMatrix<float64_t> mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } SGMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::EIGEN3>( linalg::block(mat,0,0,2,2)); for (index_t i=0; i<2; ++i) { for (index_t j=0; j<2; ++j) EXPECT_NEAR(sq(i,j), CMath::sq(mat(i,j)), 1E-15); } } TEST(MatrixElementwiseSquare, Eigen3_block_eigen3_backend) { const index_t m=2; const index_t n=3; Eigen::MatrixXd mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } SGMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::EIGEN3>( linalg::block((SGMatrix<float64_t>)mat,0,0,2,2)); for (index_t i=0; i<2; ++i) { for (index_t j=0; j<2; ++j) EXPECT_NEAR(sq(i,j), CMath::sq(mat(i,j)), 1E-15); } } #endif // HAVE_EIGEN3 #ifdef HAVE_VIENNACL #endif // HAVE_VIENNACL TEST(MatrixElementwiseSquare, viennacl_backend) { const index_t m=2; const index_t n=3; CGPUMatrix<float64_t> mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } CGPUMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::VIENNACL>(mat); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) EXPECT_NEAR(sq(i,j), mat(i,j)*mat(i,j), 1E-15); } } #endif // HAVE_LINALG_LIB <commit_msg>fixed a small mistake in linalg's elementwise square unit test<commit_after>/* * Copyright (c) The Shogun Machine Learning Toolbox * Written (w) 2014 Soumyajit De * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <shogun/lib/config.h> #ifdef HAVE_LINALG_LIB #include <shogun/mathematics/Math.h> #include <shogun/mathematics/linalg/linalg.h> #include <shogun/lib/SGMatrix.h> #include <gtest/gtest.h> #ifdef HAVE_EIGEN3 #include <shogun/mathematics/eigen3.h> #endif // HAVE_EIGEN3 #ifdef HAVE_VIENNACL #include <shogun/lib/GPUMatrix.h> #endif using namespace shogun; #ifdef HAVE_EIGEN3 TEST(MatrixElementwiseSquare, SGMatrix_eigen3_backend) { const index_t m=2; const index_t n=3; SGMatrix<float64_t> mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } SGMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::EIGEN3>(mat); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) EXPECT_NEAR(sq(i,j), CMath::sq(mat(i,j)), 1E-15); } } TEST(MatrixElementwiseSquare, Eigen3_Matrix_eigen3_backend) { const index_t m=2; const index_t n=3; Eigen::MatrixXd mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } SGMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::EIGEN3>(mat); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) EXPECT_NEAR(sq(i,j), CMath::sq(mat(i,j)), 1E-15); } } TEST(MatrixElementwiseSquare, SGMatrix_block_eigen3_backend) { const index_t m=2; const index_t n=3; SGMatrix<float64_t> mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } SGMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::EIGEN3>( linalg::block(mat,0,0,2,2)); for (index_t i=0; i<2; ++i) { for (index_t j=0; j<2; ++j) EXPECT_NEAR(sq(i,j), CMath::sq(mat(i,j)), 1E-15); } } TEST(MatrixElementwiseSquare, Eigen3_block_eigen3_backend) { const index_t m=2; const index_t n=3; Eigen::MatrixXd mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } SGMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::EIGEN3>( linalg::block((SGMatrix<float64_t>)mat,0,0,2,2)); for (index_t i=0; i<2; ++i) { for (index_t j=0; j<2; ++j) EXPECT_NEAR(sq(i,j), CMath::sq(mat(i,j)), 1E-15); } } #endif // HAVE_EIGEN3 #ifdef HAVE_VIENNACL TEST(MatrixElementwiseSquare, viennacl_backend) { const index_t m=2; const index_t n=3; CGPUMatrix<float64_t> mat(m, n); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) mat(i, j)=i*10+j+1; } CGPUMatrix<float64_t> sq=linalg::elementwise_square<linalg::Backend::VIENNACL>(mat); for (index_t i=0; i<m; ++i) { for (index_t j=0; j<n; ++j) EXPECT_NEAR(sq(i,j), mat(i,j)*mat(i,j), 1E-15); } } #endif // HAVE_VIENNACL #endif // HAVE_LINALG_LIB <|endoftext|>
<commit_before>/* Copyright 2012 Joe Hermaszewski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Joe Hermaszewski. */ #include "compound_statement.hpp" #include <cassert> #include <memory> #include <set> #include <vector> #include <compiler/parser.hpp> #include <compiler/sema_analyzer.hpp> #include <compiler/shader_writer.hpp> #include <compiler/terminal_types.hpp> #include <compiler/tokens/expressions/expression.hpp> #include <compiler/tokens/statements/statement.hpp> #include <compiler/tokens/statements/return_statement.hpp> namespace JoeLang { namespace Compiler { //------------------------------------------------------------------------------ // CompoundStatement //------------------------------------------------------------------------------ CompoundStatement::CompoundStatement( std::vector<Statement_up> statements ) :Statement( TokenTy::CompoundStatement ) ,m_Statements( std::move(statements) ) { } CompoundStatement::~CompoundStatement() { } bool CompoundStatement::AlwaysReturns() const { // // This assumes that we've performed sema on this object and have dropped // Statements after the return statement // return (*m_Statements.rbegin())->AlwaysReturns(); } std::set<Function_sp> CompoundStatement::GetCallees() const { std::set<Function_sp> ret; for( const auto& s : m_Statements ) { auto f = s->GetCallees(); ret.insert( f.begin(), f.end() ); } return ret; } std::set<Variable_sp> CompoundStatement::GetVariables() const { std::set<Variable_sp> ret; for( const auto& s : m_Statements ) { auto f = s->GetVariables(); ret.insert( f.begin(), f.end() ); } return ret; } std::set<Variable_sp> CompoundStatement::GetWrittenToVariables() const { std::set<Variable_sp> ret; for( const auto& s : m_Statements ) { auto f = s->GetWrittenToVariables(); ret.insert( f.begin(), f.end() ); } return ret; } void CompoundStatement::PerformSemaAsFunction( SemaAnalyzer& sema, const CompleteType& return_type ) { PerformSemaCommon( sema, return_type, true ); } void CompoundStatement::PerformSema( SemaAnalyzer& sema, const CompleteType& return_type ) { // Create the scope for this statement SemaAnalyzer::ScopeHolder scope( sema ); scope.Enter(); PerformSemaCommon( sema, return_type, false ); scope.Leave(); } void CompoundStatement::PerformSemaCommon( SemaAnalyzer& sema, const CompleteType& return_type, bool must_return ) { for( auto& statement : m_Statements ) statement->PerformSema( sema, return_type ); // Remove all statements after the first returning one for( unsigned i = 0; i < m_Statements.size(); ++i ) if( m_Statements[i]->AlwaysReturns() && i != m_Statements.size() - 1 ) { sema.Warning( "Statements will never be executed" ); m_Statements.erase( m_Statements.begin()+i+1, m_Statements.end() ); break; } if( must_return ) { if( return_type.IsVoid() && !AlwaysReturns() ) m_Statements.emplace_back( new ReturnStatement( nullptr ) ); if( !AlwaysReturns() ) sema.Error( "Function doesn't always return" ); } } void CompoundStatement::CodeGen( CodeGenerator& code_gen ) { for( auto& s : m_Statements ) s->CodeGen( code_gen ); } void CompoundStatement::Write( ShaderWriter& shader_writer ) const { shader_writer << "{"; shader_writer.PushIndentation(); for( const auto& statement : m_Statements ) { shader_writer.NewLine(); shader_writer << *statement; } shader_writer.PopIndentation(); shader_writer.NewLine(); shader_writer << "}"; } bool CompoundStatement::Parse( Parser& parser, CompoundStatement_up& token ) { if( !parser.ExpectTerminal( TerminalType::OPEN_BRACE ) ) return false; std::vector<Statement_up> statements; parser.ExpectSequenceOf<Statement>( statements ); CHECK_PARSER; if( !parser.ExpectTerminal( TerminalType::CLOSE_BRACE ) ) return false; token.reset( new CompoundStatement( std::move(statements) ) ); return true; } } // namespace Compiler } // namespace JoeLang <commit_msg>[~] changed error text<commit_after>/* Copyright 2012 Joe Hermaszewski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Joe Hermaszewski. */ #include "compound_statement.hpp" #include <cassert> #include <memory> #include <set> #include <vector> #include <compiler/parser.hpp> #include <compiler/sema_analyzer.hpp> #include <compiler/shader_writer.hpp> #include <compiler/terminal_types.hpp> #include <compiler/tokens/expressions/expression.hpp> #include <compiler/tokens/statements/statement.hpp> #include <compiler/tokens/statements/return_statement.hpp> namespace JoeLang { namespace Compiler { //------------------------------------------------------------------------------ // CompoundStatement //------------------------------------------------------------------------------ CompoundStatement::CompoundStatement( std::vector<Statement_up> statements ) :Statement( TokenTy::CompoundStatement ) ,m_Statements( std::move(statements) ) { } CompoundStatement::~CompoundStatement() { } bool CompoundStatement::AlwaysReturns() const { // // This assumes that we've performed sema on this object and have dropped // Statements after the return statement // return (*m_Statements.rbegin())->AlwaysReturns(); } std::set<Function_sp> CompoundStatement::GetCallees() const { std::set<Function_sp> ret; for( const auto& s : m_Statements ) { auto f = s->GetCallees(); ret.insert( f.begin(), f.end() ); } return ret; } std::set<Variable_sp> CompoundStatement::GetVariables() const { std::set<Variable_sp> ret; for( const auto& s : m_Statements ) { auto f = s->GetVariables(); ret.insert( f.begin(), f.end() ); } return ret; } std::set<Variable_sp> CompoundStatement::GetWrittenToVariables() const { std::set<Variable_sp> ret; for( const auto& s : m_Statements ) { auto f = s->GetWrittenToVariables(); ret.insert( f.begin(), f.end() ); } return ret; } void CompoundStatement::PerformSemaAsFunction( SemaAnalyzer& sema, const CompleteType& return_type ) { PerformSemaCommon( sema, return_type, true ); } void CompoundStatement::PerformSema( SemaAnalyzer& sema, const CompleteType& return_type ) { // Create the scope for this statement SemaAnalyzer::ScopeHolder scope( sema ); scope.Enter(); PerformSemaCommon( sema, return_type, false ); scope.Leave(); } void CompoundStatement::PerformSemaCommon( SemaAnalyzer& sema, const CompleteType& return_type, bool must_return ) { for( auto& statement : m_Statements ) statement->PerformSema( sema, return_type ); // Remove all statements after the first returning one for( unsigned i = 0; i < m_Statements.size(); ++i ) if( m_Statements[i]->AlwaysReturns() && i != m_Statements.size() - 1 ) { sema.Warning( "Statements will never be executed" ); m_Statements.erase( m_Statements.begin()+i+1, m_Statements.end() ); break; } if( must_return ) { if( return_type.IsVoid() && !AlwaysReturns() ) m_Statements.emplace_back( new ReturnStatement( nullptr ) ); if( !AlwaysReturns() ) sema.Error( "control reaches the end of a non-void function" ); } } void CompoundStatement::CodeGen( CodeGenerator& code_gen ) { for( auto& s : m_Statements ) s->CodeGen( code_gen ); } void CompoundStatement::Write( ShaderWriter& shader_writer ) const { shader_writer << "{"; shader_writer.PushIndentation(); for( const auto& statement : m_Statements ) { shader_writer.NewLine(); shader_writer << *statement; } shader_writer.PopIndentation(); shader_writer.NewLine(); shader_writer << "}"; } bool CompoundStatement::Parse( Parser& parser, CompoundStatement_up& token ) { if( !parser.ExpectTerminal( TerminalType::OPEN_BRACE ) ) return false; std::vector<Statement_up> statements; parser.ExpectSequenceOf<Statement>( statements ); CHECK_PARSER; if( !parser.ExpectTerminal( TerminalType::CLOSE_BRACE ) ) return false; token.reset( new CompoundStatement( std::move(statements) ) ); return true; } } // namespace Compiler } // namespace JoeLang <|endoftext|>
<commit_before>#include "appconfig.h" #include "appmodels.h" #include "appevents.h" #include "experimentcontext.h" #include <limits> #include <QBoxLayout> #include <QDebug> #include <QDialog> #include <QDialogButtonBox> #include <QRadioButton> #include <QJsonObject> #include <QJsonDocument> #include <QFileInfo> #include <QDir> #include <QTemporaryFile> #include <QTimer> ExperimentContext::ExperimentContext() { connect(this, &ExperimentContext::newImageResult, this, &ExperimentContext::aggregateResults); connect(this, &ExperimentContext::experimentFinished, this, &ExperimentContext::onExperimentFinished); _publisher = new QProcess; _publisher->setWorkingDirectory(AppConfig::ckBinPath()); _publisher->setProgram(AppConfig::ckExeName()); connect(_publisher, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(publishResultsFinished(int, QProcess::ExitStatus))); connect(_publisher, SIGNAL(error(QProcess::ProcessError)), this, SLOT(publishResultsError(QProcess::ProcessError))); } void ExperimentContext::startExperiment(bool resume) { if (!resume) { clearAggregatedResults(); } _mode = AppConfig::currentModeType(); _batchSize = AppConfig::batchSize(); _program = AppConfig::currentProgram().value<Program>(); _model = AppConfig::currentModel().value<Model>(); _dataset = AppConfig::currentDataset().value<Dataset>(); _isExperimentStarted = true; _isExperimentInterrupted = false; emit experimentStarted(resume); } void ExperimentContext::stopExperiment() { _isExperimentStarted = false; _isExperimentInterrupted = true; emit experimentStopping(); } void ExperimentContext::onExperimentFinished(bool normalExit) { _isExperimentStarted = false; if (normalExit && !_isExperimentInterrupted && currentResult() == resultCount() - 1 && Mode::Type::RECOGNITION == mode() && AppConfig::recognitionAutoRestart()) { QTimer::singleShot(200, this, SLOT(restartExperiment())); } } void ExperimentContext::restartExperiment() { startExperiment(false); } void ExperimentContext::notifyModeChanged(const Mode& mode) { emit modeChanged(mode); } void ExperimentContext::clearAggregatedResults() { _duration.clear(); _precision.clear(); _top1.clear(); _top5.clear(); _results = QVector<ImageResult>(); _combinedRollingAP = {Stat(), Stat(), Stat()}; _current_result = -1; } static bool eq(float a, float b) { return std::fabs(a - b) < std::numeric_limits<float>::epsilon(); } static void addIf(ExperimentContext::Stat& stat, double v) { if (!eq(v, 0)) { stat.add(v); } } void ExperimentContext::aggregateResults(ImageResult ir) { _duration.add(ir.duration); _precision.add(ir.precision()); _top1.add(ir.correctAsTop1() ? 1 : 0); _top5.add(ir.correctAsTop5() ? 1 : 0); _results.append(ir); if (_current_result == _results.size() - 2) { _current_result = _results.size() - 1; } for (const auto& v : ir.rollingAP) { addIf(_combinedRollingAP[EASY], v[EASY]); addIf(_combinedRollingAP[MODERATE], v[MODERATE]); addIf(_combinedRollingAP[HARD], v[HARD]); } emitCurrentResult(); } void ExperimentContext::emitZoomChanged(double z, bool ztf) { emit zoomChanged(z, ztf); } void ExperimentContext::zoomIn() { emitZoomChanged(AppConfig::adjustZoom(true), AppConfig::zoomToFit()); } void ExperimentContext::zoomOut() { emitZoomChanged(AppConfig::adjustZoom(false), AppConfig::zoomToFit()); } void ExperimentContext::zoomActual() { emitZoomChanged(AppConfig::setZoom(1), AppConfig::zoomToFit()); } void ExperimentContext::zoomToFit() { emitZoomChanged(AppConfig::zoom(), AppConfig::toggleZoomToFit()); } void ExperimentContext::emitCurrentResult() { emit currentResultChanged(_current_result, _results.size(), _results.at(_current_result)); } void ExperimentContext::gotoNextResult() { if (_current_result < _results.size() - 1) { ++_current_result; emitCurrentResult(); } } void ExperimentContext::gotoPrevResult() { if (0 < _current_result && _current_result < _results.size()) { --_current_result; emitCurrentResult(); } } void ExperimentContext::gotoFirstResult() { if (!_results.empty() && 0 < _current_result) { _current_result = 0; emitCurrentResult(); } } void ExperimentContext::gotoLastResult() { if (!_results.empty() && _current_result < _results.size() - 1) { _current_result = _results.size() - 1; emitCurrentResult(); } } static QJsonObject toJson(const ExperimentContext::Stat& stat) { QJsonObject dict; dict["avg"] = stat.avg; dict["min"] = stat.min; dict["max"] = stat.max; return dict; } static QJsonObject toJsonClassification(const ExperimentContext* context) { QJsonObject dict; dict["top1"] = context->top1().avg; dict["top5"] = context->top5().avg; dict["batch_size"] = context->batchSize(); return dict; } static QJsonObject toJsonDetection(const ExperimentContext* context) { QJsonObject dict; dict["precision"] = toJson(context->precision()); return dict; } void ExperimentContext::publishResults() { if (!hasAggregatedResults()) { // nothing to publish return; } QJsonObject dict; dict["duration"] = toJson(duration()); dict["detection"] = toJsonDetection(this); dict["classification"] = toJsonClassification(this); dict["mode"] = Mode(mode()).name(); dict["model_uoa"] = _model.uoa; dict["dataset_uoa"] = _dataset.valUoa; dict["program_uoa"] = _program.programUoa; dict["tmp_dir"] = _program.targetDir; dict["engine_uoa"] = _program.targetUoa; QJsonObject results; results["dict"] = dict; QFileInfo out(_program.outputFile); QDir dir = out.absoluteDir(); QTemporaryFile tmp(dir.absolutePath() + QDir::separator() + "tmp-publish-XXXXXX.json"); tmp.setAutoRemove(false); if (!tmp.open()) { AppEvents::error("Failed to create a results JSON file"); return; } QFileInfo tmpInfo(tmp); QString absoluteTmpPath = tmpInfo.absoluteFilePath(); QJsonDocument doc(results); tmp.write(doc.toJson()); tmp.close(); _publisher->setArguments(QStringList { "submit", "experiment.bench.dnn.desktop", "@" + absoluteTmpPath }); const QString runCmd = _publisher->program() + " " + _publisher->arguments().join(" "); qDebug() << "Run CK command: " << runCmd; _publisher->start(); emit publishStarted(); } static void reportPublisherFail(QProcess* publisher) { const QString runCmd = publisher->program() + " " + publisher->arguments().join(" "); AppEvents::error("Failed to publish results. " "Please, select the command below, copy it and run manually from command line " "to investigate the issue:\n\n" + runCmd); } void ExperimentContext::publishResultsFinished(int exitCode, QProcess::ExitStatus exitStatus) { qDebug() << "Publishing results finished with exit code " << exitCode << " and exit status " << exitStatus; if (0 != exitCode) { reportPublisherFail(_publisher); emit publishFinished(false); } else { AppEvents::info("Results are successfully pushed to the server. Thank you for contributing!"); emit publishFinished(true); } } void ExperimentContext::publishResultsError(QProcess::ProcessError error) { qDebug() << "Publishing results error " << error; reportPublisherFail(_publisher); emit publishFinished(false); } <commit_msg>fixing G++ error<commit_after>#include "appconfig.h" #include "appmodels.h" #include "appevents.h" #include "experimentcontext.h" #include <limits> #include <cmath> #include <QBoxLayout> #include <QDebug> #include <QDialog> #include <QDialogButtonBox> #include <QRadioButton> #include <QJsonObject> #include <QJsonDocument> #include <QFileInfo> #include <QDir> #include <QTemporaryFile> #include <QTimer> ExperimentContext::ExperimentContext() { connect(this, &ExperimentContext::newImageResult, this, &ExperimentContext::aggregateResults); connect(this, &ExperimentContext::experimentFinished, this, &ExperimentContext::onExperimentFinished); _publisher = new QProcess; _publisher->setWorkingDirectory(AppConfig::ckBinPath()); _publisher->setProgram(AppConfig::ckExeName()); connect(_publisher, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(publishResultsFinished(int, QProcess::ExitStatus))); connect(_publisher, SIGNAL(error(QProcess::ProcessError)), this, SLOT(publishResultsError(QProcess::ProcessError))); } void ExperimentContext::startExperiment(bool resume) { if (!resume) { clearAggregatedResults(); } _mode = AppConfig::currentModeType(); _batchSize = AppConfig::batchSize(); _program = AppConfig::currentProgram().value<Program>(); _model = AppConfig::currentModel().value<Model>(); _dataset = AppConfig::currentDataset().value<Dataset>(); _isExperimentStarted = true; _isExperimentInterrupted = false; emit experimentStarted(resume); } void ExperimentContext::stopExperiment() { _isExperimentStarted = false; _isExperimentInterrupted = true; emit experimentStopping(); } void ExperimentContext::onExperimentFinished(bool normalExit) { _isExperimentStarted = false; if (normalExit && !_isExperimentInterrupted && currentResult() == resultCount() - 1 && Mode::Type::RECOGNITION == mode() && AppConfig::recognitionAutoRestart()) { QTimer::singleShot(200, this, SLOT(restartExperiment())); } } void ExperimentContext::restartExperiment() { startExperiment(false); } void ExperimentContext::notifyModeChanged(const Mode& mode) { emit modeChanged(mode); } void ExperimentContext::clearAggregatedResults() { _duration.clear(); _precision.clear(); _top1.clear(); _top5.clear(); _results = QVector<ImageResult>(); _combinedRollingAP = {Stat(), Stat(), Stat()}; _current_result = -1; } static bool eq(float a, float b) { return std::fabs(a - b) < std::numeric_limits<float>::epsilon(); } static void addIf(ExperimentContext::Stat& stat, double v) { if (!eq(v, 0)) { stat.add(v); } } void ExperimentContext::aggregateResults(ImageResult ir) { _duration.add(ir.duration); _precision.add(ir.precision()); _top1.add(ir.correctAsTop1() ? 1 : 0); _top5.add(ir.correctAsTop5() ? 1 : 0); _results.append(ir); if (_current_result == _results.size() - 2) { _current_result = _results.size() - 1; } for (const auto& v : ir.rollingAP) { addIf(_combinedRollingAP[EASY], v[EASY]); addIf(_combinedRollingAP[MODERATE], v[MODERATE]); addIf(_combinedRollingAP[HARD], v[HARD]); } emitCurrentResult(); } void ExperimentContext::emitZoomChanged(double z, bool ztf) { emit zoomChanged(z, ztf); } void ExperimentContext::zoomIn() { emitZoomChanged(AppConfig::adjustZoom(true), AppConfig::zoomToFit()); } void ExperimentContext::zoomOut() { emitZoomChanged(AppConfig::adjustZoom(false), AppConfig::zoomToFit()); } void ExperimentContext::zoomActual() { emitZoomChanged(AppConfig::setZoom(1), AppConfig::zoomToFit()); } void ExperimentContext::zoomToFit() { emitZoomChanged(AppConfig::zoom(), AppConfig::toggleZoomToFit()); } void ExperimentContext::emitCurrentResult() { emit currentResultChanged(_current_result, _results.size(), _results.at(_current_result)); } void ExperimentContext::gotoNextResult() { if (_current_result < _results.size() - 1) { ++_current_result; emitCurrentResult(); } } void ExperimentContext::gotoPrevResult() { if (0 < _current_result && _current_result < _results.size()) { --_current_result; emitCurrentResult(); } } void ExperimentContext::gotoFirstResult() { if (!_results.empty() && 0 < _current_result) { _current_result = 0; emitCurrentResult(); } } void ExperimentContext::gotoLastResult() { if (!_results.empty() && _current_result < _results.size() - 1) { _current_result = _results.size() - 1; emitCurrentResult(); } } static QJsonObject toJson(const ExperimentContext::Stat& stat) { QJsonObject dict; dict["avg"] = stat.avg; dict["min"] = stat.min; dict["max"] = stat.max; return dict; } static QJsonObject toJsonClassification(const ExperimentContext* context) { QJsonObject dict; dict["top1"] = context->top1().avg; dict["top5"] = context->top5().avg; dict["batch_size"] = context->batchSize(); return dict; } static QJsonObject toJsonDetection(const ExperimentContext* context) { QJsonObject dict; dict["precision"] = toJson(context->precision()); return dict; } void ExperimentContext::publishResults() { if (!hasAggregatedResults()) { // nothing to publish return; } QJsonObject dict; dict["duration"] = toJson(duration()); dict["detection"] = toJsonDetection(this); dict["classification"] = toJsonClassification(this); dict["mode"] = Mode(mode()).name(); dict["model_uoa"] = _model.uoa; dict["dataset_uoa"] = _dataset.valUoa; dict["program_uoa"] = _program.programUoa; dict["tmp_dir"] = _program.targetDir; dict["engine_uoa"] = _program.targetUoa; QJsonObject results; results["dict"] = dict; QFileInfo out(_program.outputFile); QDir dir = out.absoluteDir(); QTemporaryFile tmp(dir.absolutePath() + QDir::separator() + "tmp-publish-XXXXXX.json"); tmp.setAutoRemove(false); if (!tmp.open()) { AppEvents::error("Failed to create a results JSON file"); return; } QFileInfo tmpInfo(tmp); QString absoluteTmpPath = tmpInfo.absoluteFilePath(); QJsonDocument doc(results); tmp.write(doc.toJson()); tmp.close(); _publisher->setArguments(QStringList { "submit", "experiment.bench.dnn.desktop", "@" + absoluteTmpPath }); const QString runCmd = _publisher->program() + " " + _publisher->arguments().join(" "); qDebug() << "Run CK command: " << runCmd; _publisher->start(); emit publishStarted(); } static void reportPublisherFail(QProcess* publisher) { const QString runCmd = publisher->program() + " " + publisher->arguments().join(" "); AppEvents::error("Failed to publish results. " "Please, select the command below, copy it and run manually from command line " "to investigate the issue:\n\n" + runCmd); } void ExperimentContext::publishResultsFinished(int exitCode, QProcess::ExitStatus exitStatus) { qDebug() << "Publishing results finished with exit code " << exitCode << " and exit status " << exitStatus; if (0 != exitCode) { reportPublisherFail(_publisher); emit publishFinished(false); } else { AppEvents::info("Results are successfully pushed to the server. Thank you for contributing!"); emit publishFinished(true); } } void ExperimentContext::publishResultsError(QProcess::ProcessError error) { qDebug() << "Publishing results error " << error; reportPublisherFail(_publisher); emit publishFinished(false); } <|endoftext|>
<commit_before>// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "component_library/animation.h" #include "component_library/rendermesh.h" #include "component_library/common_services.h" #include "component_library/transform.h" #include "library_components_generated.h" #include "fplbase/mesh.h" #include "fplbase/utilities.h" using mathfu::vec3; using mathfu::mat4; FPL_ENTITY_DEFINE_COMPONENT(fpl::component_library::RenderMeshComponent, fpl::component_library::RenderMeshData) namespace fpl { namespace component_library { // Offset the frustrum by this many world-units. As long as no objects are // larger than this number, they should still all draw, even if their // registration points technically fall outside our frustrum. static const float kFrustrumOffset = 50.0f; void RenderMeshComponent::Init() { asset_manager_ = entity_manager_->GetComponent<CommonServicesComponent>()->asset_manager(); } // Rendermesh depends on transform: void RenderMeshComponent::InitEntity(entity::EntityRef& entity) { entity_manager_->AddEntityToComponent<TransformComponent>(entity); } void RenderMeshComponent::RenderPrep(const CameraInterface& camera) { for (int pass = 0; pass < RenderPass_Count; pass++) { pass_render_list[pass].clear(); } for (auto iter = component_data_.begin(); iter != component_data_.end(); ++iter) { RenderMeshData* rendermesh_data = GetComponentData(iter->entity); TransformData* transform_data = Data<TransformData>(iter->entity); float max_cos = cos(camera.viewport_angle()); vec3 camera_facing = camera.facing(); vec3 camera_position = camera.position(); // Put each entity into the list for each render pass it is // planning on participating in. for (int pass = 0; pass < RenderPass_Count; pass++) { if (rendermesh_data->pass_mask & (1 << pass)) { if (rendermesh_data->currently_hidden) continue; // Check to make sure objects are inside the frustrum of our // view-cone before we draw: vec3 entity_position = transform_data->world_transform.TranslationVector3D(); vec3 pos_relative_to_camera = (entity_position - camera_position) + camera_facing * kFrustrumOffset; // Cache off the distance from the camera because we'll use it // later as a depth aproxamation. rendermesh_data->z_depth = (entity_position - camera.position()).LengthSquared(); // Are we culling this object based on the view angle? // If so, does this lie outside of our view frustrum? if ((rendermesh_data->culling_mask & (1 << CullingTest_ViewAngle)) && (vec3::DotProduct(pos_relative_to_camera.Normalized(), camera_facing.Normalized()) < max_cos)) { // The origin point for this mesh is not in our field of view. Cut // out early, and don't bother rendering it. continue; } // Are we culling this object based on view distance? If so, // is it far enough away that we should skip it? if ((rendermesh_data->culling_mask & (1 << CullingTest_Distance)) && rendermesh_data->z_depth > culling_distance_squared) { continue; } pass_render_list[pass].push_back( RenderlistEntry(iter->entity, &iter->data)); } } } std::sort(pass_render_list[RenderPass_Opaque].begin(), pass_render_list[RenderPass_Opaque].end()); std::sort(pass_render_list[RenderPass_Alpha].begin(), pass_render_list[RenderPass_Alpha].end(), std::greater<RenderlistEntry>()); } void RenderMeshComponent::RenderAllEntities(Renderer& renderer, const CameraInterface& camera) { // Make sure we only draw the front-facing polygons: renderer.SetCulling(Renderer::kCullBack); // Render the actual game: for (int pass = 0; pass < RenderPass_Count; pass++) { RenderPass(pass, camera, renderer); } } // Render a pass. void RenderMeshComponent::RenderPass(int pass_id, const CameraInterface& camera, Renderer& renderer) { RenderPass(pass_id, camera, renderer, nullptr); } // Render a single render-pass, by ID. void RenderMeshComponent::RenderPass(int pass_id, const CameraInterface& camera, Renderer& renderer, const Shader* shader_override) { mat4 camera_vp = camera.GetTransformMatrix(); for (size_t i = 0; i < pass_render_list[pass_id].size(); i++) { entity::EntityRef& entity = pass_render_list[pass_id][i].entity; RenderMeshData* rendermesh_data = Data<RenderMeshData>(entity); TransformData* transform_data = Data<TransformData>(entity); AnimationData* anim_data = Data<AnimationData>(entity); // TODO: anim_data will set uniforms for an array of matricies. Each // matrix represents one bone position. const int num_bones = rendermesh_data->mesh->num_bones(); const bool has_anim = anim_data != nullptr && anim_data->motivator.Valid(); const bool has_one_bone_anim = has_anim && num_bones <= 1; const bool has_rigged_anim = has_anim && num_bones > 1; const mat4 world_transform = has_one_bone_anim ? transform_data->world_transform * anim_data->motivator.GlobalTransforms()[0] : transform_data->world_transform; const mat4 mvp = camera_vp * world_transform; const mat4 world_matrix_inverse = world_transform.Inverse(); renderer.camera_pos() = world_matrix_inverse * camera.position(); renderer.light_pos() = world_matrix_inverse * light_position_; renderer.model_view_projection() = mvp; renderer.color() = rendermesh_data->tint; renderer.model() = world_transform; renderer.SetBoneTransforms( has_rigged_anim ? anim_data->motivator.GlobalTransforms() : nullptr, has_rigged_anim ? num_bones : 0); if (!shader_override && rendermesh_data->shader) { rendermesh_data->shader->Set(renderer); } else { shader_override->Set(renderer); } rendermesh_data->mesh->Render(renderer); } } void RenderMeshComponent::SetHiddenRecursively(const entity::EntityRef& entity, bool hidden) { RenderMeshData* rendermesh_data = Data<RenderMeshData>(entity); TransformData* transform_data = Data<TransformData>(entity); if (transform_data) { if (rendermesh_data) { rendermesh_data->currently_hidden = hidden; } for (auto iter = transform_data->children.begin(); iter != transform_data->children.end(); ++iter) { SetHiddenRecursively(iter->owner, hidden); } } } void RenderMeshComponent::AddFromRawData(entity::EntityRef& entity, const void* raw_data) { auto rendermesh_def = static_cast<const RenderMeshDef*>(raw_data); // You need to call asset_manager before you can add from raw data, // otherwise it can't load up new meshes! assert(asset_manager_ != nullptr); assert(rendermesh_def->source_file() != nullptr); assert(rendermesh_def->shader() != nullptr); RenderMeshData* rendermesh_data = AddEntity(entity); rendermesh_data->mesh_filename = rendermesh_def->source_file()->c_str(); rendermesh_data->shader_filename = rendermesh_def->shader()->c_str(); rendermesh_data->mesh = asset_manager_->LoadMesh(rendermesh_def->source_file()->c_str()); assert(rendermesh_data->mesh != nullptr); rendermesh_data->shader = asset_manager_->LoadShader(rendermesh_def->shader()->c_str()); assert(rendermesh_data->shader != nullptr); rendermesh_data->default_hidden = rendermesh_def->hidden(); rendermesh_data->currently_hidden = rendermesh_def->hidden(); rendermesh_data->pass_mask = 0; if (rendermesh_def->render_pass() != nullptr) { for (size_t i = 0; i < rendermesh_def->render_pass()->size(); i++) { int render_pass = rendermesh_def->render_pass()->Get(i); assert(render_pass < RenderPass_Count); rendermesh_data->pass_mask |= 1 << render_pass; } } else { // Anything unspecified is assumed to be opaque. rendermesh_data->pass_mask = (1 << RenderPass_Opaque); } if (rendermesh_def->culling() != nullptr) { for (size_t i = 0; i < rendermesh_def->culling()->size(); i++) { int culling_test = rendermesh_def->culling()->Get(i); assert(culling_test < CullingTest_Count); rendermesh_data->culling_mask |= 1 << culling_test; } } // TODO: Load this from a flatbuffer file instead of setting it. rendermesh_data->tint = mathfu::kOnes4f; } entity::ComponentInterface::RawDataUniquePtr RenderMeshComponent::ExportRawData( const entity::EntityRef& entity) const { const RenderMeshData* data = GetComponentData(entity); if (data == nullptr) return nullptr; if (data->mesh_filename == "" || data->shader_filename == "") { // If we don't have a mesh filename or a shader, we can't be exported; // we were obviously created programatically. return nullptr; } flatbuffers::FlatBufferBuilder fbb; bool defaults = entity_manager_->GetComponent<CommonServicesComponent>() ->export_force_defaults(); fbb.ForceDefaults(defaults); auto source_file = (data->mesh_filename != "") ? fbb.CreateString(data->mesh_filename) : 0; auto shader = (data->shader_filename != "") ? fbb.CreateString(data->shader_filename) : 0; std::vector<unsigned char> render_pass_vec; for (int i = 0; i < RenderPass_Count; i++) { if (data->pass_mask & (1 << i)) { render_pass_vec.push_back(i); } } auto render_pass = fbb.CreateVector(render_pass_vec); std::vector<unsigned char> culling_mask_vec; for (int i = 0; i < CullingTest_Count; i++) { if (data->culling_mask & (1 << i)) { culling_mask_vec.push_back(i); } } auto culling_mask = data->culling_mask ? fbb.CreateVector(culling_mask_vec) : 0; RenderMeshDefBuilder builder(fbb); if (defaults || source_file.o != 0) { builder.add_source_file(source_file); } if (defaults || shader.o != 0) { builder.add_shader(shader); } if (defaults || render_pass.o != 0) { builder.add_render_pass(render_pass); } if (defaults || culling_mask.o != 0) { builder.add_culling(culling_mask); } fbb.Finish(builder.Finish()); return fbb.ReleaseBufferPointer(); } } // component_library } // fpl <commit_msg>Fix exploding hippos problem when starting the editor.<commit_after>// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "component_library/animation.h" #include "component_library/rendermesh.h" #include "component_library/common_services.h" #include "component_library/transform.h" #include "library_components_generated.h" #include "fplbase/mesh.h" #include "fplbase/utilities.h" using mathfu::vec3; using mathfu::mat4; FPL_ENTITY_DEFINE_COMPONENT(fpl::component_library::RenderMeshComponent, fpl::component_library::RenderMeshData) namespace fpl { namespace component_library { // Offset the frustrum by this many world-units. As long as no objects are // larger than this number, they should still all draw, even if their // registration points technically fall outside our frustrum. static const float kFrustrumOffset = 50.0f; void RenderMeshComponent::Init() { asset_manager_ = entity_manager_->GetComponent<CommonServicesComponent>()->asset_manager(); } // Rendermesh depends on transform: void RenderMeshComponent::InitEntity(entity::EntityRef& entity) { entity_manager_->AddEntityToComponent<TransformComponent>(entity); } void RenderMeshComponent::RenderPrep(const CameraInterface& camera) { for (int pass = 0; pass < RenderPass_Count; pass++) { pass_render_list[pass].clear(); } for (auto iter = component_data_.begin(); iter != component_data_.end(); ++iter) { RenderMeshData* rendermesh_data = GetComponentData(iter->entity); TransformData* transform_data = Data<TransformData>(iter->entity); float max_cos = cos(camera.viewport_angle()); vec3 camera_facing = camera.facing(); vec3 camera_position = camera.position(); // Put each entity into the list for each render pass it is // planning on participating in. for (int pass = 0; pass < RenderPass_Count; pass++) { if (rendermesh_data->pass_mask & (1 << pass)) { if (rendermesh_data->currently_hidden) continue; // Check to make sure objects are inside the frustrum of our // view-cone before we draw: vec3 entity_position = transform_data->world_transform.TranslationVector3D(); vec3 pos_relative_to_camera = (entity_position - camera_position) + camera_facing * kFrustrumOffset; // Cache off the distance from the camera because we'll use it // later as a depth aproxamation. rendermesh_data->z_depth = (entity_position - camera.position()).LengthSquared(); // Are we culling this object based on the view angle? // If so, does this lie outside of our view frustrum? if ((rendermesh_data->culling_mask & (1 << CullingTest_ViewAngle)) && (vec3::DotProduct(pos_relative_to_camera.Normalized(), camera_facing.Normalized()) < max_cos)) { // The origin point for this mesh is not in our field of view. Cut // out early, and don't bother rendering it. continue; } // Are we culling this object based on view distance? If so, // is it far enough away that we should skip it? if ((rendermesh_data->culling_mask & (1 << CullingTest_Distance)) && rendermesh_data->z_depth > culling_distance_squared) { continue; } pass_render_list[pass].push_back( RenderlistEntry(iter->entity, &iter->data)); } } } std::sort(pass_render_list[RenderPass_Opaque].begin(), pass_render_list[RenderPass_Opaque].end()); std::sort(pass_render_list[RenderPass_Alpha].begin(), pass_render_list[RenderPass_Alpha].end(), std::greater<RenderlistEntry>()); } void RenderMeshComponent::RenderAllEntities(Renderer& renderer, const CameraInterface& camera) { // Make sure we only draw the front-facing polygons: renderer.SetCulling(Renderer::kCullBack); // Render the actual game: for (int pass = 0; pass < RenderPass_Count; pass++) { RenderPass(pass, camera, renderer); } } // Render a pass. void RenderMeshComponent::RenderPass(int pass_id, const CameraInterface& camera, Renderer& renderer) { RenderPass(pass_id, camera, renderer, nullptr); } // Render a single render-pass, by ID. void RenderMeshComponent::RenderPass(int pass_id, const CameraInterface& camera, Renderer& renderer, const Shader* shader_override) { mat4 camera_vp = camera.GetTransformMatrix(); for (size_t i = 0; i < pass_render_list[pass_id].size(); i++) { entity::EntityRef& entity = pass_render_list[pass_id][i].entity; RenderMeshData* rendermesh_data = Data<RenderMeshData>(entity); TransformData* transform_data = Data<TransformData>(entity); AnimationData* anim_data = Data<AnimationData>(entity); // TODO: anim_data will set uniforms for an array of matricies. Each // matrix represents one bone position. const int num_bones = rendermesh_data->mesh->num_bones(); const bool has_anim = anim_data != nullptr && anim_data->motivator.Valid(); const bool has_one_bone_anim = has_anim && num_bones <= 1; const mat4 world_transform = has_one_bone_anim ? transform_data->world_transform * anim_data->motivator.GlobalTransforms()[0] : transform_data->world_transform; const mat4 mvp = camera_vp * world_transform; const mat4 world_matrix_inverse = world_transform.Inverse(); renderer.camera_pos() = world_matrix_inverse * camera.position(); renderer.light_pos() = world_matrix_inverse * light_position_; renderer.model_view_projection() = mvp; renderer.color() = rendermesh_data->tint; renderer.model() = world_transform; // If the mesh has a skeleton, we need to update the bone positions. // The positions are normally supplied by the animation, but if they are // not, use the default pose in the RenderMesh. if (num_bones > 1) { const mat4* bone_transforms = has_anim ? anim_data->motivator.GlobalTransforms() : rendermesh_data->mesh->bone_global_transforms(); renderer.SetBoneTransforms(bone_transforms, num_bones); } if (!shader_override && rendermesh_data->shader) { rendermesh_data->shader->Set(renderer); } else { shader_override->Set(renderer); } rendermesh_data->mesh->Render(renderer); } } void RenderMeshComponent::SetHiddenRecursively(const entity::EntityRef& entity, bool hidden) { RenderMeshData* rendermesh_data = Data<RenderMeshData>(entity); TransformData* transform_data = Data<TransformData>(entity); if (transform_data) { if (rendermesh_data) { rendermesh_data->currently_hidden = hidden; } for (auto iter = transform_data->children.begin(); iter != transform_data->children.end(); ++iter) { SetHiddenRecursively(iter->owner, hidden); } } } void RenderMeshComponent::AddFromRawData(entity::EntityRef& entity, const void* raw_data) { auto rendermesh_def = static_cast<const RenderMeshDef*>(raw_data); // You need to call asset_manager before you can add from raw data, // otherwise it can't load up new meshes! assert(asset_manager_ != nullptr); assert(rendermesh_def->source_file() != nullptr); assert(rendermesh_def->shader() != nullptr); RenderMeshData* rendermesh_data = AddEntity(entity); rendermesh_data->mesh_filename = rendermesh_def->source_file()->c_str(); rendermesh_data->shader_filename = rendermesh_def->shader()->c_str(); rendermesh_data->mesh = asset_manager_->LoadMesh(rendermesh_def->source_file()->c_str()); assert(rendermesh_data->mesh != nullptr); rendermesh_data->shader = asset_manager_->LoadShader(rendermesh_def->shader()->c_str()); assert(rendermesh_data->shader != nullptr); rendermesh_data->default_hidden = rendermesh_def->hidden(); rendermesh_data->currently_hidden = rendermesh_def->hidden(); rendermesh_data->pass_mask = 0; if (rendermesh_def->render_pass() != nullptr) { for (size_t i = 0; i < rendermesh_def->render_pass()->size(); i++) { int render_pass = rendermesh_def->render_pass()->Get(i); assert(render_pass < RenderPass_Count); rendermesh_data->pass_mask |= 1 << render_pass; } } else { // Anything unspecified is assumed to be opaque. rendermesh_data->pass_mask = (1 << RenderPass_Opaque); } if (rendermesh_def->culling() != nullptr) { for (size_t i = 0; i < rendermesh_def->culling()->size(); i++) { int culling_test = rendermesh_def->culling()->Get(i); assert(culling_test < CullingTest_Count); rendermesh_data->culling_mask |= 1 << culling_test; } } // TODO: Load this from a flatbuffer file instead of setting it. rendermesh_data->tint = mathfu::kOnes4f; } entity::ComponentInterface::RawDataUniquePtr RenderMeshComponent::ExportRawData( const entity::EntityRef& entity) const { const RenderMeshData* data = GetComponentData(entity); if (data == nullptr) return nullptr; if (data->mesh_filename == "" || data->shader_filename == "") { // If we don't have a mesh filename or a shader, we can't be exported; // we were obviously created programatically. return nullptr; } flatbuffers::FlatBufferBuilder fbb; bool defaults = entity_manager_->GetComponent<CommonServicesComponent>() ->export_force_defaults(); fbb.ForceDefaults(defaults); auto source_file = (data->mesh_filename != "") ? fbb.CreateString(data->mesh_filename) : 0; auto shader = (data->shader_filename != "") ? fbb.CreateString(data->shader_filename) : 0; std::vector<unsigned char> render_pass_vec; for (int i = 0; i < RenderPass_Count; i++) { if (data->pass_mask & (1 << i)) { render_pass_vec.push_back(i); } } auto render_pass = fbb.CreateVector(render_pass_vec); std::vector<unsigned char> culling_mask_vec; for (int i = 0; i < CullingTest_Count; i++) { if (data->culling_mask & (1 << i)) { culling_mask_vec.push_back(i); } } auto culling_mask = data->culling_mask ? fbb.CreateVector(culling_mask_vec) : 0; RenderMeshDefBuilder builder(fbb); if (defaults || source_file.o != 0) { builder.add_source_file(source_file); } if (defaults || shader.o != 0) { builder.add_shader(shader); } if (defaults || render_pass.o != 0) { builder.add_render_pass(render_pass); } if (defaults || culling_mask.o != 0) { builder.add_culling(culling_mask); } fbb.Finish(builder.Finish()); return fbb.ReleaseBufferPointer(); } } // component_library } // fpl <|endoftext|>
<commit_before>/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <cmath> #include <memory> #include <vector> #include "api/array_view.h" #include "modules/audio_coding/codecs/pcm16b/audio_encoder_pcm16b.h" #include "modules/audio_coding/neteq/tools/audio_checksum.h" #include "modules/audio_coding/neteq/tools/encode_neteq_input.h" #include "modules/audio_coding/neteq/tools/neteq_test.h" #include "modules/rtp_rtcp/source/byte_io.h" namespace webrtc { namespace test { namespace { constexpr int kPayloadType = 95; class SineGenerator : public EncodeNetEqInput::Generator { public: explicit SineGenerator(int sample_rate_hz) : sample_rate_hz_(sample_rate_hz) {} rtc::ArrayView<const int16_t> Generate(size_t num_samples) override { if (samples_.size() < num_samples) { samples_.resize(num_samples); } rtc::ArrayView<int16_t> output(samples_.data(), num_samples); for (auto& x : output) { x = static_cast<int16_t>(2000.0 * std::sin(phase_)); phase_ += 2 * kPi * kFreqHz / sample_rate_hz_; } return output; } private: static constexpr int kFreqHz = 300; // The sinewave frequency. const int sample_rate_hz_; const double kPi = std::acos(-1); std::vector<int16_t> samples_; double phase_ = 0.0; }; class FuzzRtpInput : public NetEqInput { public: explicit FuzzRtpInput(rtc::ArrayView<const uint8_t> data) : data_(data) { AudioEncoderPcm16B::Config config; config.payload_type = kPayloadType; config.sample_rate_hz = 32000; std::unique_ptr<AudioEncoder> encoder(new AudioEncoderPcm16B(config)); std::unique_ptr<EncodeNetEqInput::Generator> generator( new SineGenerator(config.sample_rate_hz)); input_.reset(new EncodeNetEqInput(std::move(generator), std::move(encoder), std::numeric_limits<int64_t>::max())); packet_ = input_->PopPacket(); FuzzHeader(); } rtc::Optional<int64_t> NextPacketTime() const override { return packet_->time_ms; } rtc::Optional<int64_t> NextOutputEventTime() const override { return input_->NextOutputEventTime(); } std::unique_ptr<PacketData> PopPacket() override { RTC_DCHECK(packet_); std::unique_ptr<PacketData> packet_to_return = std::move(packet_); packet_ = input_->PopPacket(); FuzzHeader(); return packet_to_return; } void AdvanceOutputEvent() override { return input_->AdvanceOutputEvent(); } bool ended() const override { return ended_; } rtc::Optional<RTPHeader> NextHeader() const override { RTC_DCHECK(packet_); return packet_->header; } private: void FuzzHeader() { constexpr size_t kNumBytesToFuzz = 11; if (data_ix_ + kNumBytesToFuzz > data_.size()) { ended_ = true; return; } RTC_DCHECK(packet_); const size_t start_ix = data_ix_; packet_->header.payloadType = ByteReader<uint8_t>::ReadLittleEndian(&data_[data_ix_]); packet_->header.payloadType &= 0x7F; data_ix_ += sizeof(uint8_t); packet_->header.sequenceNumber = ByteReader<uint16_t>::ReadLittleEndian(&data_[data_ix_]); data_ix_ += sizeof(uint16_t); packet_->header.timestamp = ByteReader<uint32_t>::ReadLittleEndian(&data_[data_ix_]); data_ix_ += sizeof(uint32_t); packet_->header.ssrc = ByteReader<uint32_t>::ReadLittleEndian(&data_[data_ix_]); data_ix_ += sizeof(uint32_t); RTC_CHECK_EQ(data_ix_ - start_ix, kNumBytesToFuzz); } bool ended_ = false; rtc::ArrayView<const uint8_t> data_; size_t data_ix_ = 0; std::unique_ptr<EncodeNetEqInput> input_; std::unique_ptr<PacketData> packet_; }; } // namespace void FuzzOneInputTest(const uint8_t* data, size_t size) { std::unique_ptr<FuzzRtpInput> input( new FuzzRtpInput(rtc::ArrayView<const uint8_t>(data, size))); std::unique_ptr<AudioChecksum> output(new AudioChecksum); NetEqTest::Callbacks callbacks; NetEq::Config config; NetEqTest::DecoderMap codecs; codecs[0] = std::make_pair(NetEqDecoder::kDecoderPCMu, "pcmu"); codecs[8] = std::make_pair(NetEqDecoder::kDecoderPCMa, "pcma"); codecs[103] = std::make_pair(NetEqDecoder::kDecoderISAC, "isac"); codecs[104] = std::make_pair(NetEqDecoder::kDecoderISACswb, "isac-swb"); codecs[111] = std::make_pair(NetEqDecoder::kDecoderOpus, "opus"); codecs[93] = std::make_pair(NetEqDecoder::kDecoderPCM16B, "pcm16-nb"); codecs[94] = std::make_pair(NetEqDecoder::kDecoderPCM16Bwb, "pcm16-wb"); codecs[96] = std::make_pair(NetEqDecoder::kDecoderPCM16Bswb48kHz, "pcm16-swb48"); codecs[9] = std::make_pair(NetEqDecoder::kDecoderG722, "g722"); codecs[106] = std::make_pair(NetEqDecoder::kDecoderAVT, "avt"); codecs[114] = std::make_pair(NetEqDecoder::kDecoderAVT16kHz, "avt-16"); codecs[115] = std::make_pair(NetEqDecoder::kDecoderAVT32kHz, "avt-32"); codecs[116] = std::make_pair(NetEqDecoder::kDecoderAVT48kHz, "avt-48"); codecs[117] = std::make_pair(NetEqDecoder::kDecoderRED, "red"); codecs[13] = std::make_pair(NetEqDecoder::kDecoderCNGnb, "cng-nb"); codecs[98] = std::make_pair(NetEqDecoder::kDecoderCNGwb, "cng-wb"); codecs[99] = std::make_pair(NetEqDecoder::kDecoderCNGswb32kHz, "cng-swb32"); codecs[100] = std::make_pair(NetEqDecoder::kDecoderCNGswb48kHz, "cng-swb48"); // This is the payload type that will be used for encoding. codecs[kPayloadType] = std::make_pair(NetEqDecoder::kDecoderPCM16Bswb32kHz, "pcm16-swb32"); NetEqTest::ExtDecoderMap ext_codecs; NetEqTest test(config, codecs, ext_codecs, std::move(input), std::move(output), callbacks); test.Run(); } } // namespace test void FuzzOneInput(const uint8_t* data, size_t size) { test::FuzzOneInputTest(data, size); } } // namespace webrtc <commit_msg>neteq_rtp_fuzzer: limit the fuzzer input size to avoid timeout<commit_after>/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <cmath> #include <memory> #include <vector> #include "api/array_view.h" #include "modules/audio_coding/codecs/pcm16b/audio_encoder_pcm16b.h" #include "modules/audio_coding/neteq/tools/audio_checksum.h" #include "modules/audio_coding/neteq/tools/encode_neteq_input.h" #include "modules/audio_coding/neteq/tools/neteq_test.h" #include "modules/rtp_rtcp/source/byte_io.h" namespace webrtc { namespace test { namespace { constexpr int kPayloadType = 95; class SineGenerator : public EncodeNetEqInput::Generator { public: explicit SineGenerator(int sample_rate_hz) : sample_rate_hz_(sample_rate_hz) {} rtc::ArrayView<const int16_t> Generate(size_t num_samples) override { if (samples_.size() < num_samples) { samples_.resize(num_samples); } rtc::ArrayView<int16_t> output(samples_.data(), num_samples); for (auto& x : output) { x = static_cast<int16_t>(2000.0 * std::sin(phase_)); phase_ += 2 * kPi * kFreqHz / sample_rate_hz_; } return output; } private: static constexpr int kFreqHz = 300; // The sinewave frequency. const int sample_rate_hz_; const double kPi = std::acos(-1); std::vector<int16_t> samples_; double phase_ = 0.0; }; class FuzzRtpInput : public NetEqInput { public: explicit FuzzRtpInput(rtc::ArrayView<const uint8_t> data) : data_(data) { AudioEncoderPcm16B::Config config; config.payload_type = kPayloadType; config.sample_rate_hz = 32000; std::unique_ptr<AudioEncoder> encoder(new AudioEncoderPcm16B(config)); std::unique_ptr<EncodeNetEqInput::Generator> generator( new SineGenerator(config.sample_rate_hz)); input_.reset(new EncodeNetEqInput(std::move(generator), std::move(encoder), std::numeric_limits<int64_t>::max())); packet_ = input_->PopPacket(); FuzzHeader(); } rtc::Optional<int64_t> NextPacketTime() const override { return packet_->time_ms; } rtc::Optional<int64_t> NextOutputEventTime() const override { return input_->NextOutputEventTime(); } std::unique_ptr<PacketData> PopPacket() override { RTC_DCHECK(packet_); std::unique_ptr<PacketData> packet_to_return = std::move(packet_); packet_ = input_->PopPacket(); FuzzHeader(); return packet_to_return; } void AdvanceOutputEvent() override { return input_->AdvanceOutputEvent(); } bool ended() const override { return ended_; } rtc::Optional<RTPHeader> NextHeader() const override { RTC_DCHECK(packet_); return packet_->header; } private: void FuzzHeader() { constexpr size_t kNumBytesToFuzz = 11; if (data_ix_ + kNumBytesToFuzz > data_.size()) { ended_ = true; return; } RTC_DCHECK(packet_); const size_t start_ix = data_ix_; packet_->header.payloadType = ByteReader<uint8_t>::ReadLittleEndian(&data_[data_ix_]); packet_->header.payloadType &= 0x7F; data_ix_ += sizeof(uint8_t); packet_->header.sequenceNumber = ByteReader<uint16_t>::ReadLittleEndian(&data_[data_ix_]); data_ix_ += sizeof(uint16_t); packet_->header.timestamp = ByteReader<uint32_t>::ReadLittleEndian(&data_[data_ix_]); data_ix_ += sizeof(uint32_t); packet_->header.ssrc = ByteReader<uint32_t>::ReadLittleEndian(&data_[data_ix_]); data_ix_ += sizeof(uint32_t); RTC_CHECK_EQ(data_ix_ - start_ix, kNumBytesToFuzz); } bool ended_ = false; rtc::ArrayView<const uint8_t> data_; size_t data_ix_ = 0; std::unique_ptr<EncodeNetEqInput> input_; std::unique_ptr<PacketData> packet_; }; } // namespace void FuzzOneInputTest(const uint8_t* data, size_t size) { // Limit the input size to 100000 bytes to avoid fuzzer timeout. if (size > 100000) return; std::unique_ptr<FuzzRtpInput> input( new FuzzRtpInput(rtc::ArrayView<const uint8_t>(data, size))); std::unique_ptr<AudioChecksum> output(new AudioChecksum); NetEqTest::Callbacks callbacks; NetEq::Config config; NetEqTest::DecoderMap codecs; codecs[0] = std::make_pair(NetEqDecoder::kDecoderPCMu, "pcmu"); codecs[8] = std::make_pair(NetEqDecoder::kDecoderPCMa, "pcma"); codecs[103] = std::make_pair(NetEqDecoder::kDecoderISAC, "isac"); codecs[104] = std::make_pair(NetEqDecoder::kDecoderISACswb, "isac-swb"); codecs[111] = std::make_pair(NetEqDecoder::kDecoderOpus, "opus"); codecs[93] = std::make_pair(NetEqDecoder::kDecoderPCM16B, "pcm16-nb"); codecs[94] = std::make_pair(NetEqDecoder::kDecoderPCM16Bwb, "pcm16-wb"); codecs[96] = std::make_pair(NetEqDecoder::kDecoderPCM16Bswb48kHz, "pcm16-swb48"); codecs[9] = std::make_pair(NetEqDecoder::kDecoderG722, "g722"); codecs[106] = std::make_pair(NetEqDecoder::kDecoderAVT, "avt"); codecs[114] = std::make_pair(NetEqDecoder::kDecoderAVT16kHz, "avt-16"); codecs[115] = std::make_pair(NetEqDecoder::kDecoderAVT32kHz, "avt-32"); codecs[116] = std::make_pair(NetEqDecoder::kDecoderAVT48kHz, "avt-48"); codecs[117] = std::make_pair(NetEqDecoder::kDecoderRED, "red"); codecs[13] = std::make_pair(NetEqDecoder::kDecoderCNGnb, "cng-nb"); codecs[98] = std::make_pair(NetEqDecoder::kDecoderCNGwb, "cng-wb"); codecs[99] = std::make_pair(NetEqDecoder::kDecoderCNGswb32kHz, "cng-swb32"); codecs[100] = std::make_pair(NetEqDecoder::kDecoderCNGswb48kHz, "cng-swb48"); // This is the payload type that will be used for encoding. codecs[kPayloadType] = std::make_pair(NetEqDecoder::kDecoderPCM16Bswb32kHz, "pcm16-swb32"); NetEqTest::ExtDecoderMap ext_codecs; NetEqTest test(config, codecs, ext_codecs, std::move(input), std::move(output), callbacks); test.Run(); } } // namespace test void FuzzOneInput(const uint8_t* data, size_t size) { test::FuzzOneInputTest(data, size); } } // namespace webrtc <|endoftext|>
<commit_before>#include "resources/resource_collection.h" #include "resources/resource_locator.h" #include "resources/resources.h" #include <halley/resources/resource.h> #include <utility> #include "graphics/sprite/sprite.h" #include "halley/support/logger.h" using namespace Halley; ResourceCollectionBase::ResourceCollectionBase(Resources& parent, AssetType type) : parent(parent) , type(type) { } void ResourceCollectionBase::clear() { resources.clear(); } void ResourceCollectionBase::unload(const String& assetId) { resources.erase(assetId); } void ResourceCollectionBase::unloadAll(int minDepth) { for (auto iter = resources.begin(); iter != resources.end(); ) { auto next = iter; ++next; auto& res = (*iter).second; if (res.depth >= minDepth) { resources.erase(iter); } iter = next; } } void ResourceCollectionBase::reload(const String& assetId) { auto res = resources.find(assetId); if (res != resources.end()) { auto& resWrap = res->second; try { const auto [newAsset, loaded] = loadAsset(assetId, ResourceLoadPriority::High, false); newAsset->setAssetId(assetId); newAsset->onLoaded(parent); resWrap.res->reloadResource(std::move(*newAsset)); } catch (std::exception& e) { Logger::logError("Error while reloading " + assetId + ": " + e.what()); } catch (...) { Logger::logError("Unknown error while reloading " + assetId); } } } void ResourceCollectionBase::purge(const String& assetId) { if (!resourceLoader) { parent.locator->purge(assetId, type); } } std::shared_ptr<Resource> ResourceCollectionBase::getUntyped(const String& name, ResourceLoadPriority priority) { return doGet(name, priority, true); } std::vector<String> ResourceCollectionBase::enumerate() const { if (resourceEnumerator) { return resourceEnumerator(); } else { return parent.locator->enumerate(type); } } std::pair<std::shared_ptr<Resource>, bool> ResourceCollectionBase::loadAsset(const String& assetId, ResourceLoadPriority priority, bool allowFallback) { std::shared_ptr<Resource> newRes; if (resourceLoader) { // Overriding loader newRes = resourceLoader(assetId, priority); } else { // Normal loading auto resLoader = ResourceLoader(*(parent.locator), assetId, type, priority, parent.api, parent); newRes = loadResource(resLoader); if (newRes) { newRes->setMeta(resLoader.getMeta()); } else if (resLoader.loaded) { throw Exception("Unable to construct resource from data: " + toString(type) + ":" + assetId, HalleyExceptions::Resources); } } if (!newRes) { if (allowFallback && !fallback.isEmpty()) { Logger::logError("Resource not found: \"" + toString(type) + ":" + assetId + "\""); return loadAsset(fallback, priority, false); } throw Exception("Resource not found: \"" + toString(type) + ":" + assetId + "\"", HalleyExceptions::Resources); } return std::make_pair(newRes, true); } std::shared_ptr<Resource> ResourceCollectionBase::doGet(const String& assetId, ResourceLoadPriority priority, bool allowFallback) { // Look in cache and return if it's there const auto res = resources.find(assetId); if (res != resources.end()) { return res->second.res; } // Load resource from disk const auto [newRes, loaded] = loadAsset(assetId, priority, allowFallback); // Store in cache if (loaded) { newRes->setAssetId(assetId); resources.emplace(assetId, Wrapper(newRes, 0)); newRes->onLoaded(parent); } return newRes; } bool ResourceCollectionBase::exists(const String& assetId) const { // Look in cache const auto res = resources.find(assetId); if (res != resources.end()) { return true; } return parent.locator->exists(assetId, type); } void ResourceCollectionBase::setFallback(const String& assetId) { fallback = assetId; } void ResourceCollectionBase::setResource(int curDepth, const String& name, std::shared_ptr<Resource> resource) { resources.emplace(name, Wrapper(std::move(resource), curDepth)); } void ResourceCollectionBase::setResourceLoader(ResourceLoaderFunc loader) { resourceLoader = std::move(loader); } void ResourceCollectionBase::setResourceEnumerator(ResourceEnumeratorFunc enumerator) { resourceEnumerator = std::move(enumerator); } <commit_msg>Don't cache missing assets<commit_after>#include "resources/resource_collection.h" #include "resources/resource_locator.h" #include "resources/resources.h" #include <halley/resources/resource.h> #include <utility> #include "graphics/sprite/sprite.h" #include "halley/support/logger.h" using namespace Halley; ResourceCollectionBase::ResourceCollectionBase(Resources& parent, AssetType type) : parent(parent) , type(type) { } void ResourceCollectionBase::clear() { resources.clear(); } void ResourceCollectionBase::unload(const String& assetId) { resources.erase(assetId); } void ResourceCollectionBase::unloadAll(int minDepth) { for (auto iter = resources.begin(); iter != resources.end(); ) { auto next = iter; ++next; auto& res = (*iter).second; if (res.depth >= minDepth) { resources.erase(iter); } iter = next; } } void ResourceCollectionBase::reload(const String& assetId) { auto res = resources.find(assetId); if (res != resources.end()) { auto& resWrap = res->second; try { const auto [newAsset, loaded] = loadAsset(assetId, ResourceLoadPriority::High, false); newAsset->setAssetId(assetId); newAsset->onLoaded(parent); resWrap.res->reloadResource(std::move(*newAsset)); } catch (std::exception& e) { Logger::logError("Error while reloading " + assetId + ": " + e.what()); } catch (...) { Logger::logError("Unknown error while reloading " + assetId); } } } void ResourceCollectionBase::purge(const String& assetId) { if (!resourceLoader) { parent.locator->purge(assetId, type); } } std::shared_ptr<Resource> ResourceCollectionBase::getUntyped(const String& name, ResourceLoadPriority priority) { return doGet(name, priority, true); } std::vector<String> ResourceCollectionBase::enumerate() const { if (resourceEnumerator) { return resourceEnumerator(); } else { return parent.locator->enumerate(type); } } std::pair<std::shared_ptr<Resource>, bool> ResourceCollectionBase::loadAsset(const String& assetId, ResourceLoadPriority priority, bool allowFallback) { std::shared_ptr<Resource> newRes; if (resourceLoader) { // Overriding loader newRes = resourceLoader(assetId, priority); } else { // Normal loading auto resLoader = ResourceLoader(*(parent.locator), assetId, type, priority, parent.api, parent); newRes = loadResource(resLoader); if (newRes) { newRes->setMeta(resLoader.getMeta()); } else if (resLoader.loaded) { throw Exception("Unable to construct resource from data: " + toString(type) + ":" + assetId, HalleyExceptions::Resources); } } if (!newRes) { if (allowFallback && !fallback.isEmpty()) { Logger::logError("Resource not found: \"" + toString(type) + ":" + assetId + "\""); return { loadAsset(fallback, priority, false).first, false }; } throw Exception("Resource not found: \"" + toString(type) + ":" + assetId + "\"", HalleyExceptions::Resources); } return std::make_pair(newRes, true); } std::shared_ptr<Resource> ResourceCollectionBase::doGet(const String& assetId, ResourceLoadPriority priority, bool allowFallback) { // Look in cache and return if it's there const auto res = resources.find(assetId); if (res != resources.end()) { return res->second.res; } // Load resource from disk const auto [newRes, loaded] = loadAsset(assetId, priority, allowFallback); // Store in cache if (loaded) { newRes->setAssetId(assetId); resources.emplace(assetId, Wrapper(newRes, 0)); newRes->onLoaded(parent); } return newRes; } bool ResourceCollectionBase::exists(const String& assetId) const { // Look in cache const auto res = resources.find(assetId); if (res != resources.end()) { return true; } return parent.locator->exists(assetId, type); } void ResourceCollectionBase::setFallback(const String& assetId) { fallback = assetId; } void ResourceCollectionBase::setResource(int curDepth, const String& name, std::shared_ptr<Resource> resource) { resources.emplace(name, Wrapper(std::move(resource), curDepth)); } void ResourceCollectionBase::setResourceLoader(ResourceLoaderFunc loader) { resourceLoader = std::move(loader); } void ResourceCollectionBase::setResourceEnumerator(ResourceEnumeratorFunc enumerator) { resourceEnumerator = std::move(enumerator); } <|endoftext|>
<commit_before>//===------------------------- thread.cpp----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "thread" #include "exception" #include "vector" #include "future" #include "limits" #include <sys/types.h> #if !_WIN32 #if !__sun__ && !__linux__ #include <sys/sysctl.h> #else #include <unistd.h> #endif // !__sun__ && !__linux__ #endif // !_WIN32 _LIBCPP_BEGIN_NAMESPACE_STD thread::~thread() { if (__t_ != 0) terminate(); } void thread::join() { int ec = pthread_join(__t_, 0); #ifndef _LIBCPP_NO_EXCEPTIONS if (ec) throw system_error(error_code(ec, system_category()), "thread::join failed"); #endif // _LIBCPP_NO_EXCEPTIONS __t_ = 0; } void thread::detach() { int ec = EINVAL; if (__t_ != 0) { ec = pthread_detach(__t_); if (ec == 0) __t_ = 0; } #ifndef _LIBCPP_NO_EXCEPTIONS if (ec) throw system_error(error_code(ec, system_category()), "thread::detach failed"); #endif // _LIBCPP_NO_EXCEPTIONS } unsigned thread::hardware_concurrency() _NOEXCEPT { #if defined(CTL_HW) && defined(HW_NCPU) unsigned n; int mib[2] = {CTL_HW, HW_NCPU}; std::size_t s = sizeof(n); sysctl(mib, 2, &n, &s, 0, 0); return n; #elif defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L) && defined(_SC_NPROCESSORS_ONLN) long result = sysconf(_SC_NPROCESSORS_ONLN); // sysconf returns -1 if the name is invalid, the option does not exist or // does not have a definite limit. if (result == -1) return 0; return static_cast<unsigned>(result); #else // defined(CTL_HW) && defined(HW_NCPU) // TODO: grovel through /proc or check cpuid on x86 and similar // instructions on other architectures. return 0; // Means not computable [thread.thread.static] #endif // defined(CTL_HW) && defined(HW_NCPU) } namespace this_thread { void sleep_for(const chrono::nanoseconds& ns) { using namespace chrono; if (ns > nanoseconds::zero()) { seconds s = duration_cast<seconds>(ns); timespec ts; typedef decltype(ts.tv_sec) ts_sec; _LIBCPP_CONSTEXPR ts_sec ts_sec_max = numeric_limits<ts_sec>::max(); if (s.count() < ts_sec_max) { ts.tv_sec = static_cast<ts_sec>(s.count()); ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((ns-s).count()); } else { ts.tv_sec = ts_sec_max; ts.tv_nsec = giga::num - 1; } nanosleep(&ts, 0); } } } // this_thread __thread_specific_ptr<__thread_struct>& __thread_local_data() { static __thread_specific_ptr<__thread_struct> __p; return __p; } // __thread_struct_imp template <class T> class _LIBCPP_HIDDEN __hidden_allocator { public: typedef T value_type; T* allocate(size_t __n) {return static_cast<T*>(::operator new(__n * sizeof(T)));} void deallocate(T* __p, size_t) {::operator delete((void*)__p);} size_t max_size() const {return size_t(~0) / sizeof(T);} }; class _LIBCPP_HIDDEN __thread_struct_imp { typedef vector<__assoc_sub_state*, __hidden_allocator<__assoc_sub_state*> > _AsyncStates; typedef vector<pair<condition_variable*, mutex*>, __hidden_allocator<pair<condition_variable*, mutex*> > > _Notify; _AsyncStates async_states_; _Notify notify_; __thread_struct_imp(const __thread_struct_imp&); __thread_struct_imp& operator=(const __thread_struct_imp&); public: __thread_struct_imp() {} ~__thread_struct_imp(); void notify_all_at_thread_exit(condition_variable* cv, mutex* m); void __make_ready_at_thread_exit(__assoc_sub_state* __s); }; __thread_struct_imp::~__thread_struct_imp() { for (_Notify::iterator i = notify_.begin(), e = notify_.end(); i != e; ++i) { i->second->unlock(); i->first->notify_all(); } for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end(); i != e; ++i) { (*i)->__make_ready(); (*i)->__release_shared(); } } void __thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { notify_.push_back(pair<condition_variable*, mutex*>(cv, m)); } void __thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s) { async_states_.push_back(__s); __s->__add_shared(); } // __thread_struct __thread_struct::__thread_struct() : __p_(new __thread_struct_imp) { } __thread_struct::~__thread_struct() { delete __p_; } void __thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { __p_->notify_all_at_thread_exit(cv, m); } void __thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s) { __p_->__make_ready_at_thread_exit(__s); } _LIBCPP_END_NAMESPACE_STD <commit_msg>Belt and suspenders when calling sysconf<commit_after>//===------------------------- thread.cpp----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "thread" #include "exception" #include "vector" #include "future" #include "limits" #include <sys/types.h> #if !_WIN32 #if !__sun__ && !__linux__ #include <sys/sysctl.h> #else #include <unistd.h> #endif // !__sun__ && !__linux__ #endif // !_WIN32 _LIBCPP_BEGIN_NAMESPACE_STD thread::~thread() { if (__t_ != 0) terminate(); } void thread::join() { int ec = pthread_join(__t_, 0); #ifndef _LIBCPP_NO_EXCEPTIONS if (ec) throw system_error(error_code(ec, system_category()), "thread::join failed"); #endif // _LIBCPP_NO_EXCEPTIONS __t_ = 0; } void thread::detach() { int ec = EINVAL; if (__t_ != 0) { ec = pthread_detach(__t_); if (ec == 0) __t_ = 0; } #ifndef _LIBCPP_NO_EXCEPTIONS if (ec) throw system_error(error_code(ec, system_category()), "thread::detach failed"); #endif // _LIBCPP_NO_EXCEPTIONS } unsigned thread::hardware_concurrency() _NOEXCEPT { #if defined(CTL_HW) && defined(HW_NCPU) unsigned n; int mib[2] = {CTL_HW, HW_NCPU}; std::size_t s = sizeof(n); sysctl(mib, 2, &n, &s, 0, 0); return n; #elif defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L) && defined(_SC_NPROCESSORS_ONLN) long result = sysconf(_SC_NPROCESSORS_ONLN); // sysconf returns -1 if the name is invalid, the option does not exist or // does not have a definite limit. // if sysconf returns some other negative number, we have no idea // what is going on. Default to something safe. if (result < 0) return 0; return static_cast<unsigned>(result); #else // defined(CTL_HW) && defined(HW_NCPU) // TODO: grovel through /proc or check cpuid on x86 and similar // instructions on other architectures. return 0; // Means not computable [thread.thread.static] #endif // defined(CTL_HW) && defined(HW_NCPU) } namespace this_thread { void sleep_for(const chrono::nanoseconds& ns) { using namespace chrono; if (ns > nanoseconds::zero()) { seconds s = duration_cast<seconds>(ns); timespec ts; typedef decltype(ts.tv_sec) ts_sec; _LIBCPP_CONSTEXPR ts_sec ts_sec_max = numeric_limits<ts_sec>::max(); if (s.count() < ts_sec_max) { ts.tv_sec = static_cast<ts_sec>(s.count()); ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((ns-s).count()); } else { ts.tv_sec = ts_sec_max; ts.tv_nsec = giga::num - 1; } nanosleep(&ts, 0); } } } // this_thread __thread_specific_ptr<__thread_struct>& __thread_local_data() { static __thread_specific_ptr<__thread_struct> __p; return __p; } // __thread_struct_imp template <class T> class _LIBCPP_HIDDEN __hidden_allocator { public: typedef T value_type; T* allocate(size_t __n) {return static_cast<T*>(::operator new(__n * sizeof(T)));} void deallocate(T* __p, size_t) {::operator delete((void*)__p);} size_t max_size() const {return size_t(~0) / sizeof(T);} }; class _LIBCPP_HIDDEN __thread_struct_imp { typedef vector<__assoc_sub_state*, __hidden_allocator<__assoc_sub_state*> > _AsyncStates; typedef vector<pair<condition_variable*, mutex*>, __hidden_allocator<pair<condition_variable*, mutex*> > > _Notify; _AsyncStates async_states_; _Notify notify_; __thread_struct_imp(const __thread_struct_imp&); __thread_struct_imp& operator=(const __thread_struct_imp&); public: __thread_struct_imp() {} ~__thread_struct_imp(); void notify_all_at_thread_exit(condition_variable* cv, mutex* m); void __make_ready_at_thread_exit(__assoc_sub_state* __s); }; __thread_struct_imp::~__thread_struct_imp() { for (_Notify::iterator i = notify_.begin(), e = notify_.end(); i != e; ++i) { i->second->unlock(); i->first->notify_all(); } for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end(); i != e; ++i) { (*i)->__make_ready(); (*i)->__release_shared(); } } void __thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { notify_.push_back(pair<condition_variable*, mutex*>(cv, m)); } void __thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s) { async_states_.push_back(__s); __s->__add_shared(); } // __thread_struct __thread_struct::__thread_struct() : __p_(new __thread_struct_imp) { } __thread_struct::~__thread_struct() { delete __p_; } void __thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m) { __p_->notify_all_at_thread_exit(cv, m); } void __thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s) { __p_->__make_ready_at_thread_exit(__s); } _LIBCPP_END_NAMESPACE_STD <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/proxy/ppb_font_proxy.h" #include "ppapi/c/dev/ppb_font_dev.h" #include "ppapi/proxy/plugin_dispatcher.h" #include "ppapi/proxy/plugin_resource.h" #include "ppapi/proxy/ppapi_messages.h" namespace pp { namespace proxy { class Font : public PluginResource { public: Font(const HostResource& resource); virtual ~Font(); // PluginResource overrides. virtual Font* AsFont() { return this; } PP_FontDescription_Dev& desc() { return desc_; } PP_FontDescription_Dev* desc_ptr() { return &desc_; } PP_FontMetrics_Dev& metrics() { return metrics_; } private: PP_FontDescription_Dev desc_; PP_FontMetrics_Dev metrics_; DISALLOW_COPY_AND_ASSIGN(Font); }; Font::Font(const HostResource& resource) : PluginResource(resource) { memset(&desc_, 0, sizeof(PP_FontDescription_Dev)); desc_.face.type = PP_VARTYPE_UNDEFINED; memset(&metrics_, 0, sizeof(PP_FontMetrics_Dev)); } Font::~Font() { PluginVarTracker::GetInstance()->Release(desc_.face); } namespace { PP_Resource Create(PP_Instance instance, const PP_FontDescription_Dev* description) { PluginDispatcher* dispatcher = PluginDispatcher::GetForInstance(instance); if (!dispatcher) return 0; SerializedFontDescription in_description; in_description.SetFromPPFontDescription(dispatcher, *description, true); HostResource result; SerializedFontDescription out_description; std::string out_metrics; dispatcher->Send(new PpapiHostMsg_PPBFont_Create( INTERFACE_ID_PPB_FONT, instance, in_description, &result, &out_description, &out_metrics)); if (result.is_null()) return 0; // Failure creating font. linked_ptr<Font> object(new Font(result)); out_description.SetToPPFontDescription(dispatcher, object->desc_ptr(), true); // Convert the metrics, this is just serialized as a string of bytes. if (out_metrics.size() != sizeof(PP_FontMetrics_Dev)) return 0; memcpy(&object->metrics(), out_metrics.data(), sizeof(PP_FontMetrics_Dev)); return PluginResourceTracker::GetInstance()->AddResource(object); } PP_Bool IsFont(PP_Resource resource) { Font* object = PluginResource::GetAs<Font>(resource); return BoolToPPBool(!!object); } PP_Bool Describe(PP_Resource font_id, PP_FontDescription_Dev* description, PP_FontMetrics_Dev* metrics) { Font* object = PluginResource::GetAs<Font>(font_id); if (!object) return PP_FALSE; // Copy the description, the caller expects its face PP_Var to have a ref // added to it on its behalf. memcpy(description, &object->desc(), sizeof(PP_FontDescription_Dev)); PluginVarTracker::GetInstance()->AddRef(description->face); memcpy(metrics, &object->metrics(), sizeof(PP_FontMetrics_Dev)); return PP_TRUE; } PP_Bool DrawTextAt(PP_Resource font_id, PP_Resource image_data, const PP_TextRun_Dev* text, const PP_Point* position, uint32_t color, const PP_Rect* clip, PP_Bool image_data_is_opaque) { Font* font_object = PluginResource::GetAs<Font>(font_id); if (!font_object) return PP_FALSE; PluginResource* image_object = PluginResourceTracker::GetInstance()-> GetResourceObject(image_data); if (!image_object) return PP_FALSE; if (font_object->instance() != image_object->instance()) return PP_FALSE; PPBFont_DrawTextAt_Params params; params.font = font_object->host_resource(); params.image_data = image_object->host_resource(); params.text_is_rtl = text->rtl; params.override_direction = text->override_direction; params.position = *position; params.color = color; if (clip) { params.clip = *clip; params.clip_is_null = false; } else { params.clip = PP_MakeRectFromXYWH(0, 0, 0, 0); params.clip_is_null = true; } params.image_data_is_opaque = image_data_is_opaque; Dispatcher* dispatcher = PluginDispatcher::GetForInstance( image_object->instance()); PP_Bool result = PP_FALSE; if (dispatcher) { dispatcher->Send(new PpapiHostMsg_PPBFont_DrawTextAt( INTERFACE_ID_PPB_FONT, SerializedVarSendInput(dispatcher, text->text), params, &result)); } return result; } int32_t MeasureText(PP_Resource font_id, const PP_TextRun_Dev* text) { Font* object = PluginResource::GetAs<Font>(font_id); if (!object) return -1; Dispatcher* dispatcher = PluginDispatcher::GetForInstance(object->instance()); int32_t result = 0; dispatcher->Send(new PpapiHostMsg_PPBFont_MeasureText( INTERFACE_ID_PPB_FONT, object->host_resource(), SerializedVarSendInput(dispatcher, text->text), text->rtl, text->override_direction, &result)); return result; } uint32_t CharacterOffsetForPixel(PP_Resource font_id, const PP_TextRun_Dev* text, int32_t pixel_position) { Font* object = PluginResource::GetAs<Font>(font_id); if (!object) return -1; Dispatcher* dispatcher = PluginDispatcher::GetForInstance(object->instance()); uint32_t result = 0; dispatcher->Send(new PpapiHostMsg_PPBFont_CharacterOffsetForPixel( INTERFACE_ID_PPB_FONT, object->host_resource(), SerializedVarSendInput(dispatcher, text->text), text->rtl, text->override_direction, pixel_position, &result)); return result; } int32_t PixelOffsetForCharacter(PP_Resource font_id, const PP_TextRun_Dev* text, uint32_t char_offset) { Font* object = PluginResource::GetAs<Font>(font_id); if (!object) return -1; Dispatcher* dispatcher = PluginDispatcher::GetForInstance(object->instance()); int32_t result = 0; dispatcher->Send(new PpapiHostMsg_PPBFont_PixelOffsetForCharacter( INTERFACE_ID_PPB_FONT, object->host_resource(), SerializedVarSendInput(dispatcher, text->text), text->rtl, text->override_direction, char_offset, &result)); return result; } const PPB_Font_Dev font_interface = { &Create, &IsFont, &Describe, &DrawTextAt, &MeasureText, &CharacterOffsetForPixel, &PixelOffsetForCharacter }; InterfaceProxy* CreateFontProxy(Dispatcher* dispatcher, const void* target_interface) { return new PPB_Font_Proxy(dispatcher, target_interface); } } // namespace PPB_Font_Proxy::PPB_Font_Proxy(Dispatcher* dispatcher, const void* target_interface) : InterfaceProxy(dispatcher, target_interface) { } PPB_Font_Proxy::~PPB_Font_Proxy() { } // static const InterfaceProxy::Info* PPB_Font_Proxy::GetInfo() { static const Info info = { &font_interface, PPB_FONT_DEV_INTERFACE, INTERFACE_ID_PPB_FONT, false, &CreateFontProxy, }; return &info; } bool PPB_Font_Proxy::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PPB_Font_Proxy, msg) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_Create, OnMsgCreate) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_DrawTextAt, OnMsgDrawTextAt) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_MeasureText, OnMsgMeasureText) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_CharacterOffsetForPixel, OnMsgCharacterOffsetForPixel) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_PixelOffsetForCharacter, OnMsgPixelOffsetForCharacter) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void PPB_Font_Proxy::OnMsgCreate( PP_Instance instance, const SerializedFontDescription& in_description, HostResource* result, SerializedFontDescription* out_description, std::string* out_metrics) { // Convert the face name in the input description. PP_FontDescription_Dev in_pp_desc; in_description.SetToPPFontDescription(dispatcher(), &in_pp_desc, false); // Make sure the output is always defined so we can still serialize it back // to the plugin below. PP_FontDescription_Dev out_pp_desc; memset(&out_pp_desc, 0, sizeof(PP_FontDescription_Dev)); out_pp_desc.face = PP_MakeUndefined(); result->SetHostResource(instance, ppb_font_target()->Create(instance, &in_pp_desc)); if (!result->is_null()) { // Get the metrics and resulting description to return to the browser. PP_FontMetrics_Dev metrics; if (ppb_font_target()->Describe(result->host_resource(), &out_pp_desc, &metrics)) { out_metrics->assign(reinterpret_cast<const char*>(&metrics), sizeof(PP_FontMetrics_Dev)); } } // This must always get called or it will assert when trying to serialize // the un-filled-in SerializedFontDescription as the return value. out_description->SetFromPPFontDescription(dispatcher(), out_pp_desc, false); } void PPB_Font_Proxy::OnMsgDrawTextAt(SerializedVarReceiveInput text, const PPBFont_DrawTextAt_Params& params, PP_Bool* result) { PP_TextRun_Dev run; run.text = text.Get(dispatcher()); run.rtl = params.text_is_rtl; run.override_direction = params.override_direction; *result = ppb_font_target()->DrawTextAt(params.font.host_resource(), params.image_data.host_resource(), &run, &params.position, params.color, params.clip_is_null ? NULL : &params.clip, params.image_data_is_opaque); } void PPB_Font_Proxy::OnMsgMeasureText(HostResource font, SerializedVarReceiveInput text, PP_Bool text_is_rtl, PP_Bool override_direction, int32_t* result) { PP_TextRun_Dev run; run.text = text.Get(dispatcher()); run.rtl = text_is_rtl; run.override_direction = override_direction; *result = ppb_font_target()->MeasureText(font.host_resource(), &run); } void PPB_Font_Proxy::OnMsgCharacterOffsetForPixel( HostResource font, SerializedVarReceiveInput text, PP_Bool text_is_rtl, PP_Bool override_direction, int32_t pixel_pos, uint32_t* result) { PP_TextRun_Dev run; run.text = text.Get(dispatcher()); run.rtl = text_is_rtl; run.override_direction = override_direction; *result = ppb_font_target()->CharacterOffsetForPixel(font.host_resource(), &run, pixel_pos); } void PPB_Font_Proxy::OnMsgPixelOffsetForCharacter( HostResource font, SerializedVarReceiveInput text, PP_Bool text_is_rtl, PP_Bool override_direction, uint32_t char_offset, int32_t* result) { PP_TextRun_Dev run; run.text = text.Get(dispatcher()); run.rtl = text_is_rtl; run.override_direction = override_direction; *result = ppb_font_target()->PixelOffsetForCharacter(font.host_resource(), &run, char_offset); } } // namespace proxy } // namespace pp <commit_msg>Protect against a NULL dispatcher<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/proxy/ppb_font_proxy.h" #include "ppapi/c/dev/ppb_font_dev.h" #include "ppapi/proxy/plugin_dispatcher.h" #include "ppapi/proxy/plugin_resource.h" #include "ppapi/proxy/ppapi_messages.h" namespace pp { namespace proxy { class Font : public PluginResource { public: Font(const HostResource& resource); virtual ~Font(); // PluginResource overrides. virtual Font* AsFont() { return this; } PP_FontDescription_Dev& desc() { return desc_; } PP_FontDescription_Dev* desc_ptr() { return &desc_; } PP_FontMetrics_Dev& metrics() { return metrics_; } private: PP_FontDescription_Dev desc_; PP_FontMetrics_Dev metrics_; DISALLOW_COPY_AND_ASSIGN(Font); }; Font::Font(const HostResource& resource) : PluginResource(resource) { memset(&desc_, 0, sizeof(PP_FontDescription_Dev)); desc_.face.type = PP_VARTYPE_UNDEFINED; memset(&metrics_, 0, sizeof(PP_FontMetrics_Dev)); } Font::~Font() { PluginVarTracker::GetInstance()->Release(desc_.face); } namespace { PP_Resource Create(PP_Instance instance, const PP_FontDescription_Dev* description) { PluginDispatcher* dispatcher = PluginDispatcher::GetForInstance(instance); if (!dispatcher) return 0; SerializedFontDescription in_description; in_description.SetFromPPFontDescription(dispatcher, *description, true); HostResource result; SerializedFontDescription out_description; std::string out_metrics; dispatcher->Send(new PpapiHostMsg_PPBFont_Create( INTERFACE_ID_PPB_FONT, instance, in_description, &result, &out_description, &out_metrics)); if (result.is_null()) return 0; // Failure creating font. linked_ptr<Font> object(new Font(result)); out_description.SetToPPFontDescription(dispatcher, object->desc_ptr(), true); // Convert the metrics, this is just serialized as a string of bytes. if (out_metrics.size() != sizeof(PP_FontMetrics_Dev)) return 0; memcpy(&object->metrics(), out_metrics.data(), sizeof(PP_FontMetrics_Dev)); return PluginResourceTracker::GetInstance()->AddResource(object); } PP_Bool IsFont(PP_Resource resource) { Font* object = PluginResource::GetAs<Font>(resource); return BoolToPPBool(!!object); } PP_Bool Describe(PP_Resource font_id, PP_FontDescription_Dev* description, PP_FontMetrics_Dev* metrics) { Font* object = PluginResource::GetAs<Font>(font_id); if (!object) return PP_FALSE; // Copy the description, the caller expects its face PP_Var to have a ref // added to it on its behalf. memcpy(description, &object->desc(), sizeof(PP_FontDescription_Dev)); PluginVarTracker::GetInstance()->AddRef(description->face); memcpy(metrics, &object->metrics(), sizeof(PP_FontMetrics_Dev)); return PP_TRUE; } PP_Bool DrawTextAt(PP_Resource font_id, PP_Resource image_data, const PP_TextRun_Dev* text, const PP_Point* position, uint32_t color, const PP_Rect* clip, PP_Bool image_data_is_opaque) { Font* font_object = PluginResource::GetAs<Font>(font_id); if (!font_object) return PP_FALSE; PluginResource* image_object = PluginResourceTracker::GetInstance()-> GetResourceObject(image_data); if (!image_object) return PP_FALSE; if (font_object->instance() != image_object->instance()) return PP_FALSE; PPBFont_DrawTextAt_Params params; params.font = font_object->host_resource(); params.image_data = image_object->host_resource(); params.text_is_rtl = text->rtl; params.override_direction = text->override_direction; params.position = *position; params.color = color; if (clip) { params.clip = *clip; params.clip_is_null = false; } else { params.clip = PP_MakeRectFromXYWH(0, 0, 0, 0); params.clip_is_null = true; } params.image_data_is_opaque = image_data_is_opaque; Dispatcher* dispatcher = PluginDispatcher::GetForInstance( image_object->instance()); PP_Bool result = PP_FALSE; if (dispatcher) { dispatcher->Send(new PpapiHostMsg_PPBFont_DrawTextAt( INTERFACE_ID_PPB_FONT, SerializedVarSendInput(dispatcher, text->text), params, &result)); } return result; } int32_t MeasureText(PP_Resource font_id, const PP_TextRun_Dev* text) { Font* object = PluginResource::GetAs<Font>(font_id); if (!object) return -1; Dispatcher* dispatcher = PluginDispatcher::GetForInstance(object->instance()); int32_t result = 0; if (dispatcher) { dispatcher->Send(new PpapiHostMsg_PPBFont_MeasureText( INTERFACE_ID_PPB_FONT, object->host_resource(), SerializedVarSendInput(dispatcher, text->text), text->rtl, text->override_direction, &result)); } return result; } uint32_t CharacterOffsetForPixel(PP_Resource font_id, const PP_TextRun_Dev* text, int32_t pixel_position) { Font* object = PluginResource::GetAs<Font>(font_id); if (!object) return -1; Dispatcher* dispatcher = PluginDispatcher::GetForInstance(object->instance()); uint32_t result = 0; if (dispatcher) { dispatcher->Send(new PpapiHostMsg_PPBFont_CharacterOffsetForPixel( INTERFACE_ID_PPB_FONT, object->host_resource(), SerializedVarSendInput(dispatcher, text->text), text->rtl, text->override_direction, pixel_position, &result)); } return result; } int32_t PixelOffsetForCharacter(PP_Resource font_id, const PP_TextRun_Dev* text, uint32_t char_offset) { Font* object = PluginResource::GetAs<Font>(font_id); if (!object) return -1; Dispatcher* dispatcher = PluginDispatcher::GetForInstance(object->instance()); int32_t result = 0; if (dispatcher) { dispatcher->Send(new PpapiHostMsg_PPBFont_PixelOffsetForCharacter( INTERFACE_ID_PPB_FONT, object->host_resource(), SerializedVarSendInput(dispatcher, text->text), text->rtl, text->override_direction, char_offset, &result)); } return result; } const PPB_Font_Dev font_interface = { &Create, &IsFont, &Describe, &DrawTextAt, &MeasureText, &CharacterOffsetForPixel, &PixelOffsetForCharacter }; InterfaceProxy* CreateFontProxy(Dispatcher* dispatcher, const void* target_interface) { return new PPB_Font_Proxy(dispatcher, target_interface); } } // namespace PPB_Font_Proxy::PPB_Font_Proxy(Dispatcher* dispatcher, const void* target_interface) : InterfaceProxy(dispatcher, target_interface) { } PPB_Font_Proxy::~PPB_Font_Proxy() { } // static const InterfaceProxy::Info* PPB_Font_Proxy::GetInfo() { static const Info info = { &font_interface, PPB_FONT_DEV_INTERFACE, INTERFACE_ID_PPB_FONT, false, &CreateFontProxy, }; return &info; } bool PPB_Font_Proxy::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PPB_Font_Proxy, msg) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_Create, OnMsgCreate) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_DrawTextAt, OnMsgDrawTextAt) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_MeasureText, OnMsgMeasureText) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_CharacterOffsetForPixel, OnMsgCharacterOffsetForPixel) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFont_PixelOffsetForCharacter, OnMsgPixelOffsetForCharacter) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void PPB_Font_Proxy::OnMsgCreate( PP_Instance instance, const SerializedFontDescription& in_description, HostResource* result, SerializedFontDescription* out_description, std::string* out_metrics) { // Convert the face name in the input description. PP_FontDescription_Dev in_pp_desc; in_description.SetToPPFontDescription(dispatcher(), &in_pp_desc, false); // Make sure the output is always defined so we can still serialize it back // to the plugin below. PP_FontDescription_Dev out_pp_desc; memset(&out_pp_desc, 0, sizeof(PP_FontDescription_Dev)); out_pp_desc.face = PP_MakeUndefined(); result->SetHostResource(instance, ppb_font_target()->Create(instance, &in_pp_desc)); if (!result->is_null()) { // Get the metrics and resulting description to return to the browser. PP_FontMetrics_Dev metrics; if (ppb_font_target()->Describe(result->host_resource(), &out_pp_desc, &metrics)) { out_metrics->assign(reinterpret_cast<const char*>(&metrics), sizeof(PP_FontMetrics_Dev)); } } // This must always get called or it will assert when trying to serialize // the un-filled-in SerializedFontDescription as the return value. out_description->SetFromPPFontDescription(dispatcher(), out_pp_desc, false); } void PPB_Font_Proxy::OnMsgDrawTextAt(SerializedVarReceiveInput text, const PPBFont_DrawTextAt_Params& params, PP_Bool* result) { PP_TextRun_Dev run; run.text = text.Get(dispatcher()); run.rtl = params.text_is_rtl; run.override_direction = params.override_direction; *result = ppb_font_target()->DrawTextAt(params.font.host_resource(), params.image_data.host_resource(), &run, &params.position, params.color, params.clip_is_null ? NULL : &params.clip, params.image_data_is_opaque); } void PPB_Font_Proxy::OnMsgMeasureText(HostResource font, SerializedVarReceiveInput text, PP_Bool text_is_rtl, PP_Bool override_direction, int32_t* result) { PP_TextRun_Dev run; run.text = text.Get(dispatcher()); run.rtl = text_is_rtl; run.override_direction = override_direction; *result = ppb_font_target()->MeasureText(font.host_resource(), &run); } void PPB_Font_Proxy::OnMsgCharacterOffsetForPixel( HostResource font, SerializedVarReceiveInput text, PP_Bool text_is_rtl, PP_Bool override_direction, int32_t pixel_pos, uint32_t* result) { PP_TextRun_Dev run; run.text = text.Get(dispatcher()); run.rtl = text_is_rtl; run.override_direction = override_direction; *result = ppb_font_target()->CharacterOffsetForPixel(font.host_resource(), &run, pixel_pos); } void PPB_Font_Proxy::OnMsgPixelOffsetForCharacter( HostResource font, SerializedVarReceiveInput text, PP_Bool text_is_rtl, PP_Bool override_direction, uint32_t char_offset, int32_t* result) { PP_TextRun_Dev run; run.text = text.Get(dispatcher()); run.rtl = text_is_rtl; run.override_direction = override_direction; *result = ppb_font_target()->PixelOffsetForCharacter(font.host_resource(), &run, char_offset); } } // namespace proxy } // namespace pp <|endoftext|>
<commit_before>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #ifndef OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP #define OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP #include <cuda_runtime.h> #include "math.hpp" namespace cv { namespace dnn { namespace cuda4dnn { namespace kernels { template <class T> struct abs_functor { __device__ T operator()(T value) { using csl::device::abs; return abs(value); } }; template <class T> struct tanh_functor { __device__ T operator()(T value) { using csl::device::tanh; return tanh(value); } }; template <class T> struct swish_functor { __device__ T operator()(T value) { // f(x) = x * sigmoid(x) using csl::device::fast_divide; using csl::device::fast_exp; return fast_divide(value, static_cast<T>(1) + fast_exp(-value)); } }; template <class T> struct mish_functor { __device__ T operator()(T value) { using csl::device::tanh; using csl::device::log1pexp; return value * tanh(log1pexp(value)); } }; template <> struct mish_functor<float> { __device__ float operator()(float value) { // f(x) = x * tanh(log1pexp(x)); using csl::device::fast_divide; using csl::device::fast_exp; auto e = fast_exp(value); auto n = e * e + 2 * e; if (value <= -0.6f) return value * fast_divide(n, n + 2); return value - 2 * fast_divide(value, n + 2); } }; template <class T> struct sigmoid_functor { __device__ T operator()(T value) { using csl::device::fast_sigmoid; return fast_sigmoid(value); } }; template <class T> struct bnll_functor { __device__ T operator()(T value) { using csl::device::log1pexp; return value > T(0) ? value + log1pexp(-value) : log1pexp(value); } }; template <class T> struct elu_functor { __device__ T operator()(T value) { using csl::device::expm1; return value >= T(0) ? value : expm1(value); } }; template <class T> struct relu_functor { __device__ relu_functor(T slope_) : slope{slope_} { } __device__ T operator()(T value) { using csl::device::log1pexp; return value >= T(0) ? value : slope * value; } T slope; }; template <class T> struct clipped_relu_functor { __device__ clipped_relu_functor(T floor_, T ceiling_) : floor{floor_}, ceiling{ceiling_} { } __device__ T operator()(T value) { using csl::device::clamp; return clamp(value, floor, ceiling); } T floor, ceiling; }; template <class T> struct power_functor { __device__ power_functor(T exp_, T scale_, T shift_) : exp{exp_}, scale{scale_}, shift{shift_} { } __device__ T operator()(T value) { using csl::device::pow; return pow(shift + scale * value, exp); } T exp, scale, shift; }; template <class T> struct max_functor { __device__ T operator()(T x, T y) { using csl::device::max; return max(x, y); } }; template <class T> struct sum_functor { __device__ T operator()(T x, T y) { return x + y; } }; template <class T> struct scaled_sum_functor { __device__ scaled_sum_functor(T scale_x_, T scale_y_) : scale_x{scale_x_}, scale_y{scale_y_} { } __device__ T operator()(T x, T y) { return scale_x * x + scale_y * y; } T scale_x, scale_y; }; template <class T> struct product_functor { __device__ T operator()(T x, T y) { return x * y; } }; template <class T> struct div_functor { __device__ T operator()(T x, T y) { return x / y; } }; }}}} /* namespace cv::dnn::cuda4dnn::kernels */ #endif /* OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP */<commit_msg>use fp32 mish for fp16 mish<commit_after>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #ifndef OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP #define OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP #include <cuda_runtime.h> #include "math.hpp" namespace cv { namespace dnn { namespace cuda4dnn { namespace kernels { template <class T> struct abs_functor { __device__ T operator()(T value) { using csl::device::abs; return abs(value); } }; template <class T> struct tanh_functor { __device__ T operator()(T value) { using csl::device::tanh; return tanh(value); } }; template <class T> struct swish_functor { __device__ T operator()(T value) { // f(x) = x * sigmoid(x) using csl::device::fast_divide; using csl::device::fast_exp; return fast_divide(value, static_cast<T>(1) + fast_exp(-value)); } }; template <class T> struct mish_functor { __device__ T operator()(T value) { using csl::device::tanh; using csl::device::log1pexp; return value * tanh(log1pexp(value)); } }; template <> struct mish_functor<float> { __device__ float operator()(float value) { // f(x) = x * tanh(log1pexp(x)); using csl::device::fast_divide; using csl::device::fast_exp; auto e = fast_exp(value); auto n = e * e + 2 * e; if (value <= -0.6f) return value * fast_divide(n, n + 2); return value - 2 * fast_divide(value, n + 2); } }; #if !defined(__CUDA_ARCH__) || (__CUDA_ARCH__ >= 530) template <> struct mish_functor<__half> { __device__ __half operator()(__half value) { return mish_functor<float>()(value); } }; #endif template <class T> struct sigmoid_functor { __device__ T operator()(T value) { using csl::device::fast_sigmoid; return fast_sigmoid(value); } }; template <class T> struct bnll_functor { __device__ T operator()(T value) { using csl::device::log1pexp; return value > T(0) ? value + log1pexp(-value) : log1pexp(value); } }; template <class T> struct elu_functor { __device__ T operator()(T value) { using csl::device::expm1; return value >= T(0) ? value : expm1(value); } }; template <class T> struct relu_functor { __device__ relu_functor(T slope_) : slope{slope_} { } __device__ T operator()(T value) { using csl::device::log1pexp; return value >= T(0) ? value : slope * value; } T slope; }; template <class T> struct clipped_relu_functor { __device__ clipped_relu_functor(T floor_, T ceiling_) : floor{floor_}, ceiling{ceiling_} { } __device__ T operator()(T value) { using csl::device::clamp; return clamp(value, floor, ceiling); } T floor, ceiling; }; template <class T> struct power_functor { __device__ power_functor(T exp_, T scale_, T shift_) : exp{exp_}, scale{scale_}, shift{shift_} { } __device__ T operator()(T value) { using csl::device::pow; return pow(shift + scale * value, exp); } T exp, scale, shift; }; template <class T> struct max_functor { __device__ T operator()(T x, T y) { using csl::device::max; return max(x, y); } }; template <class T> struct sum_functor { __device__ T operator()(T x, T y) { return x + y; } }; template <class T> struct scaled_sum_functor { __device__ scaled_sum_functor(T scale_x_, T scale_y_) : scale_x{scale_x_}, scale_y{scale_y_} { } __device__ T operator()(T x, T y) { return scale_x * x + scale_y * y; } T scale_x, scale_y; }; template <class T> struct product_functor { __device__ T operator()(T x, T y) { return x * y; } }; template <class T> struct div_functor { __device__ T operator()(T x, T y) { return x / y; } }; }}}} /* namespace cv::dnn::cuda4dnn::kernels */ #endif /* OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP */<|endoftext|>
<commit_before>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #include "precomp.hpp" #include <memory> // unique_ptr #include "opencv2/gapi/gkernel.hpp" #include "opencv2/gapi/own/convert.hpp" #include "api/gbackend_priv.hpp" #include "backends/common/gbackend.hpp" #include "compiler/gobjref.hpp" #include "compiler/gislandmodel.hpp" // GBackend private implementation ///////////////////////////////////////////// void cv::gapi::GBackend::Priv::unpackKernel(ade::Graph & /*graph */ , const ade::NodeHandle & /*op_node*/ , const GKernelImpl & /*impl */ ) { // Default implementation is still there as Priv // is instantiated by some tests. // Priv is even instantiated as a mock object in a number of tests // as a backend and this method is called for mock objects (doing nothing). // FIXME: add a warning message here // FIXME: Do something with this! Ideally this function should be "=0"; } std::unique_ptr<cv::gimpl::GIslandExecutable> cv::gapi::GBackend::Priv::compile(const ade::Graph&, const GCompileArgs&, const std::vector<ade::NodeHandle> &) const { // ...and this method is here for the same reason! GAPI_Assert(false); return {}; } void cv::gapi::GBackend::Priv::addBackendPasses(ade::ExecutionEngineSetupContext &) { // Do nothing by default, plugins may override this to // add custom (backend-specific) graph transformations } // GBackend public implementation ////////////////////////////////////////////// cv::gapi::GBackend::GBackend() { } cv::gapi::GBackend::GBackend(std::shared_ptr<cv::gapi::GBackend::Priv> &&p) : m_priv(std::move(p)) { } cv::gapi::GBackend::Priv& cv::gapi::GBackend::priv() { return *m_priv; } const cv::gapi::GBackend::Priv& cv::gapi::GBackend::priv() const { return *m_priv; } std::size_t cv::gapi::GBackend::hash() const { return std::hash<const cv::gapi::GBackend::Priv*>{}(m_priv.get()); } bool cv::gapi::GBackend::operator== (const cv::gapi::GBackend &rhs) const { return m_priv == rhs.m_priv; } // Abstract Host-side data manipulation //////////////////////////////////////// // Reused between CPU backend and more generic GExecutor namespace cv { namespace gimpl { namespace magazine { // FIXME implement the below functions with visit()? void bindInArg(Mag& mag, const RcDesc &rc, const GRunArg &arg, bool is_umat) { switch (rc.shape) { case GShape::GMAT: { switch (arg.index()) { case GRunArg::index_of<cv::gapi::own::Mat>() : if (is_umat) { auto& mag_umat = mag.template slot<cv::UMat>()[rc.id]; mag_umat = to_ocv(util::get<cv::gapi::own::Mat>(arg)).getUMat(ACCESS_READ); } else { auto& mag_mat = mag.template slot<cv::gapi::own::Mat>()[rc.id]; mag_mat = util::get<cv::gapi::own::Mat>(arg); } break; #if !defined(GAPI_STANDALONE) case GRunArg::index_of<cv::Mat>() : if (is_umat) { auto& mag_umat = mag.template slot<cv::UMat>()[rc.id]; mag_umat = (util::get<cv::UMat>(arg)); } else { auto& mag_mat = mag.template slot<cv::gapi::own::Mat>()[rc.id]; mag_mat = to_own(util::get<cv::Mat>(arg)); } break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } case GShape::GSCALAR: { auto& mag_scalar = mag.template slot<cv::gapi::own::Scalar>()[rc.id]; switch (arg.index()) { case GRunArg::index_of<cv::gapi::own::Scalar>() : mag_scalar = util::get<cv::gapi::own::Scalar>(arg); break; #if !defined(GAPI_STANDALONE) case GRunArg::index_of<cv::Scalar>() : mag_scalar = to_own(util::get<cv::Scalar>(arg)); break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } case GShape::GARRAY: mag.template slot<cv::detail::VectorRef>()[rc.id] = util::get<cv::detail::VectorRef>(arg); break; default: util::throw_error(std::logic_error("Unsupported GShape type")); } } void bindOutArg(Mag& mag, const RcDesc &rc, const GRunArgP &arg, bool is_umat) { switch (rc.shape) { case GShape::GMAT: { switch (arg.index()) { case GRunArgP::index_of<cv::gapi::own::Mat*>() : if (is_umat) { auto& mag_umat = mag.template slot<cv::UMat>()[rc.id]; mag_umat = to_ocv(*(util::get<cv::gapi::own::Mat*>(arg))).getUMat(ACCESS_RW); } else { auto& mag_mat = mag.template slot<cv::gapi::own::Mat>()[rc.id]; mag_mat = *util::get<cv::gapi::own::Mat*>(arg); } break; #if !defined(GAPI_STANDALONE) case GRunArgP::index_of<cv::Mat*>() : if (is_umat) { auto& mag_umat = mag.template slot<cv::UMat>()[rc.id]; mag_umat = (*util::get<cv::UMat*>(arg)); } else { auto& mag_mat = mag.template slot<cv::gapi::own::Mat>()[rc.id]; mag_mat = to_own(*util::get<cv::Mat*>(arg)); } break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } case GShape::GSCALAR: { auto& mag_scalar = mag.template slot<cv::gapi::own::Scalar>()[rc.id]; switch (arg.index()) { case GRunArgP::index_of<cv::gapi::own::Scalar*>() : mag_scalar = *util::get<cv::gapi::own::Scalar*>(arg); break; #if !defined(GAPI_STANDALONE) case GRunArgP::index_of<cv::Scalar*>() : mag_scalar = to_own(*util::get<cv::Scalar*>(arg)); break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } case GShape::GARRAY: mag.template slot<cv::detail::VectorRef>()[rc.id] = util::get<cv::detail::VectorRef>(arg); break; default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } void resetInternalData(Mag& mag, const Data &d) { if (d.storage != Data::Storage::INTERNAL) return; switch (d.shape) { case GShape::GARRAY: util::get<cv::detail::ConstructVec>(d.ctor) (mag.template slot<cv::detail::VectorRef>()[d.rc]); break; case GShape::GSCALAR: mag.template slot<cv::gapi::own::Scalar>()[d.rc] = cv::gapi::own::Scalar(); break; case GShape::GMAT: // Do nothign here - FIXME unify with initInternalData? break; default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } cv::GRunArg getArg(const Mag& mag, const RcDesc &ref) { // Wrap associated CPU object (either host or an internal one) switch (ref.shape) { case GShape::GMAT: return GRunArg(mag.template slot<cv::gapi::own::Mat>().at(ref.id)); case GShape::GSCALAR: return GRunArg(mag.template slot<cv::gapi::own::Scalar>().at(ref.id)); // Note: .at() is intentional for GArray as object MUST be already there // (and constructed by either bindIn/Out or resetInternal) case GShape::GARRAY: return GRunArg(mag.template slot<cv::detail::VectorRef>().at(ref.id)); default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } cv::GRunArgP getObjPtr(Mag& mag, const RcDesc &rc, bool is_umat) { switch (rc.shape) { case GShape::GMAT: if (is_umat) return GRunArgP(&mag.template slot<cv::UMat>()[rc.id]); else return GRunArgP(&mag.template slot<cv::gapi::own::Mat>()[rc.id]); case GShape::GSCALAR: return GRunArgP(&mag.template slot<cv::gapi::own::Scalar>()[rc.id]); // Note: .at() is intentional for GArray as object MUST be already there // (and constructer by either bindIn/Out or resetInternal) case GShape::GARRAY: // FIXME(DM): For some absolutely unknown to me reason, move // semantics is involved here without const_cast to const (and // value from map is moved into return value GRunArgP, leaving // map with broken value I've spent few late Friday hours // debugging this!!!1 return GRunArgP(const_cast<const Mag&>(mag) .template slot<cv::detail::VectorRef>().at(rc.id)); default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } void writeBack(const Mag& mag, const RcDesc &rc, GRunArgP &g_arg, bool is_umat) { switch (rc.shape) { case GShape::GARRAY: // Do nothing - should we really do anything here? break; case GShape::GMAT: { //simply check that memory was not reallocated, i.e. //both instances of Mat pointing to the same memory uchar* out_arg_data = nullptr; switch (g_arg.index()) { case GRunArgP::index_of<cv::gapi::own::Mat*>() : out_arg_data = util::get<cv::gapi::own::Mat*>(g_arg)->data; break; #if !defined(GAPI_STANDALONE) case GRunArgP::index_of<cv::Mat*>() : out_arg_data = util::get<cv::Mat*>(g_arg)->data; break; case GRunArgP::index_of<cv::UMat*>() : out_arg_data = (util::get<cv::UMat*>(g_arg))->getMat(ACCESS_RW).data; break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } if (is_umat) { auto& in_mag = mag.template slot<cv::UMat>().at(rc.id); GAPI_Assert((out_arg_data == (in_mag.getMat(ACCESS_RW).data)) && " data for output parameters was reallocated ?"); } else { auto& in_mag = mag.template slot<cv::gapi::own::Mat>().at(rc.id); GAPI_Assert((out_arg_data == in_mag.data) && " data for output parameters was reallocated ?"); } break; } case GShape::GSCALAR: { switch (g_arg.index()) { case GRunArgP::index_of<cv::gapi::own::Scalar*>() : *util::get<cv::gapi::own::Scalar*>(g_arg) = mag.template slot<cv::gapi::own::Scalar>().at(rc.id); break; #if !defined(GAPI_STANDALONE) case GRunArgP::index_of<cv::Scalar*>() : *util::get<cv::Scalar*>(g_arg) = cv::gapi::own::to_ocv(mag.template slot<cv::gapi::own::Scalar>().at(rc.id)); break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } } // namespace magazine } // namespace gimpl } // namespace cv <commit_msg>G-API: Recent inclusion has broken STANDALONE build<commit_after>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #include "precomp.hpp" #include <memory> // unique_ptr #include "opencv2/gapi/gkernel.hpp" #include "opencv2/gapi/own/convert.hpp" #include "api/gbackend_priv.hpp" #include "backends/common/gbackend.hpp" #include "compiler/gobjref.hpp" #include "compiler/gislandmodel.hpp" // GBackend private implementation ///////////////////////////////////////////// void cv::gapi::GBackend::Priv::unpackKernel(ade::Graph & /*graph */ , const ade::NodeHandle & /*op_node*/ , const GKernelImpl & /*impl */ ) { // Default implementation is still there as Priv // is instantiated by some tests. // Priv is even instantiated as a mock object in a number of tests // as a backend and this method is called for mock objects (doing nothing). // FIXME: add a warning message here // FIXME: Do something with this! Ideally this function should be "=0"; } std::unique_ptr<cv::gimpl::GIslandExecutable> cv::gapi::GBackend::Priv::compile(const ade::Graph&, const GCompileArgs&, const std::vector<ade::NodeHandle> &) const { // ...and this method is here for the same reason! GAPI_Assert(false); return {}; } void cv::gapi::GBackend::Priv::addBackendPasses(ade::ExecutionEngineSetupContext &) { // Do nothing by default, plugins may override this to // add custom (backend-specific) graph transformations } // GBackend public implementation ////////////////////////////////////////////// cv::gapi::GBackend::GBackend() { } cv::gapi::GBackend::GBackend(std::shared_ptr<cv::gapi::GBackend::Priv> &&p) : m_priv(std::move(p)) { } cv::gapi::GBackend::Priv& cv::gapi::GBackend::priv() { return *m_priv; } const cv::gapi::GBackend::Priv& cv::gapi::GBackend::priv() const { return *m_priv; } std::size_t cv::gapi::GBackend::hash() const { return std::hash<const cv::gapi::GBackend::Priv*>{}(m_priv.get()); } bool cv::gapi::GBackend::operator== (const cv::gapi::GBackend &rhs) const { return m_priv == rhs.m_priv; } // Abstract Host-side data manipulation //////////////////////////////////////// // Reused between CPU backend and more generic GExecutor namespace cv { namespace gimpl { namespace magazine { // FIXME implement the below functions with visit()? void bindInArg(Mag& mag, const RcDesc &rc, const GRunArg &arg, bool is_umat) { switch (rc.shape) { case GShape::GMAT: { switch (arg.index()) { case GRunArg::index_of<cv::gapi::own::Mat>() : if (is_umat) { #if !defined(GAPI_STANDALONE) auto& mag_umat = mag.template slot<cv::UMat>()[rc.id]; mag_umat = to_ocv(util::get<cv::gapi::own::Mat>(arg)).getUMat(ACCESS_READ); #else util::throw_error(std::logic_error("UMat is not supported in stadnalone build")); #endif // !defined(GAPI_STANDALONE) } else { auto& mag_mat = mag.template slot<cv::gapi::own::Mat>()[rc.id]; mag_mat = util::get<cv::gapi::own::Mat>(arg); } break; #if !defined(GAPI_STANDALONE) case GRunArg::index_of<cv::Mat>() : if (is_umat) { auto& mag_umat = mag.template slot<cv::UMat>()[rc.id]; mag_umat = (util::get<cv::UMat>(arg)); } else { auto& mag_mat = mag.template slot<cv::gapi::own::Mat>()[rc.id]; mag_mat = to_own(util::get<cv::Mat>(arg)); } break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } case GShape::GSCALAR: { auto& mag_scalar = mag.template slot<cv::gapi::own::Scalar>()[rc.id]; switch (arg.index()) { case GRunArg::index_of<cv::gapi::own::Scalar>() : mag_scalar = util::get<cv::gapi::own::Scalar>(arg); break; #if !defined(GAPI_STANDALONE) case GRunArg::index_of<cv::Scalar>() : mag_scalar = to_own(util::get<cv::Scalar>(arg)); break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } case GShape::GARRAY: mag.template slot<cv::detail::VectorRef>()[rc.id] = util::get<cv::detail::VectorRef>(arg); break; default: util::throw_error(std::logic_error("Unsupported GShape type")); } } void bindOutArg(Mag& mag, const RcDesc &rc, const GRunArgP &arg, bool is_umat) { switch (rc.shape) { case GShape::GMAT: { switch (arg.index()) { case GRunArgP::index_of<cv::gapi::own::Mat*>() : if (is_umat) { #if !defined(GAPI_STANDALONE) auto& mag_umat = mag.template slot<cv::UMat>()[rc.id]; mag_umat = to_ocv(*(util::get<cv::gapi::own::Mat*>(arg))).getUMat(ACCESS_RW); #else util::throw_error(std::logic_error("UMat is not supported in standalone build")); #endif // !defined(GAPI_STANDALONE) } else { auto& mag_mat = mag.template slot<cv::gapi::own::Mat>()[rc.id]; mag_mat = *util::get<cv::gapi::own::Mat*>(arg); } break; #if !defined(GAPI_STANDALONE) case GRunArgP::index_of<cv::Mat*>() : if (is_umat) { auto& mag_umat = mag.template slot<cv::UMat>()[rc.id]; mag_umat = (*util::get<cv::UMat*>(arg)); } else { auto& mag_mat = mag.template slot<cv::gapi::own::Mat>()[rc.id]; mag_mat = to_own(*util::get<cv::Mat*>(arg)); } break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } case GShape::GSCALAR: { auto& mag_scalar = mag.template slot<cv::gapi::own::Scalar>()[rc.id]; switch (arg.index()) { case GRunArgP::index_of<cv::gapi::own::Scalar*>() : mag_scalar = *util::get<cv::gapi::own::Scalar*>(arg); break; #if !defined(GAPI_STANDALONE) case GRunArgP::index_of<cv::Scalar*>() : mag_scalar = to_own(*util::get<cv::Scalar*>(arg)); break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } case GShape::GARRAY: mag.template slot<cv::detail::VectorRef>()[rc.id] = util::get<cv::detail::VectorRef>(arg); break; default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } void resetInternalData(Mag& mag, const Data &d) { if (d.storage != Data::Storage::INTERNAL) return; switch (d.shape) { case GShape::GARRAY: util::get<cv::detail::ConstructVec>(d.ctor) (mag.template slot<cv::detail::VectorRef>()[d.rc]); break; case GShape::GSCALAR: mag.template slot<cv::gapi::own::Scalar>()[d.rc] = cv::gapi::own::Scalar(); break; case GShape::GMAT: // Do nothign here - FIXME unify with initInternalData? break; default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } cv::GRunArg getArg(const Mag& mag, const RcDesc &ref) { // Wrap associated CPU object (either host or an internal one) switch (ref.shape) { case GShape::GMAT: return GRunArg(mag.template slot<cv::gapi::own::Mat>().at(ref.id)); case GShape::GSCALAR: return GRunArg(mag.template slot<cv::gapi::own::Scalar>().at(ref.id)); // Note: .at() is intentional for GArray as object MUST be already there // (and constructed by either bindIn/Out or resetInternal) case GShape::GARRAY: return GRunArg(mag.template slot<cv::detail::VectorRef>().at(ref.id)); default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } cv::GRunArgP getObjPtr(Mag& mag, const RcDesc &rc, bool is_umat) { switch (rc.shape) { case GShape::GMAT: if (is_umat) { #if !defined(GAPI_STANDALONE) return GRunArgP(&mag.template slot<cv::UMat>()[rc.id]); #else util::throw_error(std::logic_error("UMat is not supported in standalone build")); #endif // !defined(GAPI_STANDALONE) } else return GRunArgP(&mag.template slot<cv::gapi::own::Mat>()[rc.id]); case GShape::GSCALAR: return GRunArgP(&mag.template slot<cv::gapi::own::Scalar>()[rc.id]); // Note: .at() is intentional for GArray as object MUST be already there // (and constructer by either bindIn/Out or resetInternal) case GShape::GARRAY: // FIXME(DM): For some absolutely unknown to me reason, move // semantics is involved here without const_cast to const (and // value from map is moved into return value GRunArgP, leaving // map with broken value I've spent few late Friday hours // debugging this!!!1 return GRunArgP(const_cast<const Mag&>(mag) .template slot<cv::detail::VectorRef>().at(rc.id)); default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } void writeBack(const Mag& mag, const RcDesc &rc, GRunArgP &g_arg, bool is_umat) { switch (rc.shape) { case GShape::GARRAY: // Do nothing - should we really do anything here? break; case GShape::GMAT: { //simply check that memory was not reallocated, i.e. //both instances of Mat pointing to the same memory uchar* out_arg_data = nullptr; switch (g_arg.index()) { case GRunArgP::index_of<cv::gapi::own::Mat*>() : out_arg_data = util::get<cv::gapi::own::Mat*>(g_arg)->data; break; #if !defined(GAPI_STANDALONE) case GRunArgP::index_of<cv::Mat*>() : out_arg_data = util::get<cv::Mat*>(g_arg)->data; break; case GRunArgP::index_of<cv::UMat*>() : out_arg_data = (util::get<cv::UMat*>(g_arg))->getMat(ACCESS_RW).data; break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } if (is_umat) { #if !defined(GAPI_STANDALONE) auto& in_mag = mag.template slot<cv::UMat>().at(rc.id); GAPI_Assert((out_arg_data == (in_mag.getMat(ACCESS_RW).data)) && " data for output parameters was reallocated ?"); #else util::throw_error(std::logic_error("UMat is not supported in standalone build")); #endif // !defined(GAPI_STANDALONE) } else { auto& in_mag = mag.template slot<cv::gapi::own::Mat>().at(rc.id); GAPI_Assert((out_arg_data == in_mag.data) && " data for output parameters was reallocated ?"); } break; } case GShape::GSCALAR: { switch (g_arg.index()) { case GRunArgP::index_of<cv::gapi::own::Scalar*>() : *util::get<cv::gapi::own::Scalar*>(g_arg) = mag.template slot<cv::gapi::own::Scalar>().at(rc.id); break; #if !defined(GAPI_STANDALONE) case GRunArgP::index_of<cv::Scalar*>() : *util::get<cv::Scalar*>(g_arg) = cv::gapi::own::to_ocv(mag.template slot<cv::gapi::own::Scalar>().at(rc.id)); break; #endif // !defined(GAPI_STANDALONE) default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?")); } break; } default: util::throw_error(std::logic_error("Unsupported GShape type")); break; } } } // namespace magazine } // namespace gimpl } // namespace cv <|endoftext|>
<commit_before>#include "periodic.h" #include "Element.h" #include <sifteo.h> // Default constructor will not create a valid element, it must be initialized before use using GetRawElement Element::Element() { } Element::Element(const char* name, const char* symbol, const char* group, short atomicNumber, double elementWeight, int numOuterElectrons, double electroNegativity) { this->baseElement = NULL; this->name = name; this->symbol = symbol; this->group = group; this->atomicNumber = atomicNumber; this->elementWeight = elementWeight; this->numOuterElectrons = numOuterElectrons; this->electroNegativity = electroNegativity; } Element::Element(Element* baseElement) { Assert(baseElement != NULL); this->baseElement = baseElement; ResetToBasicState(); } void Element::ResetToBasicState() { this->name = baseElement->name; this->symbol = baseElement->symbol; this->atomicNumber = baseElement->atomicNumber; this->elementWeight = baseElement->elementWeight; this->numOuterElectrons = baseElement->numOuterElectrons; } const char* Element::GetName() { return name; } const char* Element::GetSymbol() { return symbol; } const char* Element::GetGroup() { return group; } short Element::GetAtomicNumber() { return atomicNumber; } double Element::GetElementWeight() { return elementWeight; } int Element::GetNumOuterElectrons() { return numOuterElectrons; } double Element::GetElectroNegativity() { return electroNegativity; } bool Element::IsRawElement() { return baseElement == NULL; } int Element::GetCharge() { if (IsRawElement()) { return 0; } return baseElement->numOuterElectrons - this->numOuterElectrons; } bool Element::ReactWith(Element* other) { //TODO: This method needs to become more complicated to where it stores state about what elements it is interacting with. //LOG("My electrons: %d, Other electrons: %d\n", this->numOuterElectrons, other->numOuterElectrons); //if any element is a noble gas, a bond won't occur. if (strcmp(this->group, "noble") != 0 || strcmp(other->group, "noble") != 0) return false; //if both elements are alkali metals, no bonding will occur else if (strcmp(this->group, "alkali") == 0 && strcmp(other->group, "alkali") == 0) return false; //if both elements are halogens, covalent bonding will occur else if (strcmp(this->group, "halogen") == 0 && strcmp(other->group, "halogen") == 0) return true; //hydrogen will bond with any halogen and form a covalent bond else if (strcmp(this->name, "Hydrogen") == 0 && strcmp(other->group, "halogen") == 0) return true; //The difference in electronegativity is 1.68, which is very near to 1.7 //This is an Ionic bond but a special case in which the difference isn't >= 1.7 //which is why we have a hard coded case (possible to clean up in the future?) else if (strcmp(this->name, "Lithium") == 0 && strcmp(other->name, "Iodine") == 0) return true; //find the greater negativity double maxNegativity = this->electroNegativity > other->electroNegativity ? this->electroNegativity : other->electroNegativity; double minNegativity = this->electroNegativity < other->electroNegativity ? this->electroNegativity : other->electroNegativity; //Ionic if (maxNegativity - minNegativity > 1.7 && this->numOuterElectrons + other->numOuterElectrons == 8) { if (this->numOuterElectrons < other->numOuterElectrons) { int electronsDonated = 8 - other->numOuterElectrons; this->numOuterElectrons -= electronsDonated; other->numOuterElectrons += electronsDonated; } else { int electronsDonated = 8 - this->numOuterElectrons; other->numOuterElectrons -= electronsDonated; this->numOuterElectrons += electronsDonated; } return true; } //covalent else if (maxNegativity - minNegativity <= 1.7) return true; return false; } static Element rawElements[] = { //Alkali Metals Element("Hydrogen", "H", "nonmetal", 1, 1.008, 1, 2.20), Element("Lithium", "Li", "alkali", 3, 6.94, 1, 0.98), Element("Sodium", "Na", "alkali", 11, 22.9898, 1, 0.93), Element("Potassium", "K", "alkali", 19, 39.0938, 1, 0.82), Element("Rubidium", "Rb", "alkali", 37, 85.4678, 1, 0.82), Element("Cesium", "Cs", "alkali", 55, 132.90545196, 1, 0.79), //don't remember if we need this one or not //Halogens Element("Flourine", "F", "halogen", 9, 18.998403163, 7, 3.98), Element("Chlorine", "Cl", "halogen", 17, 35.45, 7, 3.16), Element("Bromine", "Br", "halogen", 35, 79.094, 7, 2.96), Element("Iodine", "I", "halogen", 53, 126.90447, 7, 2.66), //Noble Gases Element("Helium", "He", "noble", 2, 4.002602, 2, 0), Element("Neon", "Ne", "noble", 10, 20.1797, 8, 0), Element("Argon", "Ar", "noble", 18, 39.948, 8, 0), Element("Krypton", "Kr", "noble", 36, 83.798, 8, 0), //alkali earth metals Element("Beryllium", "Be", "alkaliEarth", 4, 9.0121831, 2, 1.27), Element("Magnesium", "Mg", "alkaliEarth", 12, 24.305, 2, 1.31), Element("Calcium", "Ca", "alkaliEarth", 20, 40.078, 2, 1.0), Element("Strontium", "Sr", "alkaliEarth", 38, 87.62, 2, 0.95), Element("Barium", "Ba", "alkaliEarth", 56, 137.327, 2, 0.89), Element("Radium", "Ra", "alkaliEarth", 88, 226, 2, 0.9), //not sure if needed }; void Element::GetRawElement(int num, Element* elementOut) { Assert(num >= 0 && num < GetRawElementCount()); *elementOut = Element(&rawElements[num]); } bool Element::GetRawElement(const char* name, Element* elementOut) { int num = GetRawElementNum(name); if (num < 0) { *elementOut = Element("INVALID", "INV", "INV", 0, 0.0, 0, 0.0); return false; } else { *elementOut = Element(&rawElements[num]); return true; } } int Element::GetRawElementNum(const char* name) { for (int i = 0; i < GetRawElementCount(); i++) { if (strcmp(name, rawElements[i].GetSymbol()) == 0) { return i; } } return -1; } int Element::GetRawElementCount() { return CountOfArray(rawElements); } <commit_msg>Added in group and electroNegativity attributes in the resetToBasicState function<commit_after>#include "periodic.h" #include "Element.h" #include <sifteo.h> // Default constructor will not create a valid element, it must be initialized before use using GetRawElement Element::Element() { } Element::Element(const char* name, const char* symbol, const char* group, short atomicNumber, double elementWeight, int numOuterElectrons, double electroNegativity) { this->baseElement = NULL; this->name = name; this->symbol = symbol; this->group = group; this->atomicNumber = atomicNumber; this->elementWeight = elementWeight; this->numOuterElectrons = numOuterElectrons; this->electroNegativity = electroNegativity; } Element::Element(Element* baseElement) { Assert(baseElement != NULL); this->baseElement = baseElement; ResetToBasicState(); } void Element::ResetToBasicState() { this->name = baseElement->name; this->symbol = baseElement->symbol; this->group = baseElement->group; this->atomicNumber = baseElement->atomicNumber; this->elementWeight = baseElement->elementWeight; this->numOuterElectrons = baseElement->numOuterElectrons; this->electroNegativity = baseElement->electroNegativity; } const char* Element::GetName() { return name; } const char* Element::GetSymbol() { return symbol; } const char* Element::GetGroup() { return group; } short Element::GetAtomicNumber() { return atomicNumber; } double Element::GetElementWeight() { return elementWeight; } int Element::GetNumOuterElectrons() { return numOuterElectrons; } double Element::GetElectroNegativity() { return electroNegativity; } bool Element::IsRawElement() { return baseElement == NULL; } int Element::GetCharge() { if (IsRawElement()) { return 0; } return baseElement->numOuterElectrons - this->numOuterElectrons; } bool Element::ReactWith(Element* other) { //TODO: This method needs to become more complicated to where it stores state about what elements it is interacting with. //LOG("My electrons: %d, Other electrons: %d\n", this->numOuterElectrons, other->numOuterElectrons); //if any element is a noble gas, a bond won't occur. if (strcmp(this->group, "noble") != 0 || strcmp(other->group, "noble") != 0) return false; //if both elements are alkali metals, no bonding will occur else if (strcmp(this->group, "alkali") == 0 && strcmp(other->group, "alkali") == 0) return false; //if both elements are halogens, covalent bonding will occur else if (strcmp(this->group, "halogen") == 0 && strcmp(other->group, "halogen") == 0) return true; //hydrogen will bond with any halogen and form a covalent bond else if (strcmp(this->name, "Hydrogen") == 0 && strcmp(other->group, "halogen") == 0) return true; //The difference in electronegativity is 1.68, which is very near to 1.7 //This is an Ionic bond but a special case in which the difference isn't >= 1.7 //which is why we have a hard coded case (possible to clean up in the future?) else if (strcmp(this->name, "Lithium") == 0 && strcmp(other->name, "Iodine") == 0) return true; //find the greater negativity double maxNegativity = this->electroNegativity > other->electroNegativity ? this->electroNegativity : other->electroNegativity; double minNegativity = this->electroNegativity < other->electroNegativity ? this->electroNegativity : other->electroNegativity; //Ionic if (maxNegativity - minNegativity > 1.7 && this->numOuterElectrons + other->numOuterElectrons == 8) { if (this->numOuterElectrons < other->numOuterElectrons) { int electronsDonated = 8 - other->numOuterElectrons; this->numOuterElectrons -= electronsDonated; other->numOuterElectrons += electronsDonated; } else { int electronsDonated = 8 - this->numOuterElectrons; other->numOuterElectrons -= electronsDonated; this->numOuterElectrons += electronsDonated; } return true; } //covalent else if (maxNegativity - minNegativity <= 1.7) return true; return false; } static Element rawElements[] = { //Alkali Metals Element("Hydrogen", "H", "nonmetal", 1, 1.008, 1, 2.20), Element("Lithium", "Li", "alkali", 3, 6.94, 1, 0.98), Element("Sodium", "Na", "alkali", 11, 22.9898, 1, 0.93), Element("Potassium", "K", "alkali", 19, 39.0938, 1, 0.82), Element("Rubidium", "Rb", "alkali", 37, 85.4678, 1, 0.82), Element("Cesium", "Cs", "alkali", 55, 132.90545196, 1, 0.79), //don't remember if we need this one or not //Halogens Element("Flourine", "F", "halogen", 9, 18.998403163, 7, 3.98), Element("Chlorine", "Cl", "halogen", 17, 35.45, 7, 3.16), Element("Bromine", "Br", "halogen", 35, 79.094, 7, 2.96), Element("Iodine", "I", "halogen", 53, 126.90447, 7, 2.66), //Noble Gases Element("Helium", "He", "noble", 2, 4.002602, 2, 0), Element("Neon", "Ne", "noble", 10, 20.1797, 8, 0), Element("Argon", "Ar", "noble", 18, 39.948, 8, 0), Element("Krypton", "Kr", "noble", 36, 83.798, 8, 0), //alkali earth metals Element("Beryllium", "Be", "alkaliEarth", 4, 9.0121831, 2, 1.27), Element("Magnesium", "Mg", "alkaliEarth", 12, 24.305, 2, 1.31), Element("Calcium", "Ca", "alkaliEarth", 20, 40.078, 2, 1.0), Element("Strontium", "Sr", "alkaliEarth", 38, 87.62, 2, 0.95), Element("Barium", "Ba", "alkaliEarth", 56, 137.327, 2, 0.89), Element("Radium", "Ra", "alkaliEarth", 88, 226, 2, 0.9), //not sure if needed }; void Element::GetRawElement(int num, Element* elementOut) { Assert(num >= 0 && num < GetRawElementCount()); *elementOut = Element(&rawElements[num]); } bool Element::GetRawElement(const char* name, Element* elementOut) { int num = GetRawElementNum(name); if (num < 0) { *elementOut = Element("INVALID", "INV", "INV", 0, 0.0, 0, 0.0); return false; } else { *elementOut = Element(&rawElements[num]); return true; } } int Element::GetRawElementNum(const char* name) { for (int i = 0; i < GetRawElementCount(); i++) { if (strcmp(name, rawElements[i].GetSymbol()) == 0) { return i; } } return -1; } int Element::GetRawElementCount() { return CountOfArray(rawElements); } <|endoftext|>
<commit_before>DEFINE_string(input_file_{{name}}, "{{name}}", "Input file"); Relation<{{tuple_type}}> {{resultsym}}; std::vector<std::string> schema_{{resultsym}} = { {% for c in colnames %}"{{c}},"{% endfor %}} }; <commit_msg>extra brace<commit_after>DEFINE_string(input_file_{{name}}, "{{name}}", "Input file"); Relation<{{tuple_type}}> {{resultsym}}; std::vector<std::string> schema_{{resultsym}} = { {% for c in colnames %}"{{c}},"{% endfor %} }; <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2012 \file main.cpp \author ([email protected]) \date 13.05.2012 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <iostream> #define BOOST_TEST_MODULE RDORealFormatTest #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_SUITE(RDORealFormatTest) BOOST_AUTO_TEST_CASE(Case1) { std::stringstream stream; stream << 0.00001; std::string data; stream >> data; int size = data.size(); BOOST_CHECK(size == 6); } BOOST_AUTO_TEST_SUITE_END() // RDORealFormatTest <commit_msg> - переделан тест<commit_after>/*! \copyright (c) RDO-Team, 2012 \file main.cpp \author ([email protected]) \date 13.05.2012 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <iostream> #define BOOST_TEST_MODULE RDORealFormatTest #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_SUITE(RDORealFormatTest) BOOST_AUTO_TEST_CASE(MantissaPrecision) { double value = 10e+007; std::stringstream stream; stream << value; std::string str = stream.str(); BOOST_CHECK(stream.str() == "1e+008"); } BOOST_AUTO_TEST_SUITE_END() // RDORealFormatTest <|endoftext|>
<commit_before>#include <unistd.h> #include <brick/httpclient/httpclient.h> #include "account.h" #include "httpclient/httpclient.h" #include "include/base/cef_logging.h" namespace { const char fake_id = -1; } Account::Account() { id_ = fake_id; login_ = ""; password_ = ""; domain_ = ""; secure_ = true; label_ = ""; base_url_ = ""; } Account::~Account() { } bool Account::IsExisted() { return id_ != fake_id; } bool Account::IsSecure() { return secure_; } int Account::GetId() { return id_; } void Account::SetId(int id) { id_ = id; } std::string Account::GetLogin() { return login_; } std::string Account::GetDomain() { return domain_; } std::string Account::GetPassword() { /** * ToDo: Нужно передалать работу с паролем на корню: * 1. Хранить в памяти пароль как можно меньше времени * 2. Занулять область памяти где хранился пароль после его использования * 3. Сделать поддержку GNOME Keyring и KWallet. И только при их отсутствии самому хранить пароль * 4. При самостоятельном хранении паролей их нужно чемнить зашифровать (libsodium?). * 5. Ключ для шифрования/дешифрования должен каждый раз читаться из файла и следовать правилу из пунктов 1 и 2 **/ return password_; } std::string Account::GetBaseUrl() { return base_url_; } std::string Account::GetLabel() { return label_; } bool Account::CheckBaseUrl(std::string url) { return (url.find(base_url_) == 0); } std::string Account::GenLabel() { return ( domain_ + "/" + login_ ); } void Account::SetLogin(std::string login) { login_ = login; label_ = GenLabel(); } void Account::SetPassword(std::string password) { password_ = password; } void Account::SetDomain(std::string domain) { domain_ = domain; label_ = GenLabel(); base_url_ = GenBaseUrl(); } void Account::SetSecure(bool is_secure) { secure_ = is_secure; base_url_ = GenBaseUrl(); } void Account::Set( bool secure, std::string domain, std::string login, std::string password) { secure_ = secure; domain_ = domain; login_ = login; password_ = password; label_ = GenLabel(); base_url_ = GenBaseUrl(); } std::string Account::GenBaseUrl() { return ( (secure_ ? "https://" : "http://" ) + domain_ + "/desktop_app/" // ToDo: Need option here? ); } Account::AuthResult Account::Auth(bool renew_password, std::string otp) { AuthResult result; HttpClient::form_map form; // ToDo: use new authentication IM protocol // form["json"] = "y"; // New versions of IM must return result in json format if (renew_password) { // New versions of IM must generate application password form["renew_password"] = "y"; } form["action"] = "login"; form["login"] = login_; if (renew_password && otp.empty()) { // Ugly hack to get application password in older IM versions form["password"] = password_.substr(0, password_.length() - 1); form["otp"] = password_.substr(password_.length() - 1, 1); } else { form["password"] = password_; form["otp"] = otp; } form["user_os_mark"] = GetOsMark(); HttpClient::response r = HttpClient::PostForm( base_url_ + "/login/", &form ); if (r.code == 200) { // Auth successful if (r.body.find("success: true") != std::string::npos) { // Maybe server returns application password? std::string new_password = TryParseApplicationPassword(r.body); if (password_ != new_password) { LOG_IF(WARNING, !renew_password) << "Unexpected password update"; password_ = new_password; } result.success = true; result.error_code = ERROR_CODE::NONE; result.cookies = r.cookies; } else { // Probably application fatal occurred result.success = false; result.error_code = ERROR_CODE::UNKNOWN; } } else if (r.code == -1 ) { // http query failed LOG(WARNING) << "Auth failed (HTTP error): " << r.error; result.success = false; result.error_code = ERROR_CODE::HTTP; result.http_error = r.error; } else if (r.code == 401 ) { // Auth failed LOG(WARNING) << "Auth failed: " << r.body; if (r.body.find("needOtp:") != std::string::npos) { // ToDo: implement OTP authorization result.error_code = ERROR_CODE::OTP; } else if (r.body.find("captchaCode:") != std::string::npos) { result.error_code = ERROR_CODE::CAPTCHA; } else { result.error_code = ERROR_CODE::AUTH; } result.success = false; result.cookies = r.cookies; } else { // Some error occurred... LOG(WARNING) << "Auth failed (Application error): " << r.body; result.error_code = ERROR_CODE::UNKNOWN; result.success = false; result.cookies = r.cookies; } return result; } std::string Account::TryParseApplicationPassword(std::string body) { std::string password; size_t pos = body.find("appPassword: '"); if (pos == std::string::npos) return password_; pos += sizeof("appPassword: '"); password = body.substr( pos - 1, body.find("'", pos + 1) - pos + 1 ); return password; } std::string Account::GetOsMark() { // ToDo: use app_token! char hostname[1024]; gethostname(hostname, 1024); return std::string(hostname); }<commit_msg>Убрал костыли для получения ПП, начиная с версии IM 15.1.5 это можно сделать без хаков<commit_after>#include <unistd.h> #include <brick/httpclient/httpclient.h> #include "account.h" #include "httpclient/httpclient.h" #include "include/base/cef_logging.h" namespace { const char fake_id = -1; } Account::Account() { id_ = fake_id; login_ = ""; password_ = ""; domain_ = ""; secure_ = true; label_ = ""; base_url_ = ""; } Account::~Account() { } bool Account::IsExisted() { return id_ != fake_id; } bool Account::IsSecure() { return secure_; } int Account::GetId() { return id_; } void Account::SetId(int id) { id_ = id; } std::string Account::GetLogin() { return login_; } std::string Account::GetDomain() { return domain_; } std::string Account::GetPassword() { /** * ToDo: Нужно передалать работу с паролем на корню: * 1. Хранить в памяти пароль как можно меньше времени * 2. Занулять область памяти где хранился пароль после его использования * 3. Сделать поддержку GNOME Keyring и KWallet. И только при их отсутствии самому хранить пароль * 4. При самостоятельном хранении паролей их нужно чемнить зашифровать (libsodium?). * 5. Ключ для шифрования/дешифрования должен каждый раз читаться из файла и следовать правилу из пунктов 1 и 2 **/ return password_; } std::string Account::GetBaseUrl() { return base_url_; } std::string Account::GetLabel() { return label_; } bool Account::CheckBaseUrl(std::string url) { return (url.find(base_url_) == 0); } std::string Account::GenLabel() { return ( domain_ + "/" + login_ ); } void Account::SetLogin(std::string login) { login_ = login; label_ = GenLabel(); } void Account::SetPassword(std::string password) { password_ = password; } void Account::SetDomain(std::string domain) { domain_ = domain; label_ = GenLabel(); base_url_ = GenBaseUrl(); } void Account::SetSecure(bool is_secure) { secure_ = is_secure; base_url_ = GenBaseUrl(); } void Account::Set( bool secure, std::string domain, std::string login, std::string password) { secure_ = secure; domain_ = domain; login_ = login; password_ = password; label_ = GenLabel(); base_url_ = GenBaseUrl(); } std::string Account::GenBaseUrl() { return ( (secure_ ? "https://" : "http://" ) + domain_ + "/desktop_app/" // ToDo: Need option here? ); } Account::AuthResult Account::Auth(bool renew_password, std::string otp) { AuthResult result; HttpClient::form_map form; // ToDo: use new authentication IM protocol // form["json"] = "y"; // New versions of IM must return result in json format if (renew_password) { // New versions of IM must generate application password form["renew_password"] = "y"; } form["action"] = "login"; form["login"] = login_; form["password"] = password_; form["otp"] = otp; form["user_os_mark"] = GetOsMark(); HttpClient::response r = HttpClient::PostForm( base_url_ + "/login/", &form ); if (r.code == 200) { // Auth successful if (r.body.find("success: true") != std::string::npos) { // Maybe server returns application password? std::string new_password = TryParseApplicationPassword(r.body); if (password_ != new_password) { LOG_IF(WARNING, !renew_password) << "Unexpected password update"; password_ = new_password; } result.success = true; result.error_code = ERROR_CODE::NONE; result.cookies = r.cookies; } else { // Probably application fatal occurred result.success = false; result.error_code = ERROR_CODE::UNKNOWN; } } else if (r.code == -1 ) { // http query failed LOG(WARNING) << "Auth failed (HTTP error): " << r.error; result.success = false; result.error_code = ERROR_CODE::HTTP; result.http_error = r.error; } else if (r.code == 401 ) { // Auth failed LOG(WARNING) << "Auth failed: " << r.body; if (r.body.find("needOtp:") != std::string::npos) { // ToDo: implement OTP authorization result.error_code = ERROR_CODE::OTP; } else if (r.body.find("captchaCode:") != std::string::npos) { result.error_code = ERROR_CODE::CAPTCHA; } else { result.error_code = ERROR_CODE::AUTH; } result.success = false; result.cookies = r.cookies; } else { // Some error occurred... LOG(WARNING) << "Auth failed (Application error): " << r.body; result.error_code = ERROR_CODE::UNKNOWN; result.success = false; result.cookies = r.cookies; } return result; } std::string Account::TryParseApplicationPassword(std::string body) { std::string password; size_t pos = body.find("appPassword: '"); if (pos == std::string::npos) return password_; pos += sizeof("appPassword: '"); password = body.substr( pos - 1, body.find("'", pos + 1) - pos + 1 ); return password; } std::string Account::GetOsMark() { // ToDo: use app_token! char hostname[1024]; gethostname(hostname, 1024); return std::string(hostname); }<|endoftext|>
<commit_before>// A C++ program to find bridges in a given undirected graph #include <iostream> #include <list> #include <ctime> #include <algorithm> #define NIL -1 #define MAX_DEGREE 5 #define MIN_DEGREE 3 using namespace std; // A class that represents an undirected graph class Graph { int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency lists void bridgeUtil(int v, bool visited[], int disc[], int low[], int parent[]); public: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph void bridge(); // prints all bridges }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; list<int> *subAdj1, *subAdj2; int V1, V2; srand(static_cast<unsigned int>(time(0))); V1 = rand() % V; V2 = V - V1; while (V1 < 4 || V2 < 4) { srand(static_cast<unsigned int>(time(0))); V1 = rand() % V; V2 = V - V1; } cout << V1 << " vertices are randomly selected to construct the 1st sub-graph" << endl; cout << V2 << " vertices are randomly selected to construct the 2nd sub-graph" << endl; // vertex id list: [0..V1-1], [V1, V-1] int degree = 0; for (int i = 0; i < V; i++) { // randomly determine the No. of neighbors for the current vertex srand(static_cast<unsigned int>(time(0))); degree = rand() % (MAX_DEGREE - MIN_DEGREE + 1) + MIN_DEGREE; cout << degree << " neighbors will be attached to vertex " << i << endl; //cout << adj[i].size() << " of them are already there " << endl; int n = degree - adj[i].size(); //cout << "Aditional " << n << " ones are: " << endl; for (int j = 0; j < n; j++) { //cout << "loop index j: " << j << " ===> "; // randomly determine these neighbors srand(static_cast<unsigned int>(time(0))); int randomNeighbor = i < V1 ? rand() % V1 : rand() % V2 + V1; bool found = (find(adj[i].begin(), adj[i].end(), randomNeighbor) != adj[i].end()); while (randomNeighbor == i || found == true) { srand(static_cast<unsigned int>(time(0))); randomNeighbor = i < V1 ? rand() % V1 : rand() % V2 + V1; found = (find(adj[i].begin(), adj[i].end(), randomNeighbor) != adj[i].end()); } //cout << randomNeighbor << endl; adj[i].push_back(randomNeighbor); adj[randomNeighbor].push_back(i); } } srand(static_cast<unsigned int>(time(0))); int bridgeVertex1 = rand() % V1; int bridgeVertex2 = rand() % V2 + V1; cout << "The finally constructed bridge is (" << bridgeVertex1 << ", " << bridgeVertex2 << ")" << endl; adj[bridgeVertex1].push_back(bridgeVertex2); adj[bridgeVertex2].push_back(bridgeVertex1); } void Graph::addEdge(int u, int v) { adj[u].push_back(v); adj[v].push_back(u); // Note: the graph is undirected } // A recursive function that finds and prints bridges using DFS traversal // u --> The vertex to be visited next // visited[] --> keeps tract of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree void Graph::bridgeUtil(int u, bool visited[], int disc[], int low[], int parent[]) { // A static variable is used for simplicity, we can avoid use of static // variable by passing a pointer. static int time = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices aadjacent to this list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // v is current adjacent of u // If v is not visited yet, then recur for it if (!visited[v]) { parent[v] = u; bridgeUtil(v, visited, disc, low, parent); // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = min(low[u], low[v]); // If the lowest vertex reachable from subtree under v is // below u in DFS tree, then u-v is a bridge if (low[v] > disc[u]) cout << u <<" " << v << endl; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = min(low[u], disc[v]); } } // DFS based function to find all bridges. It uses recursive function bridgeUtil() void Graph::bridge() { // Mark all the vertices as not visited bool *visited = new bool[V]; int *disc = new int[V]; int *low = new int[V]; int *parent = new int[V]; // Initialize parent and visited arrays for (int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; } // Call the recursive helper function to find Bridges // in DFS tree rooted with vertex 'i' for (int i = 0; i < V; i++) if (visited[i] == false) bridgeUtil(i, visited, disc, low, parent); } // Driver program to test above function int main() { // Create a graph with following attributes: // 1. the number of vertex is given by user input; // 2. for each vertex, at least 3 neighbors should be linked; // 3. there must be ONLY one bridge in the graph. // int V; cout << "\n Generate a random graph with a single bridge..." << endl; cout << "Please input the number of vertex (at least 8) you want to have in the graph: "; cin >> V; while (V < 8) { cout << "Please input a number larger or equal to 8: "; cin >> V; } Graph g1(V); //g1.addEdge(1, 0); //g1.addEdge(0, 2); //g1.addEdge(2, 1); //g1.addEdge(0, 3); //g1.addEdge(3, 4); g1.bridge(); return 0; } <commit_msg>reformat output, improve the graph generation speed<commit_after>/* * ===================================================================================== * * Filename: bridge-finder.cpp * * Description: A C++ program to find the single bridge in an undirected graph. * The problem is from MapBox directions team's hiring page. Please * refer to http://www.mapbox.com/blog/directions-hiring/ * * Version: 1.0 * Created: 2015/01/10 16时35分46秒 * Revision: none * Compiler: gcc * OS: Mac OS X 10.10.1 * * Author: Lu LIU (lliu), [email protected] * Organization: higis@dbrg * * ===================================================================================== */ #include <stdlib.h> #include <iostream> #include <list> #include <sys/time.h> #include <ctime> #include <algorithm> #define NIL -1 #define MAX_DEGREE 7 #define MIN_DEGREE 3 using namespace std; typedef unsigned long long uint64; // A class that represents an undirected graph class Graph { int V; // No. of vertices int E; // No. of edges list<int> *adj; // A dynamic array of adjacency lists void bridgeProbe(int v, bool visited[], int disc[], int low[], int parent[]); uint64 getCurrentTimeMs(); public: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph void bridge(); // prints all bridges }; Graph::Graph(int V) { // Create a graph with following attributes: // 1. the number of vertex is given by user input; // 2. for each vertex, [MIN_DEGREE, MAX_DEGREE] neighbors will be attached; // 3. there must be ONLY one bridge in the graph. uint64 startTime = getCurrentTimeMs(); this->V = V; this->E = 0; adj = new list<int>[V]; // Two seperated sub-graphs will be constructed respectively. // Their number of vertices (V1 and V2) are randomly determined, but the sum is V. int V1, V2; srand(static_cast<unsigned int>(time(0))); V1 = rand() % V; V2 = V - V1; // According to the "each vertex has at least 3 neighbors" request, there should be // at least 8 vertices in the graph (4 for each sub-graph). while (V1 < 4 || V2 < 4) { srand(static_cast<unsigned int>(time(0))); V1 = rand() % V; V2 = V - V1; } cout << " " << V1 << " vertices are randomly selected to construct the 1st sub-graph" << endl; cout << " " << V2 << " vertices are randomly selected to construct the 2nd sub-graph" << endl; // vertex id list for the two sub-graphs: [0..V1-1] and [V1, V-1] int degree = 0; cout << " Generating the single-bridge graph... " << endl; double progress = 0.0; for (int i = 0; i < V; i++) { // randomly determine the number of neighbors for the current vertex progress = (double)(i + 1) / (double)V * 100.0; cout.precision(1); cout << fixed << progress << "%\r"; cout.flush(); srand(static_cast<unsigned int>(time(0))); degree = rand() % (MAX_DEGREE - MIN_DEGREE + 1) + MIN_DEGREE; int n = degree - adj[i].size(); for (int j = 0; j < n; j++) { // randomly determine these neighbors // they should be unique, and not be the current vertex (otherwise there will be a cycle) int randomNeighbor = i < V1 ? rand() % V1 : rand() % V2 + V1; bool found = (find(adj[i].begin(), adj[i].end(), randomNeighbor) != adj[i].end()); while (randomNeighbor == i || found == true) { srand(static_cast<unsigned int>(time(0))); randomNeighbor = i < V1 ? rand() % V1 : rand() % V2 + V1; found = (find(adj[i].begin(), adj[i].end(), randomNeighbor) != adj[i].end()); } addEdge(i, randomNeighbor); } } cout << " done!" << endl; cout << " Randomly build a bridge between the two sub-graphs... "; srand(static_cast<unsigned int>(time(0))); int bridgeVertex1 = rand() % V1; int bridgeVertex2 = rand() % V2 + V1; addEdge(bridgeVertex1, bridgeVertex2); uint64 elapsedTime = getCurrentTimeMs() - startTime; cout << " done!" << endl; cout << " The built bridge is (" << bridgeVertex1 << ", " << bridgeVertex2 << ")" << endl; cout << " A graph with " << V << " vertices and " << this->E << " undirected edges has been constructed." << endl; cout << " Time consumed: " << elapsedTime << " ms" << endl; } void Graph::addEdge(int u, int v) { adj[u].push_back(v); adj[v].push_back(u); // Note: the graph is undirected E++; } uint64 Graph::getCurrentTimeMs() { struct timeval tv; gettimeofday(&tv, NULL); uint64 ret = tv.tv_usec; ret /= 1000; ret += (tv.tv_sec * 1000); return ret; } // A recursive function that finds and prints bridges using DFS traversal // u --> The vertex to be visited next // visited[] --> keeps tract of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree void Graph::bridgeProbe(int u, bool visited[], int disc[], int low[], int parent[]) { // A static variable is used for simplicity, we can avoid use of static // variable by passing a pointer. static int time = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices aadjacent to this list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // v is current adjacent of u // If v is not visited yet, then recur for it if (!visited[v]) { parent[v] = u; bridgeProbe(v, visited, disc, low, parent); // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = min(low[u], low[v]); // If the lowest vertex reachable from subtree under v is // below u in DFS tree, then u-v is a bridge if (low[v] > disc[u]) cout << endl << " Found it! The bridge is (" << u << ", " << v << ")" << endl; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = min(low[u], disc[v]); } } // DFS based function to find all bridges. It uses recursive function bridgeProbe() void Graph::bridge() { // Mark all the vertices as not visited bool *visited = new bool[V]; int *disc = new int[V]; int *low = new int[V]; int *parent = new int[V]; uint64 startTime = getCurrentTimeMs(); // Initialize parent and visited arrays for (int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; } // Call the recursive helper function to find Bridges // in DFS tree rooted with vertex 'i' for (int i = 0; i < V; i++) if (visited[i] == false) bridgeProbe(i, visited, disc, low, parent); uint64 elapsedTime = getCurrentTimeMs() - startTime; cout << " Time consumed for finding the bridge: " << elapsedTime << " ms" << endl; } // Driver program to test above function int main() { // int V; cout << endl << " # Find the single bridge in a graph " << endl << endl; cout << " This is an interesting problem posted by MapBox directions team. [ref](http://www.mapbox.com/blog/directions-hiring/)" << endl << endl; cout << " My solution contains two steps: " << endl << endl; cout << " 1. Randomly generate a single-bridge graph with a given number of vertex. " << endl; cout << " 2. Find the bridge with Tarjon's bridge-finding algorithm. " << endl << endl; cout << " Here we go. " << endl; cout << endl << " ## Step 1" << endl << endl; cout << " Please input the number of vertex (at least 8) in the graph: "; cin >> V; while (V < 8) { cout << "Please input a number larger or equal to 8: "; cin >> V; } Graph g1(V); cout << endl << " ## Step 2" << endl << endl; cout << " Searching for the bridge..." << endl; g1.bridge(); cout << endl << " Finished, thanks." << endl << endl; cout << " The codes are available at [github](https://github.com/tumluliu/mapbox-directions-hiring)." << endl; cout << " For any question or suggestion, please contact with Lu LIU ([email protected]). " << endl; return 0; } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ #include "opencv2/objdetect.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/opencv_modules.hpp" #ifdef HAVE_OPENCV_HIGHGUI # include "opencv2/highgui.hpp" #endif #include "opencv2/core/private.hpp" #ifdef HAVE_TEGRA_OPTIMIZATION #include "opencv2/objdetect/objdetect_tegra.hpp" #endif #endif <commit_msg>add opencv_ml headers to precomp<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ #include "opencv2/objdetect.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/ml.hpp" #include "opencv2/core/utility.hpp" #include "opencv2/opencv_modules.hpp" #ifdef HAVE_OPENCV_HIGHGUI # include "opencv2/highgui.hpp" #endif #include "opencv2/core/private.hpp" #ifdef HAVE_TEGRA_OPTIMIZATION #include "opencv2/objdetect/objdetect_tegra.hpp" #endif #endif <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "openglqtmenu.h" #include <modules/opengl/shader/shadermanager.h> #include <modules/opengl/shader/shaderresource.h> #include <inviwo/qt/widgets/inviwoapplicationqt.h> #include <inviwo/core/network/processornetwork.h> #include <inviwo/core/util/stdextensions.h> #include <modules/openglqt/shaderwidget.h> #include <warn/push> #include <warn/ignore/all> #include <QMainWindow> #include <QMenuBar> #include <warn/pop> namespace inviwo { OpenGLQtMenu::OpenGLQtMenu() : shadersItem_(nullptr) { if (auto qtApp = dynamic_cast<InviwoApplicationQt*>(InviwoApplication::getPtr())) { if (auto win = qtApp->getMainWindow()) { qtApp->getProcessorNetwork()->addObserver(this); shadersItem_ = win->menuBar()->addMenu(tr("&Shaders")); QAction* reloadShaders = shadersItem_->addAction("Reload All"); connect(reloadShaders, &QAction::triggered,[&](){ shadersReload(); }); } } } void OpenGLQtMenu::updateShadersMenu() { if (!shadersItem_) return; const auto shaders = ShaderManager::getPtr()->getShaders(); std::vector<QMenu*> reused; auto unusedEditors = util::transform(editors_, [](std::pair<const unsigned int, ShaderWidget*> item){ return item.first; }); for (auto shader : shaders) { QMenu*& shaderSubMenu = shadersItems_[shader->getID()]; if (!shaderSubMenu) { shaderSubMenu = shadersItem_->addMenu(QString("Id %1").arg(shader->getID(), 2)); for (auto& item : shader->getShaderObjects()) { auto action = shaderSubMenu->addAction( QString::fromStdString(item.second->getResource()->key())); shaderSubMenu->setTitle(shaderSubMenu->title() + QString(", ") + QString::fromStdString(item.second->getFileName())); connect(action, &QAction::triggered, [&]() { showShader(item.second.get()); }); util::erase_remove(unusedEditors, item.second->getID()); } } reused.push_back(shaderSubMenu); } util::map_erase_remove_if(shadersItems_, [&](std::pair<const unsigned int, QMenu*> item) { if (!util::contains(reused, item.second)) { shadersItem_->removeAction(item.second->menuAction()); delete item.second; return true; } else { return false; } }); for(auto id : unusedEditors) editors_[id]->close(); } void OpenGLQtMenu::showShader(const ShaderObject* obj) { auto win = static_cast<InviwoApplicationQt*>(InviwoApplication::getPtr())->getMainWindow(); auto editor = [&]() { if (auto res = util::map_find_or_null(editors_, obj->getID())) { return res; } else { res = new ShaderWidget(obj, win); editors_[obj->getID()] = res; res->resize(900, 800); return res; } }(); editor->show(); auto id = obj->getID(); connect(editor, &ShaderWidget::widgetClosed, [this, id](){editors_.erase(id);}); } void OpenGLQtMenu::shadersReload() { ShaderManager::getPtr()->rebuildAllShaders(); } void OpenGLQtMenu::onProcessorNetworkDidAddProcessor(Processor* processor) { updateShadersMenu(); } void OpenGLQtMenu::onProcessorNetworkDidRemoveProcessor(Processor* processor) { updateShadersMenu(); } } // namespace <commit_msg>OpenGLQt: Shadermenu, Handle shader reloading better.<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "openglqtmenu.h" #include <modules/opengl/shader/shadermanager.h> #include <modules/opengl/shader/shaderresource.h> #include <inviwo/qt/widgets/inviwoapplicationqt.h> #include <inviwo/core/network/processornetwork.h> #include <inviwo/core/util/stdextensions.h> #include <modules/openglqt/shaderwidget.h> #include <warn/push> #include <warn/ignore/all> #include <QMainWindow> #include <QMenuBar> #include <warn/pop> namespace inviwo { OpenGLQtMenu::OpenGLQtMenu() : shadersItem_(nullptr) { if (auto qtApp = dynamic_cast<InviwoApplicationQt*>(InviwoApplication::getPtr())) { if (auto win = qtApp->getMainWindow()) { qtApp->getProcessorNetwork()->addObserver(this); shadersItem_ = win->menuBar()->addMenu(tr("&Shaders")); QAction* reloadShaders = shadersItem_->addAction("Reload All"); connect(reloadShaders, &QAction::triggered,[&](){ shadersReload(); }); } } } void OpenGLQtMenu::updateShadersMenu() { if (!shadersItem_) return; const auto shaders = ShaderManager::getPtr()->getShaders(); std::vector<QMenu*> reused; auto unusedEditors = util::transform(editors_, [](std::pair<const unsigned int, ShaderWidget*> item){ return item.first; }); for (auto shader : shaders) { QMenu*& shaderSubMenu = shadersItems_[shader->getID()]; if (!shaderSubMenu) { shaderSubMenu = shadersItem_->addMenu(QString("Id %1").arg(shader->getID(), 2)); shader->onReload([this, shader, shaderSubMenu]() { shaderSubMenu->clear(); shaderSubMenu->setTitle(QString("Id %1").arg(shader->getID())); for (auto& item : shader->getShaderObjects()) { auto action = shaderSubMenu->addAction( QString::fromStdString(item.second->getResource()->key())); shaderSubMenu->setTitle(shaderSubMenu->title() + QString(", ") + QString::fromStdString(item.second->getFileName())); connect(action, &QAction::triggered, [&]() { showShader(item.second.get()); }); } }); for (auto& item : shader->getShaderObjects()) { auto action = shaderSubMenu->addAction( QString::fromStdString(item.second->getResource()->key())); shaderSubMenu->setTitle(shaderSubMenu->title() + QString(", ") + QString::fromStdString(item.second->getFileName())); connect(action, &QAction::triggered, [&]() { showShader(item.second.get()); }); util::erase_remove(unusedEditors, item.second->getID()); } } reused.push_back(shaderSubMenu); } util::map_erase_remove_if(shadersItems_, [&](std::pair<const unsigned int, QMenu*> item) { if (!util::contains(reused, item.second)) { shadersItem_->removeAction(item.second->menuAction()); delete item.second; return true; } else { return false; } }); for(auto id : unusedEditors) editors_[id]->close(); } void OpenGLQtMenu::showShader(const ShaderObject* obj) { auto win = static_cast<InviwoApplicationQt*>(InviwoApplication::getPtr())->getMainWindow(); auto editor = [&]() { if (auto res = util::map_find_or_null(editors_, obj->getID())) { return res; } else { res = new ShaderWidget(obj, win); editors_[obj->getID()] = res; res->resize(900, 800); return res; } }(); editor->show(); auto id = obj->getID(); connect(editor, &ShaderWidget::widgetClosed, [this, id](){editors_.erase(id);}); } void OpenGLQtMenu::shadersReload() { ShaderManager::getPtr()->rebuildAllShaders(); } void OpenGLQtMenu::onProcessorNetworkDidAddProcessor(Processor* processor) { updateShadersMenu(); } void OpenGLQtMenu::onProcessorNetworkDidRemoveProcessor(Processor* processor) { updateShadersMenu(); } } // namespace <|endoftext|>
<commit_before>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <sstream> #include <vpr/Thread/UncaughtThreadException.h> namespace vpr { UncaughtThreadException::UncaughtThreadException(const std::string& msg, const std::string& location) throw() : Exception(msg, location) { /* Do nothing. */ ; } UncaughtThreadException::~UncaughtThreadException() throw() { /* Do nothing. */ ; } void UncaughtThreadException::setException(const vpr::Exception& ex) { std::stringstream desc_stream; desc_stream << ex.getExceptionName() << ": " + ex.getDescription(); mDescription = desc_stream.str(); mLocation = ex.getLocation(); mStackTrace = ex.getStackTrace(); } void UncaughtThreadException::setException(const std::exception& ex) { mDescription = ex.what(); mLocation = "Location not availible with std::exception."; mStackTrace = "Stacktrace not availible with std::exception."; } } <commit_msg>Uncaught std::exceptions contain no location information.<commit_after>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <sstream> #include <vpr/Thread/UncaughtThreadException.h> namespace vpr { UncaughtThreadException::UncaughtThreadException(const std::string& msg, const std::string& location) throw() : Exception(msg, location) { /* Do nothing. */ ; } UncaughtThreadException::~UncaughtThreadException() throw() { /* Do nothing. */ ; } void UncaughtThreadException::setException(const vpr::Exception& ex) { std::stringstream desc_stream; desc_stream << ex.getExceptionName() << ": " + ex.getDescription(); mDescription = desc_stream.str(); mLocation = ex.getLocation(); mStackTrace = ex.getStackTrace(); } void UncaughtThreadException::setException(const std::exception& ex) { mDescription = ex.what(); mLocation = ""; mStackTrace = ""; } } <|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include "core/clever.h" #include "modules/std/core/function.h" #include "modules/std/reflection/reflect.h" #include "modules/std/core/array.h" #include "modules/std/core/map.h" namespace clever { namespace modules { namespace std { namespace reflection { // Allocates a Reflect object TypeObject* ReflectType::allocData(CLEVER_TYPE_CTOR_ARGS) const { return new ReflectObject(args->at(0)); } void ReflectType::dump(TypeObject* data, ::std::ostream& out) const { const ReflectObject* intern = static_cast<ReflectObject*>(data); Value* value = intern->getData(); out << "Reflect("; out << value->getType()->getName(); out << ")"; } // Reflect::Reflect(object) // Returns an instance of Reflect object CLEVER_METHOD(ReflectType::ctor) { if (!clever_check_args(".")) { return; } result->setObj(this, allocData(&args)); } // Reflect::getType() // Returns the type name of the object CLEVER_METHOD(ReflectType::getType) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); if (intern->getData()->getType()) { result->setStr(new StrObject(intern->getData()->getType()->getName())); } else { result->setNull(); } } // Reflect::isFunction() // Check if the object is of function type CLEVER_METHOD(ReflectType::isFunction) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isFunction()); } // Reflect::isBool() // Check if the object is of bool type CLEVER_METHOD(ReflectType::isBool) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isBool()); } // Reflect::isString() // Check if the object is of string type CLEVER_METHOD(ReflectType::isString) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isStr()); } // Reflect::isInt() // Check if the object is of int type CLEVER_METHOD(ReflectType::isInt) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isInt()); } // Reflect::isDouble() // Check if the object is of double type CLEVER_METHOD(ReflectType::isDouble) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isDouble()); } // Reflect::isArray() // Check if the object is of double type CLEVER_METHOD(ReflectType::isArray) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isArray()); } // Reflect::isMap() // Check if the object is of map type CLEVER_METHOD(ReflectType::isMap) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isMap()); } // Reflect::isThread() // Check if the object is of thread type CLEVER_METHOD(ReflectType::isThread) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isThread()); } // Reflect::getName() // Returns the name of the type or function CLEVER_METHOD(ReflectType::getName) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setStr(CSTRING(func->getName())); } // Reflect::isStatic() // Check if the object is an static function CLEVER_METHOD(ReflectType::isStatic) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setBool(func->isStatic()); } // Reflect::isVariadic() // Check if the object is a variadic function CLEVER_METHOD(ReflectType::isVariadic) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setBool(func->isVariadic()); } // Reflect::isUserDefined() // Check if the object is an user-defined function CLEVER_METHOD(ReflectType::isUserDefined) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setBool(func->isUserDefined()); } // Reflect::isInternal() // Check if the object is an internal function CLEVER_METHOD(ReflectType::isInternal) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setBool(func->isInternal()); } // Reflect::getNumArgs() // Returns the number of arguments (variadic is not in the count) CLEVER_METHOD(ReflectType::getNumArgs) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setInt(func->getNumArgs()); } // Reflect::getNumRegArgs() // Returns the number of required arguments (variadic is not in the count) CLEVER_METHOD(ReflectType::getNumReqArgs) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setInt(func->getNumRequiredArgs()); } // Reflect::getMethods() // Returns an array containing the type methods CLEVER_METHOD(ReflectType::getMethods) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const MethodMap& methods = intern->getData()->getType()->getMethods(); MethodMap::const_iterator it(methods.begin()), end(methods.end()); ArrayObject* arr = new ArrayObject; while (it != end) { Value* val = new Value; val->setStr(CSTRING(it->second->getName())); arr->getData().push_back(val); ++it; } result->setObj(CLEVER_ARRAY_TYPE, arr); } // Reflect::getProperties() // Returns a map containing the type properties CLEVER_METHOD(ReflectType::getProperties) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const PropertyMap& props = intern->getData()->getType()->getProperties(); PropertyMap::const_iterator it(props.begin()), end(props.end()); MapObject* map = new MapObject; while (it != end) { map->getData().insert(MapObjectPair(*it->first, it->second)); it->second->addRef(); ++it; } result->setObj(CLEVER_MAP_TYPE, map); } // Reflect::getInternClassSizes() // Returns the sizes of the Intern classes CLEVER_METHOD(ReflectType::getInternClassSizes) { printf("class \"Value\" : %N \n", sizeof(Value)); } // Reflect type initialization CLEVER_TYPE_INIT(ReflectType::init) { setConstructor((MethodPtr) &ReflectType::ctor); addMethod(new Function("getType", (MethodPtr) &ReflectType::getType)); // Type checking addMethod(new Function("isFunction", (MethodPtr) &ReflectType::isFunction)); addMethod(new Function("isBool", (MethodPtr) &ReflectType::isBool)); addMethod(new Function("isString", (MethodPtr) &ReflectType::isString)); addMethod(new Function("isInt", (MethodPtr) &ReflectType::isInt)); addMethod(new Function("isDouble", (MethodPtr) &ReflectType::isDouble)); addMethod(new Function("isArray", (MethodPtr) &ReflectType::isArray)); addMethod(new Function("isMap", (MethodPtr) &ReflectType::isMap)); addMethod(new Function("isThread", (MethodPtr) &ReflectType::isThread)); // Function specific methods addMethod(new Function("getName", (MethodPtr) &ReflectType::getName)); addMethod(new Function("isStatic", (MethodPtr) &ReflectType::isStatic)); addMethod(new Function("isVariadic", (MethodPtr) &ReflectType::isVariadic)); addMethod(new Function("isUserDefined", (MethodPtr) &ReflectType::isUserDefined)); addMethod(new Function("isInternal", (MethodPtr) &ReflectType::isInternal)); addMethod(new Function("getNumArgs", (MethodPtr) &ReflectType::getNumArgs)); addMethod(new Function("getNumReqArgs", (MethodPtr) &ReflectType::getNumReqArgs)); // Type specific methods addMethod(new Function("getMethods", (MethodPtr) &ReflectType::getMethods)); addMethod(new Function("getProperties", (MethodPtr) &ReflectType::getProperties)); addMethod(new Function("getInternClassSizes", (MethodPtr) &ReflectType::getInternClassSizes)) ->setStatic(); } }}}} // clever::modules::std::reflection <commit_msg>More classes and types added to Reflect.getInternClassSizes<commit_after>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include "core/clever.h" #include "modules/std/core/function.h" #include "modules/std/reflection/reflect.h" #include "modules/std/core/array.h" #include "modules/std/core/map.h" namespace clever { namespace modules { namespace std { namespace reflection { // Allocates a Reflect object TypeObject* ReflectType::allocData(CLEVER_TYPE_CTOR_ARGS) const { return new ReflectObject(args->at(0)); } void ReflectType::dump(TypeObject* data, ::std::ostream& out) const { const ReflectObject* intern = static_cast<ReflectObject*>(data); Value* value = intern->getData(); out << "Reflect("; out << value->getType()->getName(); out << ")"; } // Reflect::Reflect(object) // Returns an instance of Reflect object CLEVER_METHOD(ReflectType::ctor) { if (!clever_check_args(".")) { return; } result->setObj(this, allocData(&args)); } // Reflect::getType() // Returns the type name of the object CLEVER_METHOD(ReflectType::getType) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); if (intern->getData()->getType()) { result->setStr(new StrObject(intern->getData()->getType()->getName())); } else { result->setNull(); } } // Reflect::isFunction() // Check if the object is of function type CLEVER_METHOD(ReflectType::isFunction) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isFunction()); } // Reflect::isBool() // Check if the object is of bool type CLEVER_METHOD(ReflectType::isBool) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isBool()); } // Reflect::isString() // Check if the object is of string type CLEVER_METHOD(ReflectType::isString) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isStr()); } // Reflect::isInt() // Check if the object is of int type CLEVER_METHOD(ReflectType::isInt) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isInt()); } // Reflect::isDouble() // Check if the object is of double type CLEVER_METHOD(ReflectType::isDouble) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isDouble()); } // Reflect::isArray() // Check if the object is of double type CLEVER_METHOD(ReflectType::isArray) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isArray()); } // Reflect::isMap() // Check if the object is of map type CLEVER_METHOD(ReflectType::isMap) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isMap()); } // Reflect::isThread() // Check if the object is of thread type CLEVER_METHOD(ReflectType::isThread) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); result->setBool(intern->getData()->isThread()); } // Reflect::getName() // Returns the name of the type or function CLEVER_METHOD(ReflectType::getName) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setStr(CSTRING(func->getName())); } // Reflect::isStatic() // Check if the object is an static function CLEVER_METHOD(ReflectType::isStatic) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setBool(func->isStatic()); } // Reflect::isVariadic() // Check if the object is a variadic function CLEVER_METHOD(ReflectType::isVariadic) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setBool(func->isVariadic()); } // Reflect::isUserDefined() // Check if the object is an user-defined function CLEVER_METHOD(ReflectType::isUserDefined) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setBool(func->isUserDefined()); } // Reflect::isInternal() // Check if the object is an internal function CLEVER_METHOD(ReflectType::isInternal) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setBool(func->isInternal()); } // Reflect::getNumArgs() // Returns the number of arguments (variadic is not in the count) CLEVER_METHOD(ReflectType::getNumArgs) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setInt(func->getNumArgs()); } // Reflect::getNumRegArgs() // Returns the number of required arguments (variadic is not in the count) CLEVER_METHOD(ReflectType::getNumReqArgs) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const Value* data = intern->getData(); if (!data->isFunction()) { return; } const Function* func = static_cast<Function*>(data->getObj()); result->setInt(func->getNumRequiredArgs()); } // Reflect::getMethods() // Returns an array containing the type methods CLEVER_METHOD(ReflectType::getMethods) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const MethodMap& methods = intern->getData()->getType()->getMethods(); MethodMap::const_iterator it(methods.begin()), end(methods.end()); ArrayObject* arr = new ArrayObject; while (it != end) { Value* val = new Value; val->setStr(CSTRING(it->second->getName())); arr->getData().push_back(val); ++it; } result->setObj(CLEVER_ARRAY_TYPE, arr); } // Reflect::getProperties() // Returns a map containing the type properties CLEVER_METHOD(ReflectType::getProperties) { if (!clever_check_no_args()) { return; } const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS()); const PropertyMap& props = intern->getData()->getType()->getProperties(); PropertyMap::const_iterator it(props.begin()), end(props.end()); MapObject* map = new MapObject; while (it != end) { map->getData().insert(MapObjectPair(*it->first, it->second)); it->second->addRef(); ++it; } result->setObj(CLEVER_MAP_TYPE, map); } // Reflect::getInternClassSizes() // Returns the sizes of the Intern classes CLEVER_METHOD(ReflectType::getInternClassSizes) { printf("_______________________\n"); printf("Types\n"); printf("-----------------------\n"); printf("type bool : %N \n", sizeof(bool)); printf("type char : %N \n", sizeof(char)); printf("type size_t : %N \n", sizeof(size_t)); printf("type int : %N \n", sizeof(int)); printf("type long : %N \n", sizeof(long)); printf("type float : %N \n", sizeof(float)); printf("type double : %N \n", sizeof(double)); printf("type pointer : %N \n", sizeof(void*)); printf("_______________________\n"); printf("Classes\n"); printf("-----------------------\n"); printf("class \"RefCounted\" : %N \n", sizeof(RefCounted)); printf("class \"Value\" : %N \n", sizeof(Value)); } // Reflect type initialization CLEVER_TYPE_INIT(ReflectType::init) { setConstructor((MethodPtr) &ReflectType::ctor); addMethod(new Function("getType", (MethodPtr) &ReflectType::getType)); // Type checking addMethod(new Function("isFunction", (MethodPtr) &ReflectType::isFunction)); addMethod(new Function("isBool", (MethodPtr) &ReflectType::isBool)); addMethod(new Function("isString", (MethodPtr) &ReflectType::isString)); addMethod(new Function("isInt", (MethodPtr) &ReflectType::isInt)); addMethod(new Function("isDouble", (MethodPtr) &ReflectType::isDouble)); addMethod(new Function("isArray", (MethodPtr) &ReflectType::isArray)); addMethod(new Function("isMap", (MethodPtr) &ReflectType::isMap)); addMethod(new Function("isThread", (MethodPtr) &ReflectType::isThread)); // Function specific methods addMethod(new Function("getName", (MethodPtr) &ReflectType::getName)); addMethod(new Function("isStatic", (MethodPtr) &ReflectType::isStatic)); addMethod(new Function("isVariadic", (MethodPtr) &ReflectType::isVariadic)); addMethod(new Function("isUserDefined", (MethodPtr) &ReflectType::isUserDefined)); addMethod(new Function("isInternal", (MethodPtr) &ReflectType::isInternal)); addMethod(new Function("getNumArgs", (MethodPtr) &ReflectType::getNumArgs)); addMethod(new Function("getNumReqArgs", (MethodPtr) &ReflectType::getNumReqArgs)); // Type specific methods addMethod(new Function("getMethods", (MethodPtr) &ReflectType::getMethods)); addMethod(new Function("getProperties", (MethodPtr) &ReflectType::getProperties)); addMethod(new Function("getInternClassSizes", (MethodPtr) &ReflectType::getInternClassSizes)) ->setStatic(); } }}}} // clever::modules::std::reflection <|endoftext|>
<commit_before>// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk. #include "vector.hpp" namespace lsh { /** * Create a new vector from existing component chunks. * * @param components The existing component chunks. * @param size The number of components. */ vector::vector(const std::vector<unsigned int>& cs, unsigned int s) { this->size_ = s; unsigned int n = cs.size(); this->components_.reserve(n); for (unsigned int i = 0; i < n; i++) { this->components_[i] = cs[i]; } } /** * Construct a new vector. * * @param components The components of the vector. */ vector::vector(const std::vector<bool>& cs) { this->size_ = cs.size(); unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int i = 0; unsigned int k = 0; while (i < s) { this->components_.push_back(0); // Compute the number of bits in the current chunk. unsigned int b = i + c > s ? s - i : c; for (unsigned int j = 0; j < b; j++) { this->components_[k] |= cs[i + j] << (b - j - 1); } i += b; k += 1; } } /** * Get the number of components in this vector. * * @return The number of components in this vector. */ unsigned int vector::size() const { return this->size_; } /** * Get the component at the specified index of this vector. * * @param index The index of the component to get. * @return The component at the index. */ bool vector::get(unsigned int i) const { unsigned int s = this->size_; unsigned int c = this->chunk_size_; if (i >= s) { throw std::out_of_range("Invalid index"); } // Compute the index of the target chunk. unsigned int d = i / s; // Compute the index of the first bit of the target chunk. unsigned int j = d * s; // Compute the number of bits in the target chunk. unsigned int b = j + c > s ? s - j : c; return (this->components_[d] >> (b - (i % s) - 1)) & 1; } /** * Get a string representation of this vector. * * @return The string representation of the vector. */ std::string vector::to_string() const { unsigned int n = this->size_; std::string value = "Vector["; for (unsigned int i = 0; i < n; i++) { value += std::to_string(this->get(i)); } return value + "]"; } /** * Check if this vector equals another vector. * * @param vector The other vector. * @return `true` if this vector equals the other vector, otherwise `false`. */ bool vector::operator==(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } return vector::distance(*this, v) == 0; } /** * Compute the dot product of this and another vector. * * @param vector The other vector. * @return The dot product of this and another vector. */ unsigned int vector::operator*(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int d = 0; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(this->components_[i] & v.components_[i]); } return d; } /** * Compute the dot product of this vector and an integer. * * @param integer The integer. * @return The dot product of this vector and an integer. */ unsigned int vector::operator*(unsigned int it) const { unsigned int d = 0; unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { // Compute the index of the first bit of the current chunk. unsigned int j = c * i; // Compute the number of bits in the current chunk. unsigned int m = j + c > s ? s - j : c; // Grab the bits of the integer that correspond to the current chunk. unsigned int b = (it >> (s - j - m)) % (1 << m); d += __builtin_popcount(this->components_[i] & b); } return d; } /** * Compute the bitwise AND of this and another vector. * * @param vector The other vector. * @return The bitwise AND of this and another vector. */ vector vector::operator&(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int n = this->components_.size(); std::vector<unsigned int> c(n); for (unsigned int i = 0; i < n; i++) { c[i] = this->components_[i] & v.components_[i]; } return vector(c, this->size_); } /** * Compupte the hash of this vector. * * @return The hash of this vector. */ int vector::hash() const { unsigned int n = this->components_.size(); unsigned long h = 7; for (unsigned int i = 0; i < n; i++) { h = 31 * h + this->components_[i]; } return h ^ (h >> 32); } /** * Compute the distance between two vectors. * * @param u The first vector. * @param v The second vector. * @return The distance between the two vectors. */ int vector::distance(const vector& u, const vector& v) { if (u.size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int d = 0; unsigned int n = u.components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(u.components_[i] ^ v.components_[i]); } return d; } /** * Construct a random vector of a given dimensionality. * * @param dimensions The number of dimensions in the vector. * @return The randomly generated vector. */ vector vector::random(unsigned int d) { std::random_device random; std::mt19937 generator(random()); std::uniform_int_distribution<> components(0, 1); std::vector<bool> c(d); for (unsigned int i = 0; i < d; i++) { c[i] = components(generator); } return vector(c); } } <commit_msg>Improve vector component initialisation<commit_after>// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk. #include "vector.hpp" namespace lsh { /** * Create a new vector from existing component chunks. * * @param components The existing component chunks. * @param size The number of components. */ vector::vector(const std::vector<unsigned int>& cs, unsigned int s) { this->size_ = s; unsigned int n = cs.size(); this->components_.reserve(n); for (unsigned int i = 0; i < n; i++) { this->components_[i] = cs[i]; } } /** * Construct a new vector. * * @param components The components of the vector. */ vector::vector(const std::vector<bool>& cs) { this->size_ = cs.size(); unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int i = 0; unsigned int k = 0; unsigned int n = (s + c - 1) / c; this->components_.resize(n, 0); while (i < s) { // Compute the number of bits in the current chunk. unsigned int b = i + c > s ? s - i : c; for (unsigned int j = 0; j < b; j++) { this->components_[k] |= cs[i + j] << (b - j - 1); } i += b; k += 1; } } /** * Get the number of components in this vector. * * @return The number of components in this vector. */ unsigned int vector::size() const { return this->size_; } /** * Get the component at the specified index of this vector. * * @param index The index of the component to get. * @return The component at the index. */ bool vector::get(unsigned int i) const { unsigned int s = this->size_; unsigned int c = this->chunk_size_; if (i >= s) { throw std::out_of_range("Invalid index"); } // Compute the index of the target chunk. unsigned int d = i / s; // Compute the index of the first bit of the target chunk. unsigned int j = d * s; // Compute the number of bits in the target chunk. unsigned int b = j + c > s ? s - j : c; return (this->components_[d] >> (b - (i % s) - 1)) & 1; } /** * Get a string representation of this vector. * * @return The string representation of the vector. */ std::string vector::to_string() const { unsigned int n = this->size_; std::string value = "Vector["; for (unsigned int i = 0; i < n; i++) { value += std::to_string(this->get(i)); } return value + "]"; } /** * Check if this vector equals another vector. * * @param vector The other vector. * @return `true` if this vector equals the other vector, otherwise `false`. */ bool vector::operator==(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } return vector::distance(*this, v) == 0; } /** * Compute the dot product of this and another vector. * * @param vector The other vector. * @return The dot product of this and another vector. */ unsigned int vector::operator*(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int d = 0; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(this->components_[i] & v.components_[i]); } return d; } /** * Compute the dot product of this vector and an integer. * * @param integer The integer. * @return The dot product of this vector and an integer. */ unsigned int vector::operator*(unsigned int it) const { unsigned int d = 0; unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { // Compute the index of the first bit of the current chunk. unsigned int j = c * i; // Compute the number of bits in the current chunk. unsigned int m = j + c > s ? s - j : c; // Grab the bits of the integer that correspond to the current chunk. unsigned int b = (it >> (s - j - m)) % (1 << m); d += __builtin_popcount(this->components_[i] & b); } return d; } /** * Compute the bitwise AND of this and another vector. * * @param vector The other vector. * @return The bitwise AND of this and another vector. */ vector vector::operator&(const vector& v) const { if (this->size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int n = this->components_.size(); std::vector<unsigned int> c(n); for (unsigned int i = 0; i < n; i++) { c[i] = this->components_[i] & v.components_[i]; } return vector(c, this->size_); } /** * Compupte the hash of this vector. * * @return The hash of this vector. */ int vector::hash() const { unsigned int n = this->components_.size(); unsigned long h = 7; for (unsigned int i = 0; i < n; i++) { h = 31 * h + this->components_[i]; } return h ^ (h >> 32); } /** * Compute the distance between two vectors. * * @param u The first vector. * @param v The second vector. * @return The distance between the two vectors. */ int vector::distance(const vector& u, const vector& v) { if (u.size() != v.size()) { throw std::invalid_argument("Invalid vector size"); } unsigned int d = 0; unsigned int n = u.components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(u.components_[i] ^ v.components_[i]); } return d; } /** * Construct a random vector of a given dimensionality. * * @param dimensions The number of dimensions in the vector. * @return The randomly generated vector. */ vector vector::random(unsigned int d) { std::random_device random; std::mt19937 generator(random()); std::uniform_int_distribution<> components(0, 1); std::vector<bool> c(d); for (unsigned int i = 0; i < d; i++) { c[i] = components(generator); } return vector(c); } } <|endoftext|>
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 29 #define BUILD_NUMBER 44 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <commit_msg>[Auto-roll] Bump up version to 3.29.45.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 29 #define BUILD_NUMBER 45 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <|endoftext|>
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 29 #define BUILD_NUMBER 7 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <commit_msg>[Auto-roll] Bump up version to 3.29.8.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 29 #define BUILD_NUMBER 8 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <|endoftext|>
<commit_before>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "plot_pane.h" #include "models/transmissionline/catenary.h" #include "line_renderer_2d.h" #include "span_analyzer_view.h" BEGIN_EVENT_TABLE(PlotPane, wxPanel) EVT_LEFT_DOWN(PlotPane::OnMouse) EVT_LEFT_UP(PlotPane::OnMouse) EVT_MOTION(PlotPane::OnMouse) EVT_MOUSEWHEEL(PlotPane::OnMouseWheel) EVT_PAINT(PlotPane::OnPaint) END_EVENT_TABLE() PlotPane::PlotPane(wxWindow* parent, wxView* view) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL) { view_ = view; plot_.set_background(*wxBLACK_BRUSH); plot_.set_is_fitted(true); plot_.set_ratio_aspect(10); } PlotPane::~PlotPane() { } void PlotPane::Update(wxObject* hint) { wxClientDC dc(this); // interprets hint ViewUpdateHint* hint_update = (ViewUpdateHint*)hint; if (hint_update == nullptr) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelAnalysisWeathercaseEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelPreferencesEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelSpansEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelWeathercaseEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewConditionChange) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewWeathercaseChange) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewWeathercasesSetChange) { UpdatePlot(); RenderPlot(dc); } } void PlotPane::ClearPlot(wxDC& dc) { dc.Clear(); } void PlotPane::OnMouse(wxMouseEvent& event) { if (event.LeftDown() == true) { // caches the mouse coordinates coord_mouse_.x = event.GetX(); coord_mouse_.y = event.GetY(); } else if (event.LeftUp() == true) { coord_mouse_.x = -999999; coord_mouse_.y = -999999; } else if (event.Dragging() == true) { // checks if left button is pressed if (event.LeftIsDown() == false) { return; } // disables plot fitting if active if (plot_.is_fitted() == true) { plot_.set_is_fitted(false); } // gets updated mouse point from event wxPoint coord_new; coord_new.x = event.GetX(); coord_new.y = event.GetY(); // finds difference between cached and new mouse points // applies inversion to make plot track mouse position const double kShiftX = (coord_new.x - coord_mouse_.x) * -1; const double kShiftY = (coord_new.y - coord_mouse_.y); plot_.Shift(kShiftX, kShiftY); // updates cached mouse point coord_mouse_ = coord_new; // refreshes window this->Refresh(); } } void PlotPane::OnMouseWheel(wxMouseEvent& event) { // zoom factor const double kZoomFactor = 1.2; // zoom point wxPoint coord_zoom = event.GetPosition(); if (event.GetWheelRotation() < 0) { // zooms in plot_.Zoom(kZoomFactor, coord_zoom); } else if (0 < event.GetWheelRotation()) { // zooms out plot_.Zoom(1 / kZoomFactor, coord_zoom); } // refreshes window this->Refresh(); } void PlotPane::OnPaint(wxPaintEvent& event) { // gets a device context wxPaintDC dc(this); // renders RenderPlot(dc); } void PlotPane::RenderPlot(wxDC& dc) { plot_.Render(dc, GetClientRect()); } void PlotPane::UpdatePlot() { // gets the results SpanAnalyzerView* view = (SpanAnalyzerView*)view_; const SagTensionAnalysisResultSet& results = view->results(); if (results.descriptions_weathercase.empty() == true) { wxClientDC dc(this); ClearPlot(dc); return; } // gets the result set based on the current display condition const std::list<SagTensionAnalysisResult>* result_list = nullptr; if (view->condition() == CableConditionType::kInitial) { result_list = &results.results_initial; } else if (view->condition() == CableConditionType::kLoad) { result_list = &results.results_load; } else { wxClientDC dc(this); ClearPlot(dc); return; } // gets the result from the list const int index_weathercase = view->index_weathercase(); const SagTensionAnalysisResult& result = *(std::next(result_list->cbegin(), index_weathercase)); // creates a catenary with the result parameters Catenary3d catenary; catenary.set_spacing_endpoints(results.span->spacing_catenary); catenary.set_tension_horizontal(result.tension_horizontal); catenary.set_weight_unit(result.weight_unit); // calculates points std::list<Point3d> points; const int i_max = 100; for (int i = 0; i <= i_max; i++) { double pos = double(i) / double(i_max); Point3d p = catenary.Coordinate(pos); points.push_back(p); } // converts points to lines std::list<Line2d> lines; for (auto iter = points.cbegin(); iter != std::prev(points.cend(), 1); iter++) { // gets current and next point in the list const Point3d p0 = *iter; const Point3d p1 = *(std::next(iter, 1)); // creates a line and maps 3d catenary points to 2d points for drawing Line2d line; line.p0.x = p0.x; line.p0.y = p0.z; line.p1.x = p1.x; line.p1.y = p1.z; lines.push_back(line); } dataset_catenary_.set_data(lines); // creates renderer LineRenderer2d renderer; renderer.set_dataset(&dataset_catenary_); renderer.set_pen(wxCYAN_PEN); // adds renderer 2D plot plot_.AddRenderer(renderer); } <commit_msg>PlotPane crash fix.<commit_after>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "plot_pane.h" #include "models/transmissionline/catenary.h" #include "line_renderer_2d.h" #include "span_analyzer_view.h" BEGIN_EVENT_TABLE(PlotPane, wxPanel) EVT_LEFT_DOWN(PlotPane::OnMouse) EVT_LEFT_UP(PlotPane::OnMouse) EVT_MOTION(PlotPane::OnMouse) EVT_MOUSEWHEEL(PlotPane::OnMouseWheel) EVT_PAINT(PlotPane::OnPaint) END_EVENT_TABLE() PlotPane::PlotPane(wxWindow* parent, wxView* view) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL) { view_ = view; plot_.set_background(*wxBLACK_BRUSH); plot_.set_is_fitted(true); plot_.set_ratio_aspect(10); } PlotPane::~PlotPane() { } void PlotPane::Update(wxObject* hint) { wxClientDC dc(this); // interprets hint ViewUpdateHint* hint_update = (ViewUpdateHint*)hint; if (hint_update == nullptr) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelAnalysisWeathercaseEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelPreferencesEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelSpansEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelWeathercaseEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewConditionChange) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewWeathercaseChange) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewWeathercasesSetChange) { UpdatePlot(); RenderPlot(dc); } } void PlotPane::ClearPlot(wxDC& dc) { dc.Clear(); } void PlotPane::OnMouse(wxMouseEvent& event) { if (event.LeftDown() == true) { // caches the mouse coordinates coord_mouse_.x = event.GetX(); coord_mouse_.y = event.GetY(); } else if (event.LeftUp() == true) { coord_mouse_.x = -999999; coord_mouse_.y = -999999; } else if (event.Dragging() == true) { // checks if left button is pressed if (event.LeftIsDown() == false) { return; } // disables plot fitting if active if (plot_.is_fitted() == true) { plot_.set_is_fitted(false); } // gets updated mouse point from event wxPoint coord_new; coord_new.x = event.GetX(); coord_new.y = event.GetY(); // finds difference between cached and new mouse points // applies inversion to make plot track mouse position const double kShiftX = (coord_new.x - coord_mouse_.x) * -1; const double kShiftY = (coord_new.y - coord_mouse_.y); plot_.Shift(kShiftX, kShiftY); // updates cached mouse point coord_mouse_ = coord_new; // refreshes window this->Refresh(); } } void PlotPane::OnMouseWheel(wxMouseEvent& event) { // zoom factor const double kZoomFactor = 1.2; // zoom point wxPoint coord_zoom = event.GetPosition(); if (event.GetWheelRotation() < 0) { // zooms in plot_.Zoom(kZoomFactor, coord_zoom); } else if (0 < event.GetWheelRotation()) { // zooms out plot_.Zoom(1 / kZoomFactor, coord_zoom); } // refreshes window this->Refresh(); } void PlotPane::OnPaint(wxPaintEvent& event) { // gets a device context wxPaintDC dc(this); // renders RenderPlot(dc); } void PlotPane::RenderPlot(wxDC& dc) { plot_.Render(dc, GetClientRect()); } void PlotPane::UpdatePlot() { // gets the results SpanAnalyzerView* view = (SpanAnalyzerView*)view_; const SagTensionAnalysisResultSet& results = view->results(); if (results.descriptions_weathercase.empty() == true) { wxClientDC dc(this); ClearPlot(dc); return; } // gets the result set based on the current display condition const std::list<SagTensionAnalysisResult>* result_list = nullptr; if (view->condition() == CableConditionType::kInitial) { result_list = &results.results_initial; } else if (view->condition() == CableConditionType::kLoad) { result_list = &results.results_load; } else { wxClientDC dc(this); ClearPlot(dc); return; } // gets the result from the list const int index_weathercase = view->index_weathercase(); if (index_weathercase < 0) { plot_.ClearRenderers(); return; } const SagTensionAnalysisResult& result = *(std::next(result_list->cbegin(), index_weathercase)); // creates a catenary with the result parameters Catenary3d catenary; catenary.set_spacing_endpoints(results.span->spacing_catenary); catenary.set_tension_horizontal(result.tension_horizontal); catenary.set_weight_unit(result.weight_unit); // calculates points std::list<Point3d> points; const int i_max = 100; for (int i = 0; i <= i_max; i++) { double pos = double(i) / double(i_max); Point3d p = catenary.Coordinate(pos); points.push_back(p); } // converts points to lines std::list<Line2d> lines; for (auto iter = points.cbegin(); iter != std::prev(points.cend(), 1); iter++) { // gets current and next point in the list const Point3d p0 = *iter; const Point3d p1 = *(std::next(iter, 1)); // creates a line and maps 3d catenary points to 2d points for drawing Line2d line; line.p0.x = p0.x; line.p0.y = p0.z; line.p1.x = p1.x; line.p1.y = p1.z; lines.push_back(line); } dataset_catenary_.set_data(lines); // creates renderer LineRenderer2d renderer; renderer.set_dataset(&dataset_catenary_); renderer.set_pen(wxCYAN_PEN); // adds renderer 2D plot plot_.AddRenderer(renderer); } <|endoftext|>
<commit_before>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "plot_pane.h" #include "models/transmissionline/catenary.h" #include "line_renderer_2d.h" #include "span_analyzer_view.h" /// \par OVERVIEW /// /// This is the enumeration for the context menu. enum { kFitPlotData = 0, }; BEGIN_EVENT_TABLE(PlotPane, wxPanel) EVT_LEFT_DOWN(PlotPane::OnMouse) EVT_LEFT_UP(PlotPane::OnMouse) EVT_RIGHT_DOWN(PlotPane::OnMouse) EVT_MENU(wxID_ANY, PlotPane::OnContextMenuSelect) EVT_MOTION(PlotPane::OnMouse) EVT_MOUSEWHEEL(PlotPane::OnMouseWheel) EVT_PAINT(PlotPane::OnPaint) END_EVENT_TABLE() PlotPane::PlotPane(wxWindow* parent, wxView* view) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL) { view_ = view; plot_.set_background(*wxBLACK_BRUSH); plot_.set_is_fitted(true); plot_.set_ratio_aspect(10); } PlotPane::~PlotPane() { } void PlotPane::Update(wxObject* hint) { wxClientDC dc(this); // interprets hint ViewUpdateHint* hint_update = (ViewUpdateHint*)hint; if (hint_update == nullptr) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelAnalysisWeathercaseEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelPreferencesEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelSpansEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelWeathercaseEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewConditionChange) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewWeathercaseChange) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewWeathercasesSetChange) { UpdatePlot(); RenderPlot(dc); } } void PlotPane::ClearPlot(wxDC& dc) { dc.Clear(); } void PlotPane::OnContextMenuSelect(wxCommandEvent& event) { // gets context menu selection and sends to handler function const int id_event = event.GetId(); if (id_event == kFitPlotData) { // toggles plot fit if (plot_.is_fitted() == true) { plot_.set_is_fitted(false); } else { plot_.set_is_fitted(true); this->Refresh(); } } } void PlotPane::OnMouse(wxMouseEvent& event) { if (event.LeftDown() == true) { // caches the mouse coordinates coord_mouse_.x = event.GetX(); coord_mouse_.y = event.GetY(); } else if (event.LeftUp() == true) { coord_mouse_.x = -999999; coord_mouse_.y = -999999; } else if (event.RightDown() == true) { // builds a context menu wxMenu menu; menu.AppendCheckItem(kFitPlotData, "Fit Plot"); menu.Check(kFitPlotData, plot_.is_fitted()); // shows context menu // the event is caught by the pane PopupMenu(&menu, event.GetPosition()); // stops processing event (needed to allow pop-up menu to catch its event) event.Skip(); } else if (event.Dragging() == true) { // checks if left button is pressed if (event.LeftIsDown() == false) { return; } // disables plot fitting if active if (plot_.is_fitted() == true) { plot_.set_is_fitted(false); } // gets updated mouse point from event wxPoint coord_new; coord_new.x = event.GetX(); coord_new.y = event.GetY(); // finds difference between cached and new mouse points // applies inversion to make plot track mouse position const double kShiftX = (coord_new.x - coord_mouse_.x) * -1; const double kShiftY = (coord_new.y - coord_mouse_.y); plot_.Shift(kShiftX, kShiftY); // updates cached mouse point coord_mouse_ = coord_new; // refreshes window this->Refresh(); } } void PlotPane::OnMouseWheel(wxMouseEvent& event) { // zoom factor const double kZoomFactor = 1.2; // zoom point wxPoint coord_zoom = event.GetPosition(); if (event.GetWheelRotation() < 0) { // zooms in plot_.Zoom(kZoomFactor, coord_zoom); } else if (0 < event.GetWheelRotation()) { // zooms out plot_.Zoom(1 / kZoomFactor, coord_zoom); } // refreshes window this->Refresh(); } void PlotPane::OnPaint(wxPaintEvent& event) { // gets a device context wxPaintDC dc(this); // renders RenderPlot(dc); } void PlotPane::RenderPlot(wxDC& dc) { plot_.Render(dc, GetClientRect()); } void PlotPane::UpdatePlot() { // gets the results SpanAnalyzerView* view = (SpanAnalyzerView*)view_; const SagTensionAnalysisResultSet& results = view->results(); if (results.descriptions_weathercase.empty() == true) { wxClientDC dc(this); ClearPlot(dc); return; } // gets the result set based on the current display condition const std::list<SagTensionAnalysisResult>* result_list = nullptr; if (view->condition() == CableConditionType::kInitial) { result_list = &results.results_initial; } else if (view->condition() == CableConditionType::kLoad) { result_list = &results.results_load; } else { wxClientDC dc(this); ClearPlot(dc); return; } // gets the result from the list const int index_weathercase = view->index_weathercase(); if (index_weathercase < 0) { plot_.ClearRenderers(); return; } const SagTensionAnalysisResult& result = *(std::next(result_list->cbegin(), index_weathercase)); // creates a catenary with the result parameters Catenary3d catenary; catenary.set_spacing_endpoints(results.span->spacing_catenary); catenary.set_tension_horizontal(result.tension_horizontal); catenary.set_weight_unit(result.weight_unit); // calculates points std::list<Point3d> points; const int i_max = 100; for (int i = 0; i <= i_max; i++) { double pos = double(i) / double(i_max); Point3d p = catenary.Coordinate(pos); points.push_back(p); } // converts points to lines std::list<Line2d> lines; for (auto iter = points.cbegin(); iter != std::prev(points.cend(), 1); iter++) { // gets current and next point in the list const Point3d p0 = *iter; const Point3d p1 = *(std::next(iter, 1)); // creates a line and maps 3d catenary points to 2d points for drawing Line2d line; line.p0.x = p0.x; line.p0.y = p0.z; line.p1.x = p1.x; line.p1.y = p1.z; lines.push_back(line); } dataset_catenary_.set_data(lines); // creates renderer LineRenderer2d renderer; renderer.set_dataset(&dataset_catenary_); renderer.set_pen(wxCYAN_PEN); // adds renderer 2D plot plot_.AddRenderer(renderer); } <commit_msg>Fixed a bug where the panel didn't get the focus for catching events.<commit_after>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "plot_pane.h" #include "models/transmissionline/catenary.h" #include "line_renderer_2d.h" #include "span_analyzer_view.h" /// \par OVERVIEW /// /// This is the enumeration for the context menu. enum { kFitPlotData = 0, }; BEGIN_EVENT_TABLE(PlotPane, wxPanel) EVT_LEFT_DOWN(PlotPane::OnMouse) EVT_LEFT_UP(PlotPane::OnMouse) EVT_ENTER_WINDOW(PlotPane::OnMouse) EVT_RIGHT_DOWN(PlotPane::OnMouse) EVT_MENU(wxID_ANY, PlotPane::OnContextMenuSelect) EVT_MOTION(PlotPane::OnMouse) EVT_MOUSEWHEEL(PlotPane::OnMouseWheel) EVT_PAINT(PlotPane::OnPaint) END_EVENT_TABLE() PlotPane::PlotPane(wxWindow* parent, wxView* view) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL) { view_ = view; plot_.set_background(*wxBLACK_BRUSH); plot_.set_is_fitted(true); plot_.set_ratio_aspect(10); } PlotPane::~PlotPane() { } void PlotPane::Update(wxObject* hint) { wxClientDC dc(this); // interprets hint ViewUpdateHint* hint_update = (ViewUpdateHint*)hint; if (hint_update == nullptr) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelAnalysisWeathercaseEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelPreferencesEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelSpansEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kModelWeathercaseEdit) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewConditionChange) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewWeathercaseChange) { UpdatePlot(); RenderPlot(dc); } else if (hint_update->type() == ViewUpdateHint::HintType::kViewWeathercasesSetChange) { UpdatePlot(); RenderPlot(dc); } } void PlotPane::ClearPlot(wxDC& dc) { dc.Clear(); } void PlotPane::OnContextMenuSelect(wxCommandEvent& event) { // gets context menu selection and sends to handler function const int id_event = event.GetId(); if (id_event == kFitPlotData) { // toggles plot fit if (plot_.is_fitted() == true) { plot_.set_is_fitted(false); } else { plot_.set_is_fitted(true); this->Refresh(); } } } void PlotPane::OnMouse(wxMouseEvent& event) { if (event.Dragging() == true) { // checks if left button is pressed if (event.LeftIsDown() == false) { return; } // disables plot fitting if active if (plot_.is_fitted() == true) { plot_.set_is_fitted(false); } // gets updated mouse point from event wxPoint coord_new; coord_new.x = event.GetX(); coord_new.y = event.GetY(); // finds difference between cached and new mouse points // applies inversion to make plot track mouse position const double kShiftX = (coord_new.x - coord_mouse_.x) * -1; const double kShiftY = (coord_new.y - coord_mouse_.y); plot_.Shift(kShiftX, kShiftY); // updates cached mouse point coord_mouse_ = coord_new; // refreshes window this->Refresh(); } else if (event.Entering() == true) { // forces the pane to get focus, which helps catch mouse events this->SetFocus(); } else if (event.LeftDown() == true) { // caches the mouse coordinates coord_mouse_.x = event.GetX(); coord_mouse_.y = event.GetY(); } else if (event.LeftUp() == true) { coord_mouse_.x = -999999; coord_mouse_.y = -999999; } else if (event.RightDown() == true) { // builds a context menu wxMenu menu; menu.AppendCheckItem(kFitPlotData, "Fit Plot"); menu.Check(kFitPlotData, plot_.is_fitted()); // shows context menu // the event is caught by the pane PopupMenu(&menu, event.GetPosition()); // stops processing event (needed to allow pop-up menu to catch its event) event.Skip(); } } void PlotPane::OnMouseWheel(wxMouseEvent& event) { // zoom factor const double kZoomFactor = 1.2; // zoom point wxPoint coord_zoom = event.GetPosition(); if (event.GetWheelRotation() < 0) { // zooms in plot_.Zoom(kZoomFactor, coord_zoom); } else if (0 < event.GetWheelRotation()) { // zooms out plot_.Zoom(1 / kZoomFactor, coord_zoom); } // refreshes window this->Refresh(); } void PlotPane::OnPaint(wxPaintEvent& event) { // gets a device context wxPaintDC dc(this); // renders RenderPlot(dc); } void PlotPane::RenderPlot(wxDC& dc) { plot_.Render(dc, GetClientRect()); } void PlotPane::UpdatePlot() { // gets the results SpanAnalyzerView* view = (SpanAnalyzerView*)view_; const SagTensionAnalysisResultSet& results = view->results(); if (results.descriptions_weathercase.empty() == true) { wxClientDC dc(this); ClearPlot(dc); return; } // gets the result set based on the current display condition const std::list<SagTensionAnalysisResult>* result_list = nullptr; if (view->condition() == CableConditionType::kInitial) { result_list = &results.results_initial; } else if (view->condition() == CableConditionType::kLoad) { result_list = &results.results_load; } else { wxClientDC dc(this); ClearPlot(dc); return; } // gets the result from the list const int index_weathercase = view->index_weathercase(); if (index_weathercase < 0) { plot_.ClearRenderers(); return; } const SagTensionAnalysisResult& result = *(std::next(result_list->cbegin(), index_weathercase)); // creates a catenary with the result parameters Catenary3d catenary; catenary.set_spacing_endpoints(results.span->spacing_catenary); catenary.set_tension_horizontal(result.tension_horizontal); catenary.set_weight_unit(result.weight_unit); // calculates points std::list<Point3d> points; const int i_max = 100; for (int i = 0; i <= i_max; i++) { double pos = double(i) / double(i_max); Point3d p = catenary.Coordinate(pos); points.push_back(p); } // converts points to lines std::list<Line2d> lines; for (auto iter = points.cbegin(); iter != std::prev(points.cend(), 1); iter++) { // gets current and next point in the list const Point3d p0 = *iter; const Point3d p1 = *(std::next(iter, 1)); // creates a line and maps 3d catenary points to 2d points for drawing Line2d line; line.p0.x = p0.x; line.p0.y = p0.z; line.p1.x = p1.x; line.p1.y = p1.z; lines.push_back(line); } dataset_catenary_.set_data(lines); // creates renderer LineRenderer2d renderer; renderer.set_dataset(&dataset_catenary_); renderer.set_pen(wxCYAN_PEN); // adds renderer 2D plot plot_.AddRenderer(renderer); } <|endoftext|>
<commit_before>#include <QCoreApplication> #include <QDebug> #include "batteryInfo.h" #include <contextproperty.h> BatteryInfo::BatteryInfo(QObject * parent): QObject(parent), level(-1), state(Unknown), batteryLevel(new ContextProperty("Battery.ChargePercentage", this)), batteryState(new ContextProperty("Battery.State", this)) { batteryLevel->waitForSubscription(true); batteryState->waitForSubscription(true); level = getLevel(); state = getState(); connect(batteryLevel, SIGNAL(valueChanged()), this, SLOT(onPropertyChanged())); connect(batteryState, SIGNAL(valueChanged()), this, SLOT(onPropertyChanged())); } BatteryInfo::~BatteryInfo() { delete batteryLevel; delete batteryState; } void BatteryInfo::onPropertyChanged() { level = getLevel(); state = getState(); qDebug() << "level: " << level << " state: " << state; } int BatteryInfo::getLevel() const { return batteryLevel->value().toInt(); } BatteryInfo::State BatteryInfo::getState() const { QString res(batteryState->value().toString().trimmed()); if (res == "charging") { return Charging; } else if (res == "discharging") { return Discharging; } else if (res == "full") { return Full; } else { return Unknown; } } <commit_msg>fixed stupid pointer<commit_after>#include <QCoreApplication> #include <QDebug> #include "batteryInfo.h" #include <contextproperty.h> BatteryInfo::BatteryInfo(QObject * parent): QObject(parent), level(-1), state(Unknown), batteryLevel(new ContextProperty("Battery.ChargePercentage", this)), batteryState(new ContextProperty("Battery.State", this)) { batteryLevel->waitForSubscription(true); batteryState->waitForSubscription(true); level = getLevel(); state = getState(); connect(batteryLevel, SIGNAL(valueChanged()), this, SLOT(onPropertyChanged())); connect(batteryState, SIGNAL(valueChanged()), this, SLOT(onPropertyChanged())); } BatteryInfo::~BatteryInfo() { batteryState->unsubscribe(); batteryLevel->unsubscribe(); delete batteryLevel; delete batteryState; } void BatteryInfo::onPropertyChanged() { level = getLevel(); state = getState(); qDebug() << "level: " << level << " state: " << state; } int BatteryInfo::getLevel() const { return batteryLevel->value().toInt(); } BatteryInfo::State BatteryInfo::getState() const { QString res(batteryState->value().toString().trimmed()); if (res == "charging") { return Charging; } else if (res == "discharging") { return Discharging; } else if (res == "full") { return Full; } else { return Unknown; } } <|endoftext|>
<commit_before>/* This file is part of the Akonadi Mail example. Copyright (c) 2009 Stephen Kelly <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "emaillineedit.h" #include <QCompleter> #include <QDirModel> #include <QTreeView> #include <akonadi/monitor.h> #include <akonadi/session.h> #include <akonadi/entitydisplayattribute.h> #include <akonadi/itemfetchscope.h> #include "entityupdateadapter.h" #include "descendantentitiesproxymodel.h" #include "entityfilterproxymodel.h" #include "contactsmodel.h" #include <kdebug.h> using namespace Akonadi; EmailLineEdit::EmailLineEdit(Akonadi::Session *session, QWidget *parent) : QLineEdit(parent) // : KComboBox(parent) { // this->setEditable(true); ItemFetchScope scope; scope.fetchFullPayload( true ); // Need to have full item when adding it to the internal data structure // scope.fetchAttribute< CollectionChildOrderAttribute >(); scope.fetchAttribute< EntityDisplayAttribute >(); Monitor *monitor = new Monitor( this ); monitor->fetchCollection( true ); monitor->setItemFetchScope( scope ); monitor->setCollectionMonitored( Collection::root() ); monitor->setMimeTypeMonitored( "text/directory" ); ContactsModel *contactsModel = new ContactsModel( session, monitor, this); DescendantEntitiesProxyModel *descProxy = new DescendantEntitiesProxyModel(this); descProxy->setSourceModel(contactsModel); EntityFilterProxyModel *filterProxy = new EntityFilterProxyModel(this); filterProxy->setSourceModel(descProxy); filterProxy->addMimeTypeExclusionFilter( Collection::mimeType() ); QCompleter *completer = new QCompleter(filterProxy, this); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setCompletionColumn(2); // completer->setCompletionRole(ContactsModel::EmailCompletionRole); this->setCompleter(completer); // this->setModel(filterProxy); } <commit_msg>#included a file which doesn't exist anywhere, and hence wouldn't compile. Tried the obvious (commented the line out) and it now compiles - hope it's a reasonable thing to do.<commit_after>/* This file is part of the Akonadi Mail example. Copyright (c) 2009 Stephen Kelly <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "emaillineedit.h" #include <QCompleter> #include <QDirModel> #include <QTreeView> #include <akonadi/monitor.h> #include <akonadi/session.h> #include <akonadi/entitydisplayattribute.h> #include <akonadi/itemfetchscope.h> //#include "entityupdateadapter.h" #include "descendantentitiesproxymodel.h" #include "entityfilterproxymodel.h" #include "contactsmodel.h" #include <kdebug.h> using namespace Akonadi; EmailLineEdit::EmailLineEdit(Akonadi::Session *session, QWidget *parent) : QLineEdit(parent) // : KComboBox(parent) { // this->setEditable(true); ItemFetchScope scope; scope.fetchFullPayload( true ); // Need to have full item when adding it to the internal data structure // scope.fetchAttribute< CollectionChildOrderAttribute >(); scope.fetchAttribute< EntityDisplayAttribute >(); Monitor *monitor = new Monitor( this ); monitor->fetchCollection( true ); monitor->setItemFetchScope( scope ); monitor->setCollectionMonitored( Collection::root() ); monitor->setMimeTypeMonitored( "text/directory" ); ContactsModel *contactsModel = new ContactsModel( session, monitor, this); DescendantEntitiesProxyModel *descProxy = new DescendantEntitiesProxyModel(this); descProxy->setSourceModel(contactsModel); EntityFilterProxyModel *filterProxy = new EntityFilterProxyModel(this); filterProxy->setSourceModel(descProxy); filterProxy->addMimeTypeExclusionFilter( Collection::mimeType() ); QCompleter *completer = new QCompleter(filterProxy, this); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setCompletionColumn(2); // completer->setCompletionRole(ContactsModel::EmailCompletionRole); this->setCompleter(completer); // this->setModel(filterProxy); } <|endoftext|>
<commit_before>// // rbtree.cpp // rbtree // // Created by Sunil on 3/22/17. // Copyright © 2017 Sunil. All rights reserved. // #include "rbtree.hpp" #include <tuple> #include <stack> #include <list> #include <iostream> using namespace std; rbnode* rbtree::search(rbnode node, int key) { return nullptr; } rbtree::rbtree() { } rbtree::~rbtree() { remove_all(root); } void rbtree::remove_all(rbnode* node) { if (!node) { // no node to delete return; } if (node->left) remove_all(node->left); if (node->right) remove_all(node->right); delete node; } void rbtree::remove(int key) { // TODO: after removing the node, rebalance the tree. } bool rbtree::violates(bool constraint) { // just negate the constraint and return return !constraint; } void rbtree::insert(int key) { } bool rbtree::has_only_red_black_nodes(rbnode* node) { if (!node) { // no nodes, no color. return false; } // use any tree traversal and check the color // everynode has to be red or black. if (!node->is_red_node() && !node->is_black_node()) { // this node is neither red nor black. It's a invalid rb tree. return false; } // node has red/black color but doesn't have left or right subtree. if (!node->left && !node->right) { return true; } // only right subtree is available. if (!node->left && node->right) { return has_only_red_black_nodes(node->right); } // only left subtree is available. if (!node->right && node->left) { return has_only_red_black_nodes(node->left); } // Both left "and" right subtree should have only red/black nodes. return ( has_only_red_black_nodes(node->left) && has_only_red_black_nodes(node->right) ); } bool rbtree::rednode_has_black_children(rbnode* parent) { if (!parent) { // no node, no children. Nothing to check return false; } // if node is red, then check it's children if (parent->is_red_node()) { // if left and right children are null treat them as black. if (!parent->left && !parent->right) { return true; } // both left and right are available. if ((parent->left && parent->left->is_red_node()) || (parent->right && parent->right->is_red_node())) { return false; } // left child is not null. make sure its color is black if (parent->left && parent->left->is_red_node()) { // left child is not black. return false; } // right child is not null. make sure its color is black if (parent->right && parent->right->is_red_node()) { // right child is not black. return false; } } // only right subtree is available. if (!parent->left && parent->right) { return has_only_red_black_nodes(parent->right); } // only left subtree is available. if (!parent->right && parent->left) { return has_only_red_black_nodes(parent->left); } // Both left "and" right subtree return ( has_only_red_black_nodes(parent->left) && has_only_red_black_nodes(parent->right) ); } bool rbtree::has_equal_black_nodes_all_path(rbnode* parent) { // do a depth first search traversal and count the black nodes // along all path from root to leaf node. if (!parent) { // no nodes. return true or false ? return true; } // stack of tuple of (node, count of black nodes) pair. stack<tuple<rbnode*, int>> stk; list<int> paths; auto count_if_black = [](rbnode* node) { return (node->is_black_node() ? 1 : 0); }; stk.push(make_tuple(parent, count_if_black(parent))); while (!stk.empty()) { auto pair = stk.top(); stk.pop(); auto node = std::get<0>(pair); auto count = std::get<1>(pair); if (node->left) { auto left = node->left; stk.push(make_tuple(left, count + count_if_black(left))); } else { // left child is null. count it as a black node. paths.push_front(count + 1); } if (node->right) { auto right = node->right; stk.push(make_tuple(right, count + count_if_black(right))); } else { // right child is null. count it as a black node. paths.push_front(count + 1); } } // now check if black node count on all paths are same. auto first = paths.front(); #if DEBUG for (auto count : paths) cout << count << "|"; cout << endl; #endif for (auto count : paths) { if (count != first) return false; } return true; } bool rbtree::is_valid_rbtree() { // rb tree properties: // P.1: every node is red/black. // P.2: root is always black. // P.3: leaf nodes are black. // P.4: red node should have only black children. // P.5: for any node x, # of black nodes along all // paths from x to leaf nodes should be the same. if (!root) { // no nodes in the tree, is a valid RB tree return true; } // P.1: check if all nodes are red/ black. if (violates(has_only_red_black_nodes(root))) { // some nodes are of different color. It's not a red black tree return false; } // P.2: If root is not black then it's invalid. if (violates(root->is_black_node())) return false; // P.3: I take all null nodes to be black. // I treat all null nodes as black. So I don't have to // check for black null nodes. // P.4: all red nodes should have black children. if (violates(rednode_has_black_children(root))) { // some/all of red nodes doesn't have a black children return false; } // P.5: check #black nodes along all possible path from root // to leaf nodes. if (violates(has_equal_black_nodes_all_path(root))) { // unequal number of black nodes. return false; } return true; } rbnode* rbtree::search(int key) { return nullptr; } void rbtree::prune(int min, int max) { throw new runtime_error("not implemented"); } void rbtree::bfs() { throw new runtime_error("not implemented"); } void rbtree::dfs() { throw new runtime_error("not implemented"); } <commit_msg>implemented bfs and dfs<commit_after>// // rbtree.cpp // rbtree // // Created by Sunil on 3/22/17. // Copyright © 2017 Sunil. All rights reserved. // #include "rbtree.hpp" #include <list> #include <tuple> #include <stack> #include <queue> #include <iostream> using namespace std; rbnode* rbtree::search(rbnode node, int key) { return nullptr; } rbtree::rbtree() { } rbtree::~rbtree() { remove_all(root); } void rbtree::remove_all(rbnode* node) { if (!node) { // no node to delete return; } if (node->left) remove_all(node->left); if (node->right) remove_all(node->right); delete node; } void rbtree::remove(int key) { // TODO: after removing the node, rebalance the tree. } bool rbtree::violates(bool constraint) { // just negate the constraint and return return !constraint; } void rbtree::insert(int key) { } bool rbtree::has_only_red_black_nodes(rbnode* node) { if (!node) { // no nodes, no color. return false; } // use any tree traversal and check the color // everynode has to be red or black. if (!node->is_red_node() && !node->is_black_node()) { // this node is neither red nor black. It's a invalid rb tree. return false; } // node has red/black color but doesn't have left or right subtree. if (!node->left && !node->right) { return true; } // only right subtree is available. if (!node->left && node->right) { return has_only_red_black_nodes(node->right); } // only left subtree is available. if (!node->right && node->left) { return has_only_red_black_nodes(node->left); } // Both left "and" right subtree should have only red/black nodes. return ( has_only_red_black_nodes(node->left) && has_only_red_black_nodes(node->right) ); } bool rbtree::rednode_has_black_children(rbnode* parent) { if (!parent) { // no node, no children. Nothing to check return false; } // if node is red, then check it's children if (parent->is_red_node()) { // if left and right children are null treat them as black. if (!parent->left && !parent->right) { return true; } // both left and right are available. if ((parent->left && parent->left->is_red_node()) || (parent->right && parent->right->is_red_node())) { return false; } // left child is not null. make sure its color is black if (parent->left && parent->left->is_red_node()) { // left child is not black. return false; } // right child is not null. make sure its color is black if (parent->right && parent->right->is_red_node()) { // right child is not black. return false; } } // only right subtree is available. if (!parent->left && parent->right) { return has_only_red_black_nodes(parent->right); } // only left subtree is available. if (!parent->right && parent->left) { return has_only_red_black_nodes(parent->left); } // Both left "and" right subtree return ( has_only_red_black_nodes(parent->left) && has_only_red_black_nodes(parent->right) ); } bool rbtree::has_equal_black_nodes_all_path(rbnode* parent) { // do a depth first search traversal and count the black nodes // along all path from root to leaf node. if (!parent) { // no nodes. return true or false ? return true; } // stack of tuple of (node, count of black nodes) pair. stack<tuple<rbnode*, int>> stk; list<int> paths; auto count_if_black = [](rbnode* node) { return (node->is_black_node() ? 1 : 0); }; stk.push(make_tuple(parent, count_if_black(parent))); while (!stk.empty()) { auto pair = stk.top(); stk.pop(); auto node = std::get<0>(pair); auto count = std::get<1>(pair); if (node->right) { auto right = node->right; stk.push(make_tuple(right, count + count_if_black(right))); } else { // right child is null. count it as a black node. paths.push_front(count + 1); } if (node->left) { auto left = node->left; stk.push(make_tuple(left, count + count_if_black(left))); } else { // left child is null. count it as a black node. paths.push_front(count + 1); } } // now check if black node count on all paths are same. auto first = paths.front(); #if DEBUG for (auto count : paths) cout << count << "|"; cout << endl; #endif for (auto count : paths) { if (count != first) return false; } return true; } bool rbtree::is_valid_rbtree() { // rb tree properties: // P.1: every node is red/black. // P.2: root is always black. // P.3: leaf nodes are black. // P.4: red node should have only black children. // P.5: for any node x, # of black nodes along all // paths from x to leaf nodes should be the same. if (!root) { // no nodes in the tree, is a valid RB tree return true; } // P.1: check if all nodes are red/ black. if (violates(has_only_red_black_nodes(root))) { // some nodes are of different color. It's not a red black tree return false; } // P.2: If root is not black then it's invalid. if (violates(root->is_black_node())) return false; // P.3: I take all null nodes to be black. // I treat all null nodes as black. So I don't have to // check for black null nodes. // P.4: all red nodes should have black children. if (violates(rednode_has_black_children(root))) { // some/all of red nodes doesn't have a black children return false; } // P.5: check #black nodes along all possible path from root // to leaf nodes. if (violates(has_equal_black_nodes_all_path(root))) { // unequal number of black nodes. return false; } return true; } rbnode* rbtree::search(int key) { return nullptr; } void rbtree::prune(int min, int max) { throw new runtime_error("not implemented"); } void rbtree::bfs() { // breadth first search traversal. if (!root) { cout << "rb tree is empty" << endl; return; } cout << "----- BFS ------" << endl; deque<rbnode*> queue; queue.push_back(root); while(!queue.empty()) { auto node = queue.front(); queue.pop_front(); cout << node->key << endl; if (node->left) { queue.push_back(node->left); } if (node->right) { queue.push_back(node->right); } } } void rbtree::dfs() { // depth first search traversal. if (!root) { cout << "rb tree is empty!" << endl; return; } cout << "----- DFS ------" << endl; stack<rbnode*> stk; stk.push(root); while (!stk.empty()) { auto node = stk.top(); stk.pop(); cout << node->key << endl; if (node->right) { auto right = node->right; stk.push(right); } if (node->left) { auto left = node->left; stk.push(left); } } } <|endoftext|>
<commit_before>/* Q Light Controller rgbmatrix_test.cpp Copyright (C) Heikki Junnila 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.txt 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 <QtTest> #include <QtXml> #define private public #include "rgbmatrix_test.h" #include "qlcfixturemode.h" #include "qlcfixturedef.h" #include "fixturegroup.h" #include "mastertimer.h" #include "rgbscript.h" #include "rgbscriptscache.h" #include "rgbmatrix.h" #include "fixture.h" #include "qlcfile.h" #include "doc.h" #undef private #include "../common/resource_paths.h" void RGBMatrix_Test::initTestCase() { m_doc = new Doc(this); QDir fxiDir(INTERNAL_FIXTUREDIR); fxiDir.setFilter(QDir::Files); fxiDir.setNameFilters(QStringList() << QString("*%1").arg(KExtFixture)); QVERIFY(m_doc->fixtureDefCache()->load(fxiDir) == true); QLCFixtureDef* def = m_doc->fixtureDefCache()->fixtureDef("Stairville", "LED PAR56"); QVERIFY(def != NULL); QLCFixtureMode* mode = def->modes().first(); QVERIFY(mode != NULL); FixtureGroup* grp = new FixtureGroup(m_doc); grp->setName("Test Group"); grp->setSize(QSize(5, 5)); m_doc->addFixtureGroup(grp); for (int i = 0; i < 25; i++) { Fixture* fxi = new Fixture(m_doc); fxi->setFixtureDefinition(def, mode); m_doc->addFixture(fxi); grp->assignFixture(fxi->id()); } QVERIFY(m_doc->rgbScriptsCache()->load(QDir(INTERNAL_SCRIPTDIR))); QVERIFY(m_doc->rgbScriptsCache()->names().size() != 0); } void RGBMatrix_Test::cleanupTestCase() { delete m_doc; } void RGBMatrix_Test::initial() { RGBMatrix mtx(m_doc); QCOMPARE(mtx.type(), Function::RGBMatrix); QCOMPARE(mtx.fixtureGroup(), FixtureGroup::invalidId()); QCOMPARE(mtx.startColor(), QColor(Qt::red)); QCOMPARE(mtx.endColor(), QColor()); QVERIFY(mtx.m_fader == NULL); QCOMPARE(mtx.m_step, 0); QCOMPARE(mtx.name(), tr("New RGB Matrix")); QCOMPARE(mtx.duration(), uint(500)); QVERIFY(mtx.algorithm() != NULL); QCOMPARE(mtx.algorithm()->name(), QString("Stripes")); } void RGBMatrix_Test::group() { RGBMatrix mtx(m_doc); mtx.setFixtureGroup(0); QCOMPARE(mtx.fixtureGroup(), uint(0)); mtx.setFixtureGroup(15); QCOMPARE(mtx.fixtureGroup(), uint(15)); mtx.setFixtureGroup(FixtureGroup::invalidId()); QCOMPARE(mtx.fixtureGroup(), FixtureGroup::invalidId()); } void RGBMatrix_Test::color() { RGBMatrix mtx(m_doc); mtx.setStartColor(Qt::blue); QCOMPARE(mtx.startColor(), QColor(Qt::blue)); mtx.setStartColor(QColor()); QCOMPARE(mtx.startColor(), QColor()); mtx.setEndColor(Qt::green); QCOMPARE(mtx.endColor(), QColor(Qt::green)); mtx.setEndColor(QColor()); QCOMPARE(mtx.endColor(), QColor()); } void RGBMatrix_Test::copy() { RGBMatrix mtx(m_doc); mtx.setStartColor(Qt::magenta); mtx.setEndColor(Qt::yellow); mtx.setFixtureGroup(0); mtx.setAlgorithm(RGBAlgorithm::algorithm(m_doc, "Stripes")); QVERIFY(mtx.algorithm() != NULL); RGBMatrix* copyMtx = qobject_cast<RGBMatrix*> (mtx.createCopy(m_doc)); QVERIFY(copyMtx != NULL); QCOMPARE(copyMtx->startColor(), QColor(Qt::magenta)); QCOMPARE(copyMtx->endColor(), QColor(Qt::yellow)); QCOMPARE(copyMtx->fixtureGroup(), uint(0)); QVERIFY(copyMtx->algorithm() != NULL); QVERIFY(copyMtx->algorithm() != mtx.algorithm()); // Different object pointer! QCOMPARE(copyMtx->algorithm()->name(), QString("Stripes")); } void RGBMatrix_Test::previewMaps() { RGBMatrix mtx(m_doc); QVERIFY(mtx.algorithm() != NULL); QCOMPARE(mtx.algorithm()->name(), QString("Stripes")); int steps = mtx.stepsCount(); QCOMPARE(steps, 0); RGBMap map = mtx.previewMap(0); QCOMPARE(map.size(), 0); // No fixture group mtx.setFixtureGroup(0); steps = mtx.stepsCount(); QCOMPARE(steps, 5); map = mtx.previewMap(0); QCOMPARE(map.size(), 5); for (int z = 0; z < steps; z++) { map = mtx.previewMap(z); for (int y = 0; y < 5; y++) { for (int x = 0; x < 5; x++) { if (x == z) QCOMPARE(map[y][x], QColor(Qt::black).rgb()); else QCOMPARE(map[y][x], uint(0)); } } } } void RGBMatrix_Test::loadSave() { RGBMatrix* mtx = new RGBMatrix(m_doc); mtx->setStartColor(Qt::magenta); mtx->setEndColor(Qt::blue); mtx->setFixtureGroup(42); mtx->setAlgorithm(RGBAlgorithm::algorithm(m_doc, "Stripes")); QVERIFY(mtx->algorithm() != NULL); QCOMPARE(mtx->algorithm()->name(), QString("Stripes")); mtx->setName("Xyzzy"); mtx->setDirection(Function::Backward); mtx->setRunOrder(Function::PingPong); mtx->setDuration(1200); mtx->setFadeInSpeed(10); mtx->setFadeOutSpeed(20); m_doc->addFunction(mtx); QDomDocument doc; QDomElement root = doc.createElement("Foo"); QVERIFY(mtx->saveXML(&doc, &root) == true); QCOMPARE(root.firstChild().toElement().tagName(), QString("Function")); QCOMPARE(root.firstChild().toElement().attribute("Type"), QString("RGBMatrix")); QCOMPARE(root.firstChild().toElement().attribute("ID"), QString::number(mtx->id())); QCOMPARE(root.firstChild().toElement().attribute("Name"), QString("Xyzzy")); int speed = 0, dir = 0, run = 0, algo = 0, monocolor = 0, endcolor = 0, grp = 0; QDomNode node = root.firstChild().firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == "Speed") { QCOMPARE(tag.attribute("FadeIn"), QString("10")); QCOMPARE(tag.attribute("FadeOut"), QString("20")); QCOMPARE(tag.attribute("Duration"), QString("1200")); speed++; } else if (tag.tagName() == "Direction") { QCOMPARE(tag.text(), QString("Backward")); dir++; } else if (tag.tagName() == "RunOrder") { QCOMPARE(tag.text(), QString("PingPong")); run++; } else if (tag.tagName() == "Algorithm") { // RGBAlgorithms take care of Algorithm tag's contents algo++; } else if (tag.tagName() == "MonoColor") { QCOMPARE(tag.text().toUInt(), QColor(Qt::magenta).rgb()); monocolor++; } else if (tag.tagName() == "EndColor") { QCOMPARE(tag.text().toUInt(), QColor(Qt::blue).rgb()); endcolor++; } else if (tag.tagName() == "FixtureGroup") { QCOMPARE(tag.text(), QString("42")); grp++; } else { QFAIL(QString("Unexpected tag: %1").arg(tag.tagName()).toUtf8().constData()); } node = node.nextSibling(); } QCOMPARE(speed, 1); QCOMPARE(dir, 1); QCOMPARE(run, 1); QCOMPARE(algo, 1); QCOMPARE(monocolor, 1); QCOMPARE(endcolor, 1); QCOMPARE(grp, 1); // Put some extra garbage in QDomNode parent = node.parentNode(); QDomElement foo = doc.createElement("Foo"); root.firstChild().appendChild(foo); RGBMatrix mtx2(m_doc); QVERIFY(mtx2.loadXML(root.firstChild().toElement()) == true); QCOMPARE(mtx2.direction(), Function::Backward); QCOMPARE(mtx2.runOrder(), Function::PingPong); QCOMPARE(mtx2.startColor(), QColor(Qt::magenta)); QCOMPARE(mtx2.endColor(), QColor(Qt::blue)); QCOMPARE(mtx2.fixtureGroup(), uint(42)); QVERIFY(mtx2.algorithm() != NULL); QCOMPARE(mtx2.algorithm()->name(), mtx->algorithm()->name()); QCOMPARE(mtx2.duration(), uint(1200)); QCOMPARE(mtx2.fadeInSpeed(), uint(10)); QCOMPARE(mtx2.fadeOutSpeed(), uint(20)); QVERIFY(mtx2.loadXML(root.toElement()) == false); // Not a function node root.firstChild().toElement().setAttribute("Type", "Scene"); QVERIFY(mtx2.loadXML(root.firstChild().toElement()) == false); // Not an RGBMatrix node } QTEST_MAIN(RGBMatrix_Test) <commit_msg>Tests: fixed RGB Matrix test for DimmerControl<commit_after>/* Q Light Controller rgbmatrix_test.cpp Copyright (C) Heikki Junnila 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.txt 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 <QtTest> #include <QtXml> #define private public #include "rgbmatrix_test.h" #include "qlcfixturemode.h" #include "qlcfixturedef.h" #include "fixturegroup.h" #include "mastertimer.h" #include "rgbscript.h" #include "rgbscriptscache.h" #include "rgbmatrix.h" #include "fixture.h" #include "qlcfile.h" #include "doc.h" #undef private #include "../common/resource_paths.h" void RGBMatrix_Test::initTestCase() { m_doc = new Doc(this); QDir fxiDir(INTERNAL_FIXTUREDIR); fxiDir.setFilter(QDir::Files); fxiDir.setNameFilters(QStringList() << QString("*%1").arg(KExtFixture)); QVERIFY(m_doc->fixtureDefCache()->load(fxiDir) == true); QLCFixtureDef* def = m_doc->fixtureDefCache()->fixtureDef("Stairville", "LED PAR56"); QVERIFY(def != NULL); QLCFixtureMode* mode = def->modes().first(); QVERIFY(mode != NULL); FixtureGroup* grp = new FixtureGroup(m_doc); grp->setName("Test Group"); grp->setSize(QSize(5, 5)); m_doc->addFixtureGroup(grp); for (int i = 0; i < 25; i++) { Fixture* fxi = new Fixture(m_doc); fxi->setFixtureDefinition(def, mode); m_doc->addFixture(fxi); grp->assignFixture(fxi->id()); } QVERIFY(m_doc->rgbScriptsCache()->load(QDir(INTERNAL_SCRIPTDIR))); QVERIFY(m_doc->rgbScriptsCache()->names().size() != 0); } void RGBMatrix_Test::cleanupTestCase() { delete m_doc; } void RGBMatrix_Test::initial() { RGBMatrix mtx(m_doc); QCOMPARE(mtx.type(), Function::RGBMatrix); QCOMPARE(mtx.fixtureGroup(), FixtureGroup::invalidId()); QCOMPARE(mtx.startColor(), QColor(Qt::red)); QCOMPARE(mtx.endColor(), QColor()); QVERIFY(mtx.m_fader == NULL); QCOMPARE(mtx.m_step, 0); QCOMPARE(mtx.name(), tr("New RGB Matrix")); QCOMPARE(mtx.duration(), uint(500)); QVERIFY(mtx.algorithm() != NULL); QCOMPARE(mtx.algorithm()->name(), QString("Stripes")); } void RGBMatrix_Test::group() { RGBMatrix mtx(m_doc); mtx.setFixtureGroup(0); QCOMPARE(mtx.fixtureGroup(), uint(0)); mtx.setFixtureGroup(15); QCOMPARE(mtx.fixtureGroup(), uint(15)); mtx.setFixtureGroup(FixtureGroup::invalidId()); QCOMPARE(mtx.fixtureGroup(), FixtureGroup::invalidId()); } void RGBMatrix_Test::color() { RGBMatrix mtx(m_doc); mtx.setStartColor(Qt::blue); QCOMPARE(mtx.startColor(), QColor(Qt::blue)); mtx.setStartColor(QColor()); QCOMPARE(mtx.startColor(), QColor()); mtx.setEndColor(Qt::green); QCOMPARE(mtx.endColor(), QColor(Qt::green)); mtx.setEndColor(QColor()); QCOMPARE(mtx.endColor(), QColor()); } void RGBMatrix_Test::copy() { RGBMatrix mtx(m_doc); mtx.setStartColor(Qt::magenta); mtx.setEndColor(Qt::yellow); mtx.setFixtureGroup(0); mtx.setAlgorithm(RGBAlgorithm::algorithm(m_doc, "Stripes")); QVERIFY(mtx.algorithm() != NULL); RGBMatrix* copyMtx = qobject_cast<RGBMatrix*> (mtx.createCopy(m_doc)); QVERIFY(copyMtx != NULL); QCOMPARE(copyMtx->startColor(), QColor(Qt::magenta)); QCOMPARE(copyMtx->endColor(), QColor(Qt::yellow)); QCOMPARE(copyMtx->fixtureGroup(), uint(0)); QVERIFY(copyMtx->algorithm() != NULL); QVERIFY(copyMtx->algorithm() != mtx.algorithm()); // Different object pointer! QCOMPARE(copyMtx->algorithm()->name(), QString("Stripes")); } void RGBMatrix_Test::previewMaps() { RGBMatrix mtx(m_doc); QVERIFY(mtx.algorithm() != NULL); QCOMPARE(mtx.algorithm()->name(), QString("Stripes")); int steps = mtx.stepsCount(); QCOMPARE(steps, 0); RGBMap map = mtx.previewMap(0); QCOMPARE(map.size(), 0); // No fixture group mtx.setFixtureGroup(0); steps = mtx.stepsCount(); QCOMPARE(steps, 5); map = mtx.previewMap(0); QCOMPARE(map.size(), 5); for (int z = 0; z < steps; z++) { map = mtx.previewMap(z); for (int y = 0; y < 5; y++) { for (int x = 0; x < 5; x++) { if (x == z) QCOMPARE(map[y][x], QColor(Qt::black).rgb()); else QCOMPARE(map[y][x], uint(0)); } } } } void RGBMatrix_Test::loadSave() { RGBMatrix* mtx = new RGBMatrix(m_doc); mtx->setStartColor(Qt::magenta); mtx->setEndColor(Qt::blue); mtx->setFixtureGroup(42); mtx->setAlgorithm(RGBAlgorithm::algorithm(m_doc, "Stripes")); QVERIFY(mtx->algorithm() != NULL); QCOMPARE(mtx->algorithm()->name(), QString("Stripes")); mtx->setName("Xyzzy"); mtx->setDirection(Function::Backward); mtx->setRunOrder(Function::PingPong); mtx->setDuration(1200); mtx->setFadeInSpeed(10); mtx->setFadeOutSpeed(20); mtx->setDimmerControl(false); m_doc->addFunction(mtx); QDomDocument doc; QDomElement root = doc.createElement("Foo"); QVERIFY(mtx->saveXML(&doc, &root) == true); QCOMPARE(root.firstChild().toElement().tagName(), QString("Function")); QCOMPARE(root.firstChild().toElement().attribute("Type"), QString("RGBMatrix")); QCOMPARE(root.firstChild().toElement().attribute("ID"), QString::number(mtx->id())); QCOMPARE(root.firstChild().toElement().attribute("Name"), QString("Xyzzy")); int speed = 0, dir = 0, run = 0, algo = 0, monocolor = 0, endcolor = 0, grp = 0, dimmer = 0; QDomNode node = root.firstChild().firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == "Speed") { QCOMPARE(tag.attribute("FadeIn"), QString("10")); QCOMPARE(tag.attribute("FadeOut"), QString("20")); QCOMPARE(tag.attribute("Duration"), QString("1200")); speed++; } else if (tag.tagName() == "Direction") { QCOMPARE(tag.text(), QString("Backward")); dir++; } else if (tag.tagName() == "RunOrder") { QCOMPARE(tag.text(), QString("PingPong")); run++; } else if (tag.tagName() == "Algorithm") { // RGBAlgorithms take care of Algorithm tag's contents algo++; } else if (tag.tagName() == "MonoColor") { QCOMPARE(tag.text().toUInt(), QColor(Qt::magenta).rgb()); monocolor++; } else if (tag.tagName() == "EndColor") { QCOMPARE(tag.text().toUInt(), QColor(Qt::blue).rgb()); endcolor++; } else if (tag.tagName() == "FixtureGroup") { QCOMPARE(tag.text(), QString("42")); grp++; } else if (tag.tagName() == "DimmerControl") { QCOMPARE(tag.text(), QString("0")); dimmer++; } else { QFAIL(QString("Unexpected tag: %1").arg(tag.tagName()).toUtf8().constData()); } node = node.nextSibling(); } QCOMPARE(speed, 1); QCOMPARE(dir, 1); QCOMPARE(run, 1); QCOMPARE(algo, 1); QCOMPARE(monocolor, 1); QCOMPARE(endcolor, 1); QCOMPARE(grp, 1); QCOMPARE(dimmer, 1); // Put some extra garbage in QDomNode parent = node.parentNode(); QDomElement foo = doc.createElement("Foo"); root.firstChild().appendChild(foo); RGBMatrix mtx2(m_doc); QVERIFY(mtx2.loadXML(root.firstChild().toElement()) == true); QCOMPARE(mtx2.direction(), Function::Backward); QCOMPARE(mtx2.runOrder(), Function::PingPong); QCOMPARE(mtx2.startColor(), QColor(Qt::magenta)); QCOMPARE(mtx2.endColor(), QColor(Qt::blue)); QCOMPARE(mtx2.fixtureGroup(), uint(42)); QVERIFY(mtx2.algorithm() != NULL); QCOMPARE(mtx2.algorithm()->name(), mtx->algorithm()->name()); QCOMPARE(mtx2.duration(), uint(1200)); QCOMPARE(mtx2.fadeInSpeed(), uint(10)); QCOMPARE(mtx2.fadeOutSpeed(), uint(20)); QVERIFY(mtx2.loadXML(root.toElement()) == false); // Not a function node root.firstChild().toElement().setAttribute("Type", "Scene"); QVERIFY(mtx2.loadXML(root.firstChild().toElement()) == false); // Not an RGBMatrix node } QTEST_MAIN(RGBMatrix_Test) <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_tod_init.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //----------------------------------------------------------------------------------- // /// @file p9_tod_init.H /// @brief Procedures to initialize the TOD to 'running' state /// // *HWP HWP Owner: Christina Graves [email protected] // *HWP FW Owner: Thi Tran [email protected] // *HWP Team: Nest // *HWP Level: 1 // *HWP Consumed by: // ---------------------------------------------------------------------------------- // // *! ADDITIONAL COMMENTS : // *! // *! // *! //----------------------------------------------------------------------------------- #ifndef _P9_TOD_INIT_H_ #define _P9_TOD_INIT_H_ //----------------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------------- #include <fapi2.H> #include "p9_tod_utils.H" //----------------------------------------------------------------------------------- // Structure definitions //----------------------------------------------------------------------------------- //function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_tod_init_FP_t) (const tod_topology_node*, fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>* ); //----------------------------------------------------------------------------------- // Constant definitions //----------------------------------------------------------------------------------- extern "C" { //----------------------------------------------------------------------------------- // Function prototype //----------------------------------------------------------------------------------- /// @brief Initialized the TOD to 'running' state /// @param[in] i_tod_node => Reference to TOD topology (FAPI targets are included in this) /// @param[in] i_failingTodProc => Pointer to the fapi target, the memory location addressed by this parameter will be populated with processor target which is not able ot receive proper signals from OSC. Caller needs to look at this parameter only when p9_tod_init fail and reason code indicated OSC failure. Defaulted to NULL. /// @return FAPI_RC_SUCCESS if TOD topology is successfully initialized else FAPI or ECMD error is sent through fapi2::ReturnCode p9_tod_init( const tod_topology_node* i_tod_node, fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>* i_target = NULL); } //extern "C" #endif //_P9_TOD_INIT_H_ <commit_msg>Tod init and tod setup L2 procedures<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_tod_init.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //----------------------------------------------------------------------------------- // /// @file p9_tod_init.H /// @brief Procedures to initialize the TOD to 'running' state /// // *HWP HWP Owner: Christina Graves [email protected] // *HWP FW Owner: Thi Tran [email protected] // *HWP Team: Nest // *HWP Level: 2 // *HWP Consumed by: SBE // ---------------------------------------------------------------------------------- // // *! ADDITIONAL COMMENTS : // *! // *! // *! //----------------------------------------------------------------------------------- #ifndef _P9_TOD_INIT_H_ #define _P9_TOD_INIT_H_ //----------------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------------- #include <fapi2.H> #include <p9_tod_utils.H> //----------------------------------------------------------------------------------- // Structure definitions //----------------------------------------------------------------------------------- //function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_tod_init_FP_t) (const tod_topology_node*, fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>* ); //----------------------------------------------------------------------------------- // Constant definitions //----------------------------------------------------------------------------------- extern "C" { //----------------------------------------------------------------------------------- // Function prototype //----------------------------------------------------------------------------------- /// @brief Initialized the TOD to 'running' state /// @param[in] i_tod_node => Pointer to TOD topology (FAPI targets are included in this) /// @param[in] i_failingTodProc => Pointer to the fapi target, the memory location addressed by this parameter will be populated with processor target which is not able ot receive proper signals from OSC. Caller needs to look at this parameter only when p9_tod_init fail and reason code indicated OSC failure. Defaulted to NULL. /// @return FAPI_RC_SUCCESS if TOD topology is successfully initialized else FAPI or ECMD error is sent through fapi2::ReturnCode p9_tod_init(const tod_topology_node* i_tod_node, fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>* i_failingTodProc = NULL); /// @brief Clears TOD error register /// @param[in] i_tod_node => Pointer to TOD topology (FAPI targets included within) /// @return FAPI_RC_SUCCESS if TOD topology is cleared of previous errors /// else FAPI or ECMD error is sent through fapi2::ReturnCode p9_tod_clear_error_reg(const tod_topology_node* i_tod_node); /// @brief Helper function for p9_tod_init /// @param[in] i_tod_node => Pointer to TOD topology (FAPI targets included within) /// @param[in] i_failingTodProc => Pointer to the fapi target, the memory location /// addressed by this parameter will be populated with processor target /// which is not able to recieve proper singals from OSC. /// Caller needs to look at this parameter only when proc_tod_init fails /// and reason code indicates OSC failure. It is defaulted to NULL. /// @return FAPI_RC_SUCCESS if TOD topology is successfully initialized /// else FAPI or ECMD error is sent through fapi2::ReturnCode init_tod_node(const tod_topology_node* i_tod_node, fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>* i_failingTodProc = NULL); } //extern "C" #endif //_P9_TOD_INIT_H_ <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <thrift/lib/cpp2/async/RequestChannel.h> #include <thrift/lib/cpp2/protocol/BinaryProtocol.h> #include <thrift/lib/cpp2/protocol/CompactProtocol.h> namespace apache { namespace thrift { template <typename F> static void maybeRunInEb(folly::EventBase* eb, F func) { if (!eb || eb->isInEventBaseThread()) { func(); } else { eb->runInEventBaseThread(std::forward<F>(func)); } } template <> void RequestChannel::sendRequestAsync<RpcKind::SINGLE_REQUEST_NO_RESPONSE>( const apache::thrift::RpcOptions& rpcOptions, folly::StringPiece methodName, SerializedRequest&& request, std::shared_ptr<apache::thrift::transport::THeader> header, RequestClientCallback::Ptr callback) { maybeRunInEb( getEventBase(), [this, rpcOptions, methodNameStr = std::string(methodName), request = std::move(request), header = std::move(header), callback = std::move(callback)]() mutable { sendRequestNoResponse( rpcOptions, methodNameStr.c_str(), std::move(request), std::move(header), std::move(callback)); }); } template <> void RequestChannel::sendRequestAsync<RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE>( const apache::thrift::RpcOptions& rpcOptions, folly::StringPiece methodName, SerializedRequest&& request, std::shared_ptr<apache::thrift::transport::THeader> header, RequestClientCallback::Ptr callback) { maybeRunInEb( getEventBase(), [this, rpcOptions, methodNameStr = std::string(methodName), request = std::move(request), header = std::move(header), callback = std::move(callback)]() mutable { sendRequestResponse( rpcOptions, methodNameStr.c_str(), std::move(request), std::move(header), std::move(callback)); }); } template <> void RequestChannel::sendRequestAsync< RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE>( const apache::thrift::RpcOptions& rpcOptions, folly::StringPiece methodName, SerializedRequest&& request, std::shared_ptr<apache::thrift::transport::THeader> header, StreamClientCallback* callback) { maybeRunInEb( getEventBase(), [this, rpcOptions, methodNameStr = std::string(methodName), request = std::move(request), header = std::move(header), callback = std::move(callback)]() mutable { sendRequestStream( rpcOptions, methodNameStr.c_str(), std::move(request), std::move(header), callback); }); } template <> void RequestChannel::sendRequestAsync<RpcKind::SINK>( const apache::thrift::RpcOptions& rpcOptions, folly::StringPiece methodName, SerializedRequest&& request, std::shared_ptr<apache::thrift::transport::THeader> header, SinkClientCallback* callback) { maybeRunInEb( getEventBase(), [this, rpcOptions, methodNameStr = std::string(methodName), request = std::move(request), header = std::move(header), callback = std::move(callback)]() mutable { sendRequestSink( rpcOptions, methodNameStr.c_str(), std::move(request), std::move(header), callback); }); } void RequestChannel::sendRequestStream( const RpcOptions&, folly::StringPiece, SerializedRequest&&, std::shared_ptr<transport::THeader>, StreamClientCallback* clientCallback) { clientCallback->onFirstResponseError( folly::make_exception_wrapper<transport::TTransportException>( "This channel doesn't support stream RPC")); } void RequestChannel::sendRequestSink( const RpcOptions&, folly::StringPiece, SerializedRequest&&, std::shared_ptr<transport::THeader>, SinkClientCallback* clientCallback) { clientCallback->onFirstResponseError( folly::make_exception_wrapper<transport::TTransportException>( "This channel doesn't support sink RPC")); } void RequestChannel::terminateInteraction(InteractionId) { folly::terminate_with<std::runtime_error>( "This channel doesn't support interactions"); } InteractionId RequestChannel::createInteraction(folly::StringPiece name) { static std::atomic<int64_t> nextId{0}; int64_t id = 1 + nextId.fetch_add(1, std::memory_order_relaxed); return registerInteraction(name, id); } InteractionId RequestChannel::registerInteraction(folly::StringPiece, int64_t) { folly::terminate_with<std::runtime_error>( "This channel doesn't support interactions"); } InteractionId RequestChannel::createInteractionId(int64_t id) { return InteractionId(id); } void RequestChannel::releaseInteractionId(InteractionId&& id) { id.release(); } } // namespace thrift } // namespace apache <commit_msg>Avoid recomputing method name length in sendRequestAsync<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <thrift/lib/cpp2/async/RequestChannel.h> #include <thrift/lib/cpp2/protocol/BinaryProtocol.h> #include <thrift/lib/cpp2/protocol/CompactProtocol.h> namespace apache { namespace thrift { template <typename F> static void maybeRunInEb(folly::EventBase* eb, F func) { if (!eb || eb->isInEventBaseThread()) { func(); } else { eb->runInEventBaseThread(std::forward<F>(func)); } } template <> void RequestChannel::sendRequestAsync<RpcKind::SINGLE_REQUEST_NO_RESPONSE>( const apache::thrift::RpcOptions& rpcOptions, folly::StringPiece methodName, SerializedRequest&& request, std::shared_ptr<apache::thrift::transport::THeader> header, RequestClientCallback::Ptr callback) { maybeRunInEb( getEventBase(), [this, rpcOptions, methodNameStr = std::string(methodName), request = std::move(request), header = std::move(header), callback = std::move(callback)]() mutable { sendRequestNoResponse( rpcOptions, methodNameStr, std::move(request), std::move(header), std::move(callback)); }); } template <> void RequestChannel::sendRequestAsync<RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE>( const apache::thrift::RpcOptions& rpcOptions, folly::StringPiece methodName, SerializedRequest&& request, std::shared_ptr<apache::thrift::transport::THeader> header, RequestClientCallback::Ptr callback) { maybeRunInEb( getEventBase(), [this, rpcOptions, methodNameStr = std::string(methodName), request = std::move(request), header = std::move(header), callback = std::move(callback)]() mutable { sendRequestResponse( rpcOptions, methodNameStr, std::move(request), std::move(header), std::move(callback)); }); } template <> void RequestChannel::sendRequestAsync< RpcKind::SINGLE_REQUEST_STREAMING_RESPONSE>( const apache::thrift::RpcOptions& rpcOptions, folly::StringPiece methodName, SerializedRequest&& request, std::shared_ptr<apache::thrift::transport::THeader> header, StreamClientCallback* callback) { maybeRunInEb( getEventBase(), [this, rpcOptions, methodNameStr = std::string(methodName), request = std::move(request), header = std::move(header), callback = std::move(callback)]() mutable { sendRequestStream( rpcOptions, methodNameStr, std::move(request), std::move(header), callback); }); } template <> void RequestChannel::sendRequestAsync<RpcKind::SINK>( const apache::thrift::RpcOptions& rpcOptions, folly::StringPiece methodName, SerializedRequest&& request, std::shared_ptr<apache::thrift::transport::THeader> header, SinkClientCallback* callback) { maybeRunInEb( getEventBase(), [this, rpcOptions, methodNameStr = std::string(methodName), request = std::move(request), header = std::move(header), callback = std::move(callback)]() mutable { sendRequestSink( rpcOptions, methodNameStr, std::move(request), std::move(header), callback); }); } void RequestChannel::sendRequestStream( const RpcOptions&, folly::StringPiece, SerializedRequest&&, std::shared_ptr<transport::THeader>, StreamClientCallback* clientCallback) { clientCallback->onFirstResponseError( folly::make_exception_wrapper<transport::TTransportException>( "This channel doesn't support stream RPC")); } void RequestChannel::sendRequestSink( const RpcOptions&, folly::StringPiece, SerializedRequest&&, std::shared_ptr<transport::THeader>, SinkClientCallback* clientCallback) { clientCallback->onFirstResponseError( folly::make_exception_wrapper<transport::TTransportException>( "This channel doesn't support sink RPC")); } void RequestChannel::terminateInteraction(InteractionId) { folly::terminate_with<std::runtime_error>( "This channel doesn't support interactions"); } InteractionId RequestChannel::createInteraction(folly::StringPiece name) { static std::atomic<int64_t> nextId{0}; int64_t id = 1 + nextId.fetch_add(1, std::memory_order_relaxed); return registerInteraction(name, id); } InteractionId RequestChannel::registerInteraction(folly::StringPiece, int64_t) { folly::terminate_with<std::runtime_error>( "This channel doesn't support interactions"); } InteractionId RequestChannel::createInteractionId(int64_t id) { return InteractionId(id); } void RequestChannel::releaseInteractionId(InteractionId&& id) { id.release(); } } // namespace thrift } // namespace apache <|endoftext|>
<commit_before>#include "protocol.h" Protocol::Protocol(std::string serverAddress, std::tr1::unordered_map<std::string, std::string> confVars, Base* theBase, unsigned short debug) : serverName(serverAddress), debugLevel(debug), serverConf(confVars), botBase(theBase), keepServer(true) { connection = botBase->assignSocket(confVars["sockettype"]); } Protocol::~Protocol() {} void Protocol::connectServer() {} bool Protocol::stillConnected() { if (connection == NULL) return false; return connection->isConnected(); } bool Protocol::shouldReset() { return keepServer; } bool Protocol::isClient() { return false; } // most protocol modules won't be clients std::tr1::unordered_map<std::string, std::string> Protocol::info() { return serverConf; } std::list<std::pair<std::string, char> > Protocol::prefixes() { return std::list<std::pair<std::string, char> > (); } std::set<char> Protocol::channelTypes() { return std::set<char> (); } std::vector<std::vector<std::string> > Protocol::channelModes() { return std::vector<std::vector<std::string> > (); } std::list<std::string> Protocol::channels() { return std::list<std::string> (); } std::string Protocol::channelTopic(std::string channel) { return ""; } std::set<std::string> Protocol::channelUsers(std::string channel) { return std::set<std::string> (); } std::set<std::string> Protocol::channelModes(std::string channel) { return std::set<std::string> (); } std::string Protocol::userIdent(std::string user) { return ""; } std::string Protocol::userHost(std::string user) { return ""; } std::pair<std::string, char> Protocol::userStatus(std::string channel, std::string user) { return std::pair<std::string, char> ("", ' '); } std::string Protocol::userMetadata(std::string user, std::string key) { return ""; } std::string Protocol::compareStatus(std::set<std::string> statuses) { return *(statuses.begin()); } // It may or may not be correct for the server, but it's a valid answer. void Protocol::sendMsg(std::string client, std::string target, std::string message) {} void Protocol::sendNotice(std::string client, std::string target, std::string message) {} void Protocol::setMode(std::string client, std::string target, std::list<std::string> addModes, std::list<std::string> remModes) {} void Protocol::joinChannel(std::string client, std::string channel, std::string key) {} void Protocol::partChannel(std::string client, std::string channel, std::string reason) {} void Protocol::quitServer(std::string reason) {} void Protocol::kickUser(std::string client, std::string channel, std::string user, std::string reason) {} void Protocol::changeNick(std::string client, std::string newNick) {} void Protocol::oper(std::string client, std::string username, std::string password) {} void Protocol::killUser(std::string client, std::string user, std::string reason) {} void Protocol::setXLine(std::string client, char lineType, std::string hostmask, time_t duration, std::string reason) {} void Protocol::removeXLine(std::string client, char lineType, std::string hostmask) {} std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, time_t> > Protocol::listXLines() { return std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, time_t> > (); } void Protocol::sendSNotice(char snomask, std::string text) {} void Protocol::sendOther(std::string rawLine) {} std::string Protocol::addClient(std::string nick, std::string ident, std::string host, std::string gecos) { return ""; } void Protocol::removeClient(std::string client, std::string reason) {} std::set<std::string> Protocol::clients() { return std::set<std::string> (); } std::tr1::unordered_map<std::string, std::string> Protocol::clientInfo(std::string client) { return std::tr1::unordered_map<std::string, std::string> (); } std::list<std::string> Protocol::userModes(std::string client) { return std::list<std::string> (); } std::vector<std::string> Protocol::parseLine(std::string rawLine) { std::vector<std::string> parsedLine; std::string linePart = ""; for (unsigned int i = 0; i < rawLine.size(); i++) { if (i != 0 && rawLine[i] == ':' && rawLine[i-1] == ' ') { i++; // Move off of colon while (i < rawLine.size()) { linePart += rawLine[i]; i++; } parsedLine.push_back(linePart); return parsedLine; } if (rawLine[i] == ' ') { parsedLine.push_back(linePart); linePart = ""; continue; } linePart += rawLine[i]; } if (linePart != "") parsedLine.push_back(linePart); return parsedLine; } bool Protocol::callChanMsgHook(std::string client, std::string channel, char target, std::string nick, std::string message) { return botBase->callChanMsgHook(serverName, client, channel, target, nick, message); } bool Protocol::callUserMsgHook(std::string client, std::string nick, std::string message) { return botBase->callUserMsgHook(serverName, client, nick, message); } bool Protocol::callChanNoticeHook(std::string client, std::string channel, char target, std::string nick, std::string message) { return botBase->callChanNoticeHook(serverName, client, channel, target, nick, message); } bool Protocol::callUserNoticeHook(std::string client, std::string nick, std::string message) { return botBase->callUserNoticeHook(serverName, client, nick, message); } bool Protocol::callChannelCTCPHook(std::string client, std::string channel, char target, std::string nick, std::string message) { return botBase->callChannelCTCPHook(serverName, client, channel, target, nick, message); } bool Protocol::callUserCTCPHook(std::string client, std::string nick, std::string message) { return botBase->callUserCTCPHook(serverName, client, nick, message); } bool Protocol::callChannelCTCPReplyHook(std::string client, std::string channel, char target, std::string nick, std::string message) { return botBase->callChannelCTCPReplyHook(serverName, client, channel, target, nick, message); } bool Protocol::callUserCTCPReplyHook(std::string client, std::string nick, std::string message) { return botBase->callUserCTCPReplyHook(serverName, client, nick, message); } void Protocol::callChannelJoinPreHook(std::string channel, std::string hostmask) { botBase->callChannelJoinPreHook(serverName, channel, hostmask); } void Protocol::callChannelJoinPostHook(std::string channel, std::string hostmask) { botBase->callChannelJoinPostHook(serverName, channel, hostmask); } void Protocol::callChannelPartPreHook(std::string channel, std::string hostmask, std::string reason) { botBase->callChannelPartPreHook(serverName, channel, hostmask, reason); } void Protocol::callChannelPartPostHook(std::string channel, std::string hostmask, std::string reason) { botBase->callChannelPartPostHook(serverName, channel, hostmask, reason); } void Protocol::callUserConnectPreHook(std::string nick, std::string ident, std::string host, std::string gecos) { botBase->callUserConnectPreHook(serverName, nick, ident, host, gecos); } void Protocol::callUserConnectPostHook(std::string nick, std::string ident, std::string host, std::string gecos) { botBase->callUserConnectPostHook(serverName, nick, ident, host, gecos); } void Protocol::callUserQuitPreHook(std::string hostmask, std::string reason) { botBase->callUserQuitPreHook(serverName, hostmask, reason); } void Protocol::callUserQuitPostHook(std::string hostmask, std::string reason) { botBase->callUserQuitPostHook(serverName, hostmask, reason); } void Protocol::callNickChangePreHook(std::string oldNick, std::string newNick) { botBase->callNickChangePreHook(serverName, oldNick, newNick); } void Protocol::callNickChangePostHook(std::string oldNick, std::string newNick) { botBase->callNickChangePostHook(serverName, oldNick, newNick); } void Protocol::callChannelKickPreHook(std::string channel, std::string kicker, std::string kickee, std::string reason) { botBase->callChannelKickPreHook(serverName, channel, kicker, kickee, reason); } void Protocol::callChannelKickPostHook(std::string channel, std::string kicker, std::string kickee, std::string reason) { botBase->callChannelKickPostHook(serverName, channel, kicker, kickee, reason); } void Protocol::callChannelModePreHook(std::string channel, std::string setter, std::string mode, bool add, std::string param) { botBase->callChannelModePreHook(serverName, channel, setter, mode, add, param); } void Protocol::callChannelModePostHook(std::string channel, std::string setter, std::string mode, bool add, std::string param) { botBase->callChannelModePostHook(serverName, channel, setter, mode, add, param); } void Protocol::callUserModePreHook(std::string client, std::string mode, bool add) { botBase->callUserModePreHook(serverName, client, mode, add); } void Protocol::callUserModePostHook(std::string client, std::string mode, bool add) { botBase->callUserModePostHook(serverName, client, mode, add); } void Protocol::callUserOperPreHook(std::string user, std::string opertype) { botBase->callUserOperPreHook(serverName, user, opertype); } void Protocol::callUserOperPostHook(std::string user, std::string opertype) { botBase->callUserOperPostHook(serverName, user, opertype); } void Protocol::callNumericHook(std::string client, std::string numeric, std::vector<std::string> parsedLine) { botBase->callNumericHook(serverName, client, numeric, parsedLine); } void Protocol::callOtherDataHook(std::string client, std::vector<std::string> parsedLine) { botBase->callOtherDataHook(serverName, client, parsedLine); } void Protocol::callPreConnectHook() { botBase->callPreConnectHook(serverName); } void Protocol::callConnectHook(std::string client) { botBase->callConnectHook(serverName, client); } void Protocol::callQuitHook(std::string client) { botBase->callQuitHook(serverName, client); } std::string Protocol::callChannelMessageOutHook(std::string client, std::string target, char status, std::string message) { return botBase->callChannelMessageOutHook(serverName, client, target, status, message); } void Protocol::callChannelMessageSendHook(std::string client, std::string target, char status, std::string message) { botBase->callChannelMessageSendHook(serverName, client, target, status, message); } std::string Protocol::callUserMessageOutHook(std::string client, std::string target, std::string message) { return botBase->callUserMessageOutHook(serverName, client, target, message); } void Protocol::callUserMessageSendHook(std::string client, std::string target, std::string message) { botBase->callUserMessageSendHook(serverName, client, target, message); } std::string Protocol::callChannelNoticeOutHook(std::string client, std::string target, char status, std::string message) { return botBase->callChannelNoticeOutHook(serverName, client, target, status, message); } void Protocol::callChannelNoticeSendHook(std::string client, std::string target, char status, std::string message) { botBase->callChannelNoticeSendHook(serverName, client, target, status, message); } std::string Protocol::callUserNoticeOutHook(std::string client, std::string target, std::string message) { return botBase->callUserNoticeOutHook(serverName, client, target, message); } void Protocol::callUserNoticeSendHook(std::string client, std::string target, std::string message) { botBase->callUserNoticeSendHook(serverName, client, target, message); } std::string Protocol::callChannelCTCPOutHook(std::string client, std::string target, char status, std::string message) { return botBase->callChannelCTCPOutHook(serverName, client, target, status, message); } void Protocol::callChannelCTCPSendHook(std::string client, std::string target, char status, std::string message) { botBase->callChannelCTCPSendHook(serverName, client, target, status, message); } std::string Protocol::callUserCTCPOutHook(std::string client, std::string target, std::string message) { return botBase->callUserCTCPOutHook(serverName, client, target, message); } void Protocol::callUserCTCPSendHook(std::string client, std::string target, std::string message) { botBase->callUserCTCPSendHook(serverName, client, target, message); } std::string Protocol::callChannelCTCPReplyOutHook(std::string client, std::string target, char status, std::string message) { return botBase->callChannelCTCPReplyOutHook(serverName, client, target, status, message); } void Protocol::callChannelCTCPReplySendHook(std::string client, std::string target, char status, std::string message) { botBase->callChannelCTCPReplySendHook(serverName, client, target, status, message); } std::string Protocol::callUserCTCPReplyOutHook(std::string client, std::string target, std::string message) { return botBase->callUserCTCPReplyOutHook(serverName, client, target, message); } void Protocol::callUserCTCPReplySendHook(std::string client, std::string target, std::string message) { botBase->callUserCTCPReplySendHook(serverName, client, target, message); }<commit_msg>Quash warning<commit_after>#include "protocol.h" Protocol::Protocol(std::string serverAddress, std::tr1::unordered_map<std::string, std::string> confVars, Base* theBase, unsigned short debug) : serverName(serverAddress), keepServer(true), debugLevel(debug), serverConf(confVars), botBase(theBase) { connection = botBase->assignSocket(confVars["sockettype"]); } Protocol::~Protocol() {} void Protocol::connectServer() {} bool Protocol::stillConnected() { if (connection == NULL) return false; return connection->isConnected(); } bool Protocol::shouldReset() { return keepServer; } bool Protocol::isClient() { return false; } // most protocol modules won't be clients std::tr1::unordered_map<std::string, std::string> Protocol::info() { return serverConf; } std::list<std::pair<std::string, char> > Protocol::prefixes() { return std::list<std::pair<std::string, char> > (); } std::set<char> Protocol::channelTypes() { return std::set<char> (); } std::vector<std::vector<std::string> > Protocol::channelModes() { return std::vector<std::vector<std::string> > (); } std::list<std::string> Protocol::channels() { return std::list<std::string> (); } std::string Protocol::channelTopic(std::string channel) { return ""; } std::set<std::string> Protocol::channelUsers(std::string channel) { return std::set<std::string> (); } std::set<std::string> Protocol::channelModes(std::string channel) { return std::set<std::string> (); } std::string Protocol::userIdent(std::string user) { return ""; } std::string Protocol::userHost(std::string user) { return ""; } std::pair<std::string, char> Protocol::userStatus(std::string channel, std::string user) { return std::pair<std::string, char> ("", ' '); } std::string Protocol::userMetadata(std::string user, std::string key) { return ""; } std::string Protocol::compareStatus(std::set<std::string> statuses) { return *(statuses.begin()); } // It may or may not be correct for the server, but it's a valid answer. void Protocol::sendMsg(std::string client, std::string target, std::string message) {} void Protocol::sendNotice(std::string client, std::string target, std::string message) {} void Protocol::setMode(std::string client, std::string target, std::list<std::string> addModes, std::list<std::string> remModes) {} void Protocol::joinChannel(std::string client, std::string channel, std::string key) {} void Protocol::partChannel(std::string client, std::string channel, std::string reason) {} void Protocol::quitServer(std::string reason) {} void Protocol::kickUser(std::string client, std::string channel, std::string user, std::string reason) {} void Protocol::changeNick(std::string client, std::string newNick) {} void Protocol::oper(std::string client, std::string username, std::string password) {} void Protocol::killUser(std::string client, std::string user, std::string reason) {} void Protocol::setXLine(std::string client, char lineType, std::string hostmask, time_t duration, std::string reason) {} void Protocol::removeXLine(std::string client, char lineType, std::string hostmask) {} std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, time_t> > Protocol::listXLines() { return std::tr1::unordered_map<std::string, std::tr1::unordered_map<std::string, time_t> > (); } void Protocol::sendSNotice(char snomask, std::string text) {} void Protocol::sendOther(std::string rawLine) {} std::string Protocol::addClient(std::string nick, std::string ident, std::string host, std::string gecos) { return ""; } void Protocol::removeClient(std::string client, std::string reason) {} std::set<std::string> Protocol::clients() { return std::set<std::string> (); } std::tr1::unordered_map<std::string, std::string> Protocol::clientInfo(std::string client) { return std::tr1::unordered_map<std::string, std::string> (); } std::list<std::string> Protocol::userModes(std::string client) { return std::list<std::string> (); } std::vector<std::string> Protocol::parseLine(std::string rawLine) { std::vector<std::string> parsedLine; std::string linePart = ""; for (unsigned int i = 0; i < rawLine.size(); i++) { if (i != 0 && rawLine[i] == ':' && rawLine[i-1] == ' ') { i++; // Move off of colon while (i < rawLine.size()) { linePart += rawLine[i]; i++; } parsedLine.push_back(linePart); return parsedLine; } if (rawLine[i] == ' ') { parsedLine.push_back(linePart); linePart = ""; continue; } linePart += rawLine[i]; } if (linePart != "") parsedLine.push_back(linePart); return parsedLine; } bool Protocol::callChanMsgHook(std::string client, std::string channel, char target, std::string nick, std::string message) { return botBase->callChanMsgHook(serverName, client, channel, target, nick, message); } bool Protocol::callUserMsgHook(std::string client, std::string nick, std::string message) { return botBase->callUserMsgHook(serverName, client, nick, message); } bool Protocol::callChanNoticeHook(std::string client, std::string channel, char target, std::string nick, std::string message) { return botBase->callChanNoticeHook(serverName, client, channel, target, nick, message); } bool Protocol::callUserNoticeHook(std::string client, std::string nick, std::string message) { return botBase->callUserNoticeHook(serverName, client, nick, message); } bool Protocol::callChannelCTCPHook(std::string client, std::string channel, char target, std::string nick, std::string message) { return botBase->callChannelCTCPHook(serverName, client, channel, target, nick, message); } bool Protocol::callUserCTCPHook(std::string client, std::string nick, std::string message) { return botBase->callUserCTCPHook(serverName, client, nick, message); } bool Protocol::callChannelCTCPReplyHook(std::string client, std::string channel, char target, std::string nick, std::string message) { return botBase->callChannelCTCPReplyHook(serverName, client, channel, target, nick, message); } bool Protocol::callUserCTCPReplyHook(std::string client, std::string nick, std::string message) { return botBase->callUserCTCPReplyHook(serverName, client, nick, message); } void Protocol::callChannelJoinPreHook(std::string channel, std::string hostmask) { botBase->callChannelJoinPreHook(serverName, channel, hostmask); } void Protocol::callChannelJoinPostHook(std::string channel, std::string hostmask) { botBase->callChannelJoinPostHook(serverName, channel, hostmask); } void Protocol::callChannelPartPreHook(std::string channel, std::string hostmask, std::string reason) { botBase->callChannelPartPreHook(serverName, channel, hostmask, reason); } void Protocol::callChannelPartPostHook(std::string channel, std::string hostmask, std::string reason) { botBase->callChannelPartPostHook(serverName, channel, hostmask, reason); } void Protocol::callUserConnectPreHook(std::string nick, std::string ident, std::string host, std::string gecos) { botBase->callUserConnectPreHook(serverName, nick, ident, host, gecos); } void Protocol::callUserConnectPostHook(std::string nick, std::string ident, std::string host, std::string gecos) { botBase->callUserConnectPostHook(serverName, nick, ident, host, gecos); } void Protocol::callUserQuitPreHook(std::string hostmask, std::string reason) { botBase->callUserQuitPreHook(serverName, hostmask, reason); } void Protocol::callUserQuitPostHook(std::string hostmask, std::string reason) { botBase->callUserQuitPostHook(serverName, hostmask, reason); } void Protocol::callNickChangePreHook(std::string oldNick, std::string newNick) { botBase->callNickChangePreHook(serverName, oldNick, newNick); } void Protocol::callNickChangePostHook(std::string oldNick, std::string newNick) { botBase->callNickChangePostHook(serverName, oldNick, newNick); } void Protocol::callChannelKickPreHook(std::string channel, std::string kicker, std::string kickee, std::string reason) { botBase->callChannelKickPreHook(serverName, channel, kicker, kickee, reason); } void Protocol::callChannelKickPostHook(std::string channel, std::string kicker, std::string kickee, std::string reason) { botBase->callChannelKickPostHook(serverName, channel, kicker, kickee, reason); } void Protocol::callChannelModePreHook(std::string channel, std::string setter, std::string mode, bool add, std::string param) { botBase->callChannelModePreHook(serverName, channel, setter, mode, add, param); } void Protocol::callChannelModePostHook(std::string channel, std::string setter, std::string mode, bool add, std::string param) { botBase->callChannelModePostHook(serverName, channel, setter, mode, add, param); } void Protocol::callUserModePreHook(std::string client, std::string mode, bool add) { botBase->callUserModePreHook(serverName, client, mode, add); } void Protocol::callUserModePostHook(std::string client, std::string mode, bool add) { botBase->callUserModePostHook(serverName, client, mode, add); } void Protocol::callUserOperPreHook(std::string user, std::string opertype) { botBase->callUserOperPreHook(serverName, user, opertype); } void Protocol::callUserOperPostHook(std::string user, std::string opertype) { botBase->callUserOperPostHook(serverName, user, opertype); } void Protocol::callNumericHook(std::string client, std::string numeric, std::vector<std::string> parsedLine) { botBase->callNumericHook(serverName, client, numeric, parsedLine); } void Protocol::callOtherDataHook(std::string client, std::vector<std::string> parsedLine) { botBase->callOtherDataHook(serverName, client, parsedLine); } void Protocol::callPreConnectHook() { botBase->callPreConnectHook(serverName); } void Protocol::callConnectHook(std::string client) { botBase->callConnectHook(serverName, client); } void Protocol::callQuitHook(std::string client) { botBase->callQuitHook(serverName, client); } std::string Protocol::callChannelMessageOutHook(std::string client, std::string target, char status, std::string message) { return botBase->callChannelMessageOutHook(serverName, client, target, status, message); } void Protocol::callChannelMessageSendHook(std::string client, std::string target, char status, std::string message) { botBase->callChannelMessageSendHook(serverName, client, target, status, message); } std::string Protocol::callUserMessageOutHook(std::string client, std::string target, std::string message) { return botBase->callUserMessageOutHook(serverName, client, target, message); } void Protocol::callUserMessageSendHook(std::string client, std::string target, std::string message) { botBase->callUserMessageSendHook(serverName, client, target, message); } std::string Protocol::callChannelNoticeOutHook(std::string client, std::string target, char status, std::string message) { return botBase->callChannelNoticeOutHook(serverName, client, target, status, message); } void Protocol::callChannelNoticeSendHook(std::string client, std::string target, char status, std::string message) { botBase->callChannelNoticeSendHook(serverName, client, target, status, message); } std::string Protocol::callUserNoticeOutHook(std::string client, std::string target, std::string message) { return botBase->callUserNoticeOutHook(serverName, client, target, message); } void Protocol::callUserNoticeSendHook(std::string client, std::string target, std::string message) { botBase->callUserNoticeSendHook(serverName, client, target, message); } std::string Protocol::callChannelCTCPOutHook(std::string client, std::string target, char status, std::string message) { return botBase->callChannelCTCPOutHook(serverName, client, target, status, message); } void Protocol::callChannelCTCPSendHook(std::string client, std::string target, char status, std::string message) { botBase->callChannelCTCPSendHook(serverName, client, target, status, message); } std::string Protocol::callUserCTCPOutHook(std::string client, std::string target, std::string message) { return botBase->callUserCTCPOutHook(serverName, client, target, message); } void Protocol::callUserCTCPSendHook(std::string client, std::string target, std::string message) { botBase->callUserCTCPSendHook(serverName, client, target, message); } std::string Protocol::callChannelCTCPReplyOutHook(std::string client, std::string target, char status, std::string message) { return botBase->callChannelCTCPReplyOutHook(serverName, client, target, status, message); } void Protocol::callChannelCTCPReplySendHook(std::string client, std::string target, char status, std::string message) { botBase->callChannelCTCPReplySendHook(serverName, client, target, status, message); } std::string Protocol::callUserCTCPReplyOutHook(std::string client, std::string target, std::string message) { return botBase->callUserCTCPReplyOutHook(serverName, client, target, message); } void Protocol::callUserCTCPReplySendHook(std::string client, std::string target, std::string message) { botBase->callUserCTCPReplySendHook(serverName, client, target, message); }<|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 <memory> #include <usConfig.h> #include <usTestingMacros.h> #include <usModule.h> #include <usModuleContext.h> #include <usGetModuleContext.h> #include <usServiceInterface.h> #include <usServiceTracker.h> #include US_BASECLASS_HEADER #include "usServiceControlInterface.h" #include "usTestUtilSharedLibrary.h" #include <memory> US_USE_NAMESPACE int usServiceTrackerTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ServiceTrackerTest") ModuleContext* mc = GetModuleContext(); SharedLibraryHandle libS("TestModuleS"); // Start the test target to get a service published. try { libS.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() ); } // 1. Create a ServiceTracker with ServiceTrackerCustomizer == null std::string s1("org.cppmicroservices.TestModuleSService"); ServiceReference servref = mc->GetServiceReference(s1 + "0"); US_TEST_CONDITION_REQUIRED(servref != 0, "Test if registered service of id org.cppmicroservices.TestModuleSService0"); ServiceControlInterface* serviceController = mc->GetService<ServiceControlInterface>(servref); US_TEST_CONDITION_REQUIRED(serviceController != 0, "Test valid service controller"); std::auto_ptr<ServiceTracker<> > st1(new ServiceTracker<>(mc, servref)); // 2. Check the size method with an unopened service tracker US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Test if size == 0"); // 3. Open the service tracker and see what it finds, // expect to find one instance of the implementation, // "org.cppmicroservices.TestModuleSService0" st1->Open(); std::string expName = "TestModuleS"; std::list<ServiceReference> sa2; st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 1, "Checking ServiceTracker size"); std::string name(us_service_impl_name(mc->GetService(sa2.front()))); US_TEST_CONDITION_REQUIRED(name == expName, "Checking service implementation name"); // 5. Close this service tracker st1->Close(); // 6. Check the size method, now when the servicetracker is closed US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Checking ServiceTracker size"); // 7. Check if we still track anything , we should get null sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.empty(), "Checking ServiceTracker size"); // 8. A new Servicetracker, this time with a filter for the object std::string fs = std::string("(") + ServiceConstants::OBJECTCLASS() + "=" + s1 + "*" + ")"; LDAPFilter f1(fs); st1.reset(new ServiceTracker<>(mc, f1)); // add a service serviceController->ServiceControl(1, "register", 7); // 9. Open the service tracker and see what it finds, // expect to find two instances of references to // "org.cppmicroservices.TestModuleSService*" // i.e. they refer to the same piece of code st1->Open(); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name(mc->GetService(*i)->GetNameOfClass()); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 10. Get libTestModuleS to register one more service and see if it appears serviceController->ServiceControl(2, "register", 1); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name(mc->GetService(*i)->GetNameOfClass()); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 11. Get libTestModuleS to register one more service and see if it appears serviceController->ServiceControl(3, "register", 2); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 4, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name = mc->GetService(*i)->GetNameOfClass(); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 12. Get libTestModuleS to unregister one service and see if it disappears serviceController->ServiceControl(3, "unregister", 0); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name = mc->GetService(*i)->GetNameOfClass(); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 13. Get the highest ranking service reference, it should have ranking 7 ServiceReference h1 = st1->GetServiceReference(); int rank = any_cast<int>(h1.GetProperty(ServiceConstants::SERVICE_RANKING())); US_TEST_CONDITION_REQUIRED(rank == 7, "Check service rank"); // 14. Get the service of the highest ranked service reference US_BASECLASS_NAME* o1 = st1->GetService(h1); US_TEST_CONDITION_REQUIRED(o1 != 0, "Check for non-null service"); // 14a Get the highest ranked service, directly this time US_BASECLASS_NAME* o3 = st1->GetService(); US_TEST_CONDITION_REQUIRED(o3 != 0, "Check for non-null service"); US_TEST_CONDITION_REQUIRED(o1 == o3, "Check for equal service instances"); // 15. Now release the tracking of that service and then try to get it // from the servicetracker, which should yield a null object serviceController->ServiceControl(1, "unregister", 7); US_BASECLASS_NAME* o2 = st1->GetService(h1); US_TEST_CONDITION_REQUIRED(o2 == 0, "Checkt that service is null"); // 16. Get all service objects this tracker tracks, it should be 2 std::list<US_BASECLASS_NAME*> ts1; st1->GetServices(ts1); US_TEST_CONDITION_REQUIRED(ts1.size() == 2, "Check service count"); // 17. Test the remove method. // First register another service, then remove it being tracked serviceController->ServiceControl(1, "register", 7); h1 = st1->GetServiceReference(); std::list<ServiceReference> sa3; st1->GetServiceReferences(sa3); US_TEST_CONDITION_REQUIRED(sa3.size() == 3, "Check service reference count"); for (std::list<ServiceReference>::const_iterator i = sa3.begin(); i != sa3.end(); ++i) { std::string name = mc->GetService(*i)->GetNameOfClass(); US_TEST_CONDITION_REQUIRED(name == expName, "Checking for expected class name"); } st1->Remove(h1); // remove tracking on one servref sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Check service reference count"); // 18. Test the addingService method,add a service reference // 19. Test the removedService method, remove a service reference // 20. Test the waitForService method US_BASECLASS_NAME* o9 = st1->WaitForService(50); US_TEST_CONDITION_REQUIRED(o9 != 0, "Checking WaitForService method"); US_TEST_END() } <commit_msg>Removed duplicated include statement.<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 <usConfig.h> #include <usTestingMacros.h> #include <usModule.h> #include <usModuleContext.h> #include <usGetModuleContext.h> #include <usServiceInterface.h> #include <usServiceTracker.h> #include US_BASECLASS_HEADER #include "usServiceControlInterface.h" #include "usTestUtilSharedLibrary.h" #include <memory> US_USE_NAMESPACE int usServiceTrackerTest(int /*argc*/, char* /*argv*/[]) { US_TEST_BEGIN("ServiceTrackerTest") ModuleContext* mc = GetModuleContext(); SharedLibraryHandle libS("TestModuleS"); // Start the test target to get a service published. try { libS.Load(); } catch (const std::exception& e) { US_TEST_FAILED_MSG( << "Failed to load module, got exception: " << e.what() ); } // 1. Create a ServiceTracker with ServiceTrackerCustomizer == null std::string s1("org.cppmicroservices.TestModuleSService"); ServiceReference servref = mc->GetServiceReference(s1 + "0"); US_TEST_CONDITION_REQUIRED(servref != 0, "Test if registered service of id org.cppmicroservices.TestModuleSService0"); ServiceControlInterface* serviceController = mc->GetService<ServiceControlInterface>(servref); US_TEST_CONDITION_REQUIRED(serviceController != 0, "Test valid service controller"); std::auto_ptr<ServiceTracker<> > st1(new ServiceTracker<>(mc, servref)); // 2. Check the size method with an unopened service tracker US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Test if size == 0"); // 3. Open the service tracker and see what it finds, // expect to find one instance of the implementation, // "org.cppmicroservices.TestModuleSService0" st1->Open(); std::string expName = "TestModuleS"; std::list<ServiceReference> sa2; st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 1, "Checking ServiceTracker size"); std::string name(us_service_impl_name(mc->GetService(sa2.front()))); US_TEST_CONDITION_REQUIRED(name == expName, "Checking service implementation name"); // 5. Close this service tracker st1->Close(); // 6. Check the size method, now when the servicetracker is closed US_TEST_CONDITION_REQUIRED(st1->Size() == 0, "Checking ServiceTracker size"); // 7. Check if we still track anything , we should get null sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.empty(), "Checking ServiceTracker size"); // 8. A new Servicetracker, this time with a filter for the object std::string fs = std::string("(") + ServiceConstants::OBJECTCLASS() + "=" + s1 + "*" + ")"; LDAPFilter f1(fs); st1.reset(new ServiceTracker<>(mc, f1)); // add a service serviceController->ServiceControl(1, "register", 7); // 9. Open the service tracker and see what it finds, // expect to find two instances of references to // "org.cppmicroservices.TestModuleSService*" // i.e. they refer to the same piece of code st1->Open(); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name(mc->GetService(*i)->GetNameOfClass()); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 10. Get libTestModuleS to register one more service and see if it appears serviceController->ServiceControl(2, "register", 1); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name(mc->GetService(*i)->GetNameOfClass()); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 11. Get libTestModuleS to register one more service and see if it appears serviceController->ServiceControl(3, "register", 2); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 4, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name = mc->GetService(*i)->GetNameOfClass(); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 12. Get libTestModuleS to unregister one service and see if it disappears serviceController->ServiceControl(3, "unregister", 0); sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 3, "Checking service reference count"); for (std::list<ServiceReference>::const_iterator i = sa2.begin(); i != sa2.end(); ++i) { std::string name = mc->GetService(*i)->GetNameOfClass(); US_TEST_CONDITION_REQUIRED(name == expName, "Check for expected class name"); } // 13. Get the highest ranking service reference, it should have ranking 7 ServiceReference h1 = st1->GetServiceReference(); int rank = any_cast<int>(h1.GetProperty(ServiceConstants::SERVICE_RANKING())); US_TEST_CONDITION_REQUIRED(rank == 7, "Check service rank"); // 14. Get the service of the highest ranked service reference US_BASECLASS_NAME* o1 = st1->GetService(h1); US_TEST_CONDITION_REQUIRED(o1 != 0, "Check for non-null service"); // 14a Get the highest ranked service, directly this time US_BASECLASS_NAME* o3 = st1->GetService(); US_TEST_CONDITION_REQUIRED(o3 != 0, "Check for non-null service"); US_TEST_CONDITION_REQUIRED(o1 == o3, "Check for equal service instances"); // 15. Now release the tracking of that service and then try to get it // from the servicetracker, which should yield a null object serviceController->ServiceControl(1, "unregister", 7); US_BASECLASS_NAME* o2 = st1->GetService(h1); US_TEST_CONDITION_REQUIRED(o2 == 0, "Checkt that service is null"); // 16. Get all service objects this tracker tracks, it should be 2 std::list<US_BASECLASS_NAME*> ts1; st1->GetServices(ts1); US_TEST_CONDITION_REQUIRED(ts1.size() == 2, "Check service count"); // 17. Test the remove method. // First register another service, then remove it being tracked serviceController->ServiceControl(1, "register", 7); h1 = st1->GetServiceReference(); std::list<ServiceReference> sa3; st1->GetServiceReferences(sa3); US_TEST_CONDITION_REQUIRED(sa3.size() == 3, "Check service reference count"); for (std::list<ServiceReference>::const_iterator i = sa3.begin(); i != sa3.end(); ++i) { std::string name = mc->GetService(*i)->GetNameOfClass(); US_TEST_CONDITION_REQUIRED(name == expName, "Checking for expected class name"); } st1->Remove(h1); // remove tracking on one servref sa2.clear(); st1->GetServiceReferences(sa2); US_TEST_CONDITION_REQUIRED(sa2.size() == 2, "Check service reference count"); // 18. Test the addingService method,add a service reference // 19. Test the removedService method, remove a service reference // 20. Test the waitForService method US_BASECLASS_NAME* o9 = st1->WaitForService(50); US_TEST_CONDITION_REQUIRED(o9 != 0, "Checking WaitForService method"); US_TEST_END() } <|endoftext|>
<commit_before>/** * @allknn_test.cc * Test file for AllkNN class */ #include "allknn.h" #include "fastlib/base/test.h" #include <armadillo> using namespace mlpack::allknn; namespace mlpack { namespace allknn { class TestAllkNN { public: void Init() { // allknn_ = new AllkNN(); // naive_ = new AllkNN(); if(data::Load("test_data_3_1000.csv", data_for_tree_) != SUCCESS_PASS) FATAL("Unable to load test dataset."); } void Destruct() { delete allknn_; delete naive_; } void TestDualTreeVsNaive1() { Init(); arma::mat dual_query(data_for_tree_); arma::mat dual_references(data_for_tree_); arma::mat naive_query(data_for_tree_); arma::mat naive_references(data_for_tree_); allknn_ = new AllkNN(dual_query, dual_references, 20, 5); naive_ = new AllkNN(naive_query, naive_references, 1 /* leaf_size ignored */, 5, AllkNN::NAIVE); arma::Col<index_t> resulting_neighbors_tree; arma::vec distances_tree; allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree); arma::Col<index_t> resulting_neighbors_naive; arma::vec distances_naive; naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive); for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) { TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]); TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5); } NOTIFY("AllkNN test 1 passed."); Destruct(); } void TestDualTreeVsNaive2() { arma::mat dual_query(data_for_tree_); arma::mat naive_query(data_for_tree_); allknn_ = new AllkNN(dual_query, 20, 1); naive_ = new AllkNN(naive_query, 1 /* leaf_size ignored with naive */, 1, AllkNN::NAIVE); arma::Col<index_t> resulting_neighbors_tree; arma::vec distances_tree; allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree); arma::Col<index_t> resulting_neighbors_naive; arma::vec distances_naive; naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive); for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) { TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]); TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5); } NOTIFY("AllkNN test 2 passed."); Destruct(); } void TestSingleTreeVsNaive() { arma::mat single_query(data_for_tree_); arma::mat naive_query(data_for_tree_); allknn_ = new AllkNN(single_query, 20, 5, AllkNN::MODE_SINGLE); naive_ = new AllkNN(naive_query, 1 /* leaf_size ignored with naive */, 5, AllkNN::NAIVE); arma::Col<index_t> resulting_neighbors_tree; arma::vec distances_tree; allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree); arma::Col<index_t> resulting_neighbors_naive; arma::vec distances_naive; naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive); for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) { TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]); TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5); } NOTIFY("AllkNN test 3 passed."); Destruct(); } void TestAll() { TestDualTreeVsNaive1(); TestDualTreeVsNaive2(); TestSingleTreeVsNaive(); } private: AllkNN *allknn_; AllkNN *naive_; arma::mat data_for_tree_; }; }; // namespace allknn }; // namespace mlpack int main(int argc, char* argv[]) { fx_root = fx_init(argc, argv, NULL); TestAllkNN test; test.TestAll(); fx_done(fx_root); } <commit_msg>Do not use local include<commit_after>/** * @allknn_test.cc * Test file for AllkNN class */ #include "allknn.h" #include <fastlib/base/test.h> #include <armadillo> using namespace mlpack::allknn; namespace mlpack { namespace allknn { class TestAllkNN { public: void Init() { // allknn_ = new AllkNN(); // naive_ = new AllkNN(); if(data::Load("test_data_3_1000.csv", data_for_tree_) != SUCCESS_PASS) FATAL("Unable to load test dataset."); } void Destruct() { delete allknn_; delete naive_; } void TestDualTreeVsNaive1() { Init(); arma::mat dual_query(data_for_tree_); arma::mat dual_references(data_for_tree_); arma::mat naive_query(data_for_tree_); arma::mat naive_references(data_for_tree_); allknn_ = new AllkNN(dual_query, dual_references, 20, 5); naive_ = new AllkNN(naive_query, naive_references, 1 /* leaf_size ignored */, 5, AllkNN::NAIVE); arma::Col<index_t> resulting_neighbors_tree; arma::vec distances_tree; allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree); arma::Col<index_t> resulting_neighbors_naive; arma::vec distances_naive; naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive); for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) { TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]); TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5); } NOTIFY("AllkNN test 1 passed."); Destruct(); } void TestDualTreeVsNaive2() { arma::mat dual_query(data_for_tree_); arma::mat naive_query(data_for_tree_); allknn_ = new AllkNN(dual_query, 20, 1); naive_ = new AllkNN(naive_query, 1 /* leaf_size ignored with naive */, 1, AllkNN::NAIVE); arma::Col<index_t> resulting_neighbors_tree; arma::vec distances_tree; allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree); arma::Col<index_t> resulting_neighbors_naive; arma::vec distances_naive; naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive); for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) { TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]); TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5); } NOTIFY("AllkNN test 2 passed."); Destruct(); } void TestSingleTreeVsNaive() { arma::mat single_query(data_for_tree_); arma::mat naive_query(data_for_tree_); allknn_ = new AllkNN(single_query, 20, 5, AllkNN::MODE_SINGLE); naive_ = new AllkNN(naive_query, 1 /* leaf_size ignored with naive */, 5, AllkNN::NAIVE); arma::Col<index_t> resulting_neighbors_tree; arma::vec distances_tree; allknn_->ComputeNeighbors(resulting_neighbors_tree, distances_tree); arma::Col<index_t> resulting_neighbors_naive; arma::vec distances_naive; naive_->ComputeNeighbors(resulting_neighbors_naive, distances_naive); for (index_t i = 0; i < resulting_neighbors_tree.n_elem; i++) { TEST_ASSERT(resulting_neighbors_tree[i] == resulting_neighbors_naive[i]); TEST_DOUBLE_APPROX(distances_tree[i], distances_naive[i], 1e-5); } NOTIFY("AllkNN test 3 passed."); Destruct(); } void TestAll() { TestDualTreeVsNaive1(); TestDualTreeVsNaive2(); TestSingleTreeVsNaive(); } private: AllkNN *allknn_; AllkNN *naive_; arma::mat data_for_tree_; }; }; // namespace allknn }; // namespace mlpack int main(int argc, char* argv[]) { fx_root = fx_init(argc, argv, NULL); TestAllkNN test; test.TestAll(); fx_done(fx_root); } <|endoftext|>
<commit_before>/* * Copyright (c) 2018, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "UBLOX_AT.h" using namespace mbed; using namespace events; #ifdef TARGET_UBLOX_C030_R41XM static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = { AT_CellularNetwork::RegistrationModeDisable,// C_EREG AT_CellularNetwork::RegistrationModeLAC, // C_GREG AT_CellularNetwork::RegistrationModeLAC, // C_REG 0, // AT_CGSN_WITH_TYPE 1, // AT_CGDATA 1, // AT_CGAUTH 1, // AT_CNMI 1, // AT_CSMP 1, // AT_CMGF 1, // AT_CSDH 1, // PROPERTY_IPV4_STACK 0, // PROPERTY_IPV6_STACK 0, // PROPERTY_IPV4V6_STACK 0, // PROPERTY_NON_IP_PDP_TYPE 1, // PROPERTY_AT_CGEREP }; #else static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = { AT_CellularNetwork::RegistrationModeDisable,// C_EREG AT_CellularNetwork::RegistrationModeLAC, // C_GREG AT_CellularNetwork::RegistrationModeLAC, // C_REG 1, // AT_CGSN_WITH_TYPE 1, // AT_CGDATA 1, // AT_CGAUTH 1, // AT_CNMI 1, // AT_CSMP 1, // AT_CMGF 1, // AT_CSDH 1, // PROPERTY_IPV4_STACK 0, // PROPERTY_IPV6_STACK 0, // PROPERTY_IPV4V6_STACK 0, // PROPERTY_NON_IP_PDP_TYPE 1, // PROPERTY_AT_CGEREP }; #endif UBLOX_AT::UBLOX_AT(FileHandle *fh) : AT_CellularDevice(fh) { AT_CellularBase::set_cellular_properties(cellular_properties); } AT_CellularNetwork *UBLOX_AT::open_network_impl(ATHandler &at) { return new UBLOX_AT_CellularNetwork(at); } AT_CellularContext *UBLOX_AT::create_context_impl(ATHandler &at, const char *apn, bool cp_req, bool nonip_req) { ubx_context = new UBLOX_AT_CellularContext(at, this, apn, cp_req, nonip_req); return ubx_context; } #if MBED_CONF_UBLOX_AT_PROVIDE_DEFAULT #include "UARTSerial.h" CellularDevice *CellularDevice::get_default_instance() { static UARTSerial serial(MBED_CONF_UBLOX_AT_TX, MBED_CONF_UBLOX_AT_RX, MBED_CONF_UBLOX_AT_BAUDRATE); #if defined (MBED_CONF_UBLOX_AT_RTS) && defined(MBED_CONF_UBLOX_AT_CTS) tr_debug("UBLOX_AT flow control: RTS %d CTS %d", MBED_CONF_UBLOX_AT_RTS, MBED_CONF_UBLOX_AT_CTS); serial.set_flow_control(SerialBase::RTSCTS, MBED_CONF_UBLOX_AT_RTS, MBED_CONF_UBLOX_AT_CTS); #endif static UBLOX_AT device(&serial); return &device; } #endif nsapi_error_t UBLOX_AT::init() { setup_at_handler(); _at->lock(); _at->flush(); _at->at_cmd_discard("", ""); nsapi_error_t err = NSAPI_ERROR_OK; #ifdef TARGET_UBLOX_C027 err = _at->at_cmd_discard("+CFUN", "=0"); if (err == NSAPI_ERROR_OK) { _at->at_cmd_discard("E0", ""); // echo off _at->at_cmd_discard("+CMEE", "=1"); // verbose responses config_authentication_parameters(); err = _at->at_cmd_discard("+CFUN", "=1"); // set full functionality } #else err = _at->at_cmd_discard("+CFUN", "=4"); if (err == NSAPI_ERROR_OK) { _at->at_cmd_discard("E0", ""); // echo off _at->at_cmd_discard("+CMEE", "=1"); // verbose responses config_authentication_parameters(); err = _at->at_cmd_discard("+CFUN", "=1"); // set full functionality } #endif return _at->unlock_return_error(); } nsapi_error_t UBLOX_AT::config_authentication_parameters() { char *config = NULL; nsapi_error_t err; char imsi[MAX_IMSI_LENGTH + 1]; if (apn == NULL) { err = get_imsi(imsi); if (err == NSAPI_ERROR_OK) { config = (char *)apnconfig(imsi); } } ubx_context->get_next_credentials(&config); apn = ubx_context->get_apn(); pwd = ubx_context->get_pwd(); uname = ubx_context->get_uname(); auth = ubx_context->get_auth(); auth = (*uname && *pwd) ? auth : CellularContext::NOAUTH; err = set_authentication_parameters(apn, uname, pwd, auth); return err; } nsapi_error_t UBLOX_AT::set_authentication_parameters(const char *apn, const char *username, const char *password, CellularContext::AuthenticationType auth) { int modem_security = ubx_context->nsapi_security_to_modem_security(auth); nsapi_error_t err = _at->at_cmd_discard("+CGDCONT", "=", "%d%s%s", 1, "IP", apn); if (err == NSAPI_ERROR_OK) { #ifdef TARGET_UBLOX_C030_R41XM if (modem_security == CellularContext::CHAP) { err = _at->at_cmd_discard("+UAUTHREQ", "=", "%d%d%s%s", 1, modem_security, password, username); } else if (modem_security == CellularContext::NOAUTH) { err = _at->at_cmd_discard("+UAUTHREQ", "=", "%d%d", 1, modem_security); } else { err = _at->at_cmd_discard("+UAUTHREQ", "=", "%d%d%s%s", 1, modem_security, username, password); } #else err = _at->at_cmd_discard("+UAUTHREQ", "=", "%d%d%s%s", 1, modem_security, username, password); #endif } return err; } nsapi_error_t UBLOX_AT::get_imsi(char *imsi) { //Special case: Command put in cmd_chr to make a 1 liner return _at->at_cmd_str("", "+CIMI", imsi, MAX_IMSI_LENGTH + 1); } <commit_msg>fix apn check<commit_after>/* * Copyright (c) 2018, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "UBLOX_AT.h" using namespace mbed; using namespace events; #ifdef TARGET_UBLOX_C030_R41XM static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = { AT_CellularNetwork::RegistrationModeDisable,// C_EREG AT_CellularNetwork::RegistrationModeLAC, // C_GREG AT_CellularNetwork::RegistrationModeLAC, // C_REG 0, // AT_CGSN_WITH_TYPE 1, // AT_CGDATA 1, // AT_CGAUTH 1, // AT_CNMI 1, // AT_CSMP 1, // AT_CMGF 1, // AT_CSDH 1, // PROPERTY_IPV4_STACK 0, // PROPERTY_IPV6_STACK 0, // PROPERTY_IPV4V6_STACK 0, // PROPERTY_NON_IP_PDP_TYPE 1, // PROPERTY_AT_CGEREP }; #else static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = { AT_CellularNetwork::RegistrationModeDisable,// C_EREG AT_CellularNetwork::RegistrationModeLAC, // C_GREG AT_CellularNetwork::RegistrationModeLAC, // C_REG 1, // AT_CGSN_WITH_TYPE 1, // AT_CGDATA 1, // AT_CGAUTH 1, // AT_CNMI 1, // AT_CSMP 1, // AT_CMGF 1, // AT_CSDH 1, // PROPERTY_IPV4_STACK 0, // PROPERTY_IPV6_STACK 0, // PROPERTY_IPV4V6_STACK 0, // PROPERTY_NON_IP_PDP_TYPE 1, // PROPERTY_AT_CGEREP }; #endif UBLOX_AT::UBLOX_AT(FileHandle *fh) : AT_CellularDevice(fh) { AT_CellularBase::set_cellular_properties(cellular_properties); } AT_CellularNetwork *UBLOX_AT::open_network_impl(ATHandler &at) { return new UBLOX_AT_CellularNetwork(at); } AT_CellularContext *UBLOX_AT::create_context_impl(ATHandler &at, const char *apn, bool cp_req, bool nonip_req) { ubx_context = new UBLOX_AT_CellularContext(at, this, apn, cp_req, nonip_req); return ubx_context; } #if MBED_CONF_UBLOX_AT_PROVIDE_DEFAULT #include "UARTSerial.h" CellularDevice *CellularDevice::get_default_instance() { static UARTSerial serial(MBED_CONF_UBLOX_AT_TX, MBED_CONF_UBLOX_AT_RX, MBED_CONF_UBLOX_AT_BAUDRATE); #if defined (MBED_CONF_UBLOX_AT_RTS) && defined(MBED_CONF_UBLOX_AT_CTS) tr_debug("UBLOX_AT flow control: RTS %d CTS %d", MBED_CONF_UBLOX_AT_RTS, MBED_CONF_UBLOX_AT_CTS); serial.set_flow_control(SerialBase::RTSCTS, MBED_CONF_UBLOX_AT_RTS, MBED_CONF_UBLOX_AT_CTS); #endif static UBLOX_AT device(&serial); return &device; } #endif nsapi_error_t UBLOX_AT::init() { setup_at_handler(); _at->lock(); _at->flush(); _at->at_cmd_discard("", ""); nsapi_error_t err = NSAPI_ERROR_OK; #ifdef TARGET_UBLOX_C027 err = _at->at_cmd_discard("+CFUN", "=0"); if (err == NSAPI_ERROR_OK) { _at->at_cmd_discard("E0", ""); // echo off _at->at_cmd_discard("+CMEE", "=1"); // verbose responses config_authentication_parameters(); err = _at->at_cmd_discard("+CFUN", "=1"); // set full functionality } #else err = _at->at_cmd_discard("+CFUN", "=4"); if (err == NSAPI_ERROR_OK) { _at->at_cmd_discard("E0", ""); // echo off _at->at_cmd_discard("+CMEE", "=1"); // verbose responses config_authentication_parameters(); err = _at->at_cmd_discard("+CFUN", "=1"); // set full functionality } #endif return _at->unlock_return_error(); } nsapi_error_t UBLOX_AT::config_authentication_parameters() { char *config = NULL; nsapi_error_t err; char imsi[MAX_IMSI_LENGTH + 1]; if (ubx_context->get_apn() == NULL) { err = get_imsi(imsi); if (err == NSAPI_ERROR_OK) { config = (char *)apnconfig(imsi); } ubx_context->get_next_credentials(&config); } apn = ubx_context->get_apn(); pwd = ubx_context->get_pwd(); uname = ubx_context->get_uname(); auth = ubx_context->get_auth(); auth = (*uname && *pwd) ? auth : CellularContext::NOAUTH; err = set_authentication_parameters(apn, uname, pwd, auth); return err; } nsapi_error_t UBLOX_AT::set_authentication_parameters(const char *apn, const char *username, const char *password, CellularContext::AuthenticationType auth) { int modem_security = ubx_context->nsapi_security_to_modem_security(auth); nsapi_error_t err = _at->at_cmd_discard("+CGDCONT", "=", "%d%s%s", 1, "IP", apn); if (err == NSAPI_ERROR_OK) { #ifdef TARGET_UBLOX_C030_R41XM if (modem_security == CellularContext::CHAP) { err = _at->at_cmd_discard("+UAUTHREQ", "=", "%d%d%s%s", 1, modem_security, password, username); } else if (modem_security == CellularContext::NOAUTH) { err = _at->at_cmd_discard("+UAUTHREQ", "=", "%d%d", 1, modem_security); } else { err = _at->at_cmd_discard("+UAUTHREQ", "=", "%d%d%s%s", 1, modem_security, username, password); } #else err = _at->at_cmd_discard("+UAUTHREQ", "=", "%d%d%s%s", 1, modem_security, username, password); #endif } return err; } nsapi_error_t UBLOX_AT::get_imsi(char *imsi) { //Special case: Command put in cmd_chr to make a 1 liner return _at->at_cmd_str("", "+CIMI", imsi, MAX_IMSI_LENGTH + 1); } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 Akil Darjean ([email protected]) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #include "window.h" #include <SFML/Graphics.hpp> #include <algorithm> #include <boost/filesystem.hpp> #include <exception> #include <future> #include <iostream> #include <iterator> #include <utility> struct path_leaf_string { std::string operator()(const boost::filesystem::directory_entry& entry) const { return entry.path().leaf().string(); } }; Window::Window(const std::string&& filename) { this->isFullscreen = false; this->filename = filename; // Run a seperate thread to get a list of all files in the directory auto f = std::async(std::launch::async, &Window::getFilesInDirectory, this); load(); init(); files = f.get(); draw(); } void Window::load() { sf::Image image; image.loadFromFile(filename); if (!texture.loadFromImage(image)) { throw std::runtime_error("Error: Image not found"); } texture.setSmooth(true); texture.update(image); sprite.setTexture(texture); } void Window::init() { desktop = sf::VideoMode::getDesktopMode(); window.create(sf::VideoMode(640, 480), "SFML Image Viewer"); window.setKeyRepeatEnabled(false); window.setFramerateLimit(framerate); // Initialize view view.reset(sf::FloatRect( 0.0f, 0.0f, static_cast<float>(texture.getSize().x), static_cast<float>(texture.getSize().y))); } void Window::draw() { while (window.isOpen()) { checkEvents(); window.clear(); window.setView(view); window.draw(sprite); window.display(); } } void Window::checkEvents() { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::EventType::Closed: window.close(); break; case sf::Event::EventType::Resized: getLetterboxView(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Q) { window.close(); } if (event.key.code == sf::Keyboard::F) { if (!isFullscreen) { window.create(desktop, "SFML Image Viewer", sf::Style::Fullscreen); } else { window.create(sf::VideoMode(640, 480), "SFML Image Viewer"); } isFullscreen = !isFullscreen; } if ((event.key.code == sf::Keyboard::P) || (event.key.code == sf::Keyboard::N)) { auto it = find(files.begin(), files.end(), filename); if (it != files.end()) { // Get position of current image auto pos = std::distance(files.begin(), it); auto size = static_cast<int>(files.size()); auto original = files.at(pos); if ((event.key.code == sf::Keyboard::P) && (pos > 0)) { filename = files.at(pos - 1); } if ((event.key.code == sf::Keyboard::N) && (pos < (size - 1))) { filename = files.at(pos + 1); } try { load(); } catch (std::exception& e) { files.erase(std::remove(files.begin(), files.end(), filename), files.end()); filename = original; load(); } } } default: break; } } } void Window::getLetterboxView() { float windowRatio = window.getSize().x / static_cast<float>(window.getSize().y); float viewRatio = view.getSize().x / static_cast<float>(view.getSize().y); sf::Vector2f size; sf::Vector2f pos; if (windowRatio > viewRatio) { size.x = viewRatio / windowRatio; pos.x = (1.0f - size.x) / 2.0f; size.y = 1.0f; pos.y = 0.0f; } else { size.y = windowRatio / viewRatio; pos.y = (1.0f - size.y) / 2.0f; size.x = 1.0f; pos.x = 0.0f; } view.setViewport(sf::FloatRect(pos.x, pos.y, size.x, size.y)); } std::vector<std::string> Window::getFilesInDirectory() { std::vector<std::string> v; auto dir = boost::filesystem::current_path(); boost::filesystem::path p(dir); boost::filesystem::directory_iterator start(p); boost::filesystem::directory_iterator end; std::transform(start, end, std::back_inserter(v), path_leaf_string()); std::sort(v.begin(), v.end()); return v; } <commit_msg>Remove iostream library<commit_after>/* * Copyright (c) 2017 Akil Darjean ([email protected]) * Distributed under the MIT License. * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT */ #include "window.h" #include <SFML/Graphics.hpp> #include <algorithm> #include <boost/filesystem.hpp> #include <exception> #include <future> #include <iterator> #include <utility> struct path_leaf_string { std::string operator()(const boost::filesystem::directory_entry& entry) const { return entry.path().leaf().string(); } }; Window::Window(const std::string&& filename) { this->isFullscreen = false; this->filename = filename; // Run a seperate thread to get a list of all files in the directory auto f = std::async(std::launch::async, &Window::getFilesInDirectory, this); load(); init(); files = f.get(); draw(); } void Window::load() { sf::Image image; image.loadFromFile(filename); if (!texture.loadFromImage(image)) { throw std::runtime_error("Error: Image not found"); } texture.setSmooth(true); texture.update(image); sprite.setTexture(texture); } void Window::init() { desktop = sf::VideoMode::getDesktopMode(); window.create(sf::VideoMode(640, 480), "SFML Image Viewer"); window.setKeyRepeatEnabled(false); window.setFramerateLimit(framerate); // Initialize view view.reset(sf::FloatRect( 0.0f, 0.0f, static_cast<float>(texture.getSize().x), static_cast<float>(texture.getSize().y))); } void Window::draw() { while (window.isOpen()) { checkEvents(); window.clear(); window.setView(view); window.draw(sprite); window.display(); } } void Window::checkEvents() { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::EventType::Closed: window.close(); break; case sf::Event::EventType::Resized: getLetterboxView(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Q) { window.close(); } if (event.key.code == sf::Keyboard::F) { if (!isFullscreen) { window.create(desktop, "SFML Image Viewer", sf::Style::Fullscreen); } else { window.create(sf::VideoMode(640, 480), "SFML Image Viewer"); } isFullscreen = !isFullscreen; } if ((event.key.code == sf::Keyboard::P) || (event.key.code == sf::Keyboard::N)) { auto it = find(files.begin(), files.end(), filename); if (it != files.end()) { // Get position of current image auto pos = std::distance(files.begin(), it); auto size = static_cast<int>(files.size()); auto original = files.at(pos); if ((event.key.code == sf::Keyboard::P) && (pos > 0)) { filename = files.at(pos - 1); } if ((event.key.code == sf::Keyboard::N) && (pos < (size - 1))) { filename = files.at(pos + 1); } try { load(); } catch (std::exception& e) { files.erase(std::remove(files.begin(), files.end(), filename), files.end()); filename = original; load(); } } } default: break; } } } void Window::getLetterboxView() { float windowRatio = window.getSize().x / static_cast<float>(window.getSize().y); float viewRatio = view.getSize().x / static_cast<float>(view.getSize().y); sf::Vector2f size; sf::Vector2f pos; if (windowRatio > viewRatio) { size.x = viewRatio / windowRatio; pos.x = (1.0f - size.x) / 2.0f; size.y = 1.0f; pos.y = 0.0f; } else { size.y = windowRatio / viewRatio; pos.y = (1.0f - size.y) / 2.0f; size.x = 1.0f; pos.x = 0.0f; } view.setViewport(sf::FloatRect(pos.x, pos.y, size.x, size.y)); } std::vector<std::string> Window::getFilesInDirectory() { std::vector<std::string> v; auto dir = boost::filesystem::current_path(); boost::filesystem::path p(dir); boost::filesystem::directory_iterator start(p); boost::filesystem::directory_iterator end; std::transform(start, end, std::back_inserter(v), path_leaf_string()); std::sort(v.begin(), v.end()); return v; } <|endoftext|>
<commit_before>#include <QtGui> #include "window.h" SettingsTab::SettingsTab(QWidget *parent) : QWidget(parent) { QLabel *usernameLabel = new QLabel(tr("Username:")); username = new QLineEdit; usernameLabel->setBuddy(username); QLabel *passwordLabel = new QLabel(tr("Password:")); password = new QLineEdit; passwordLabel->setBuddy(password); QLabel *webserviceUrlLabel = new QLabel(tr("Webservice URL:")); webserviceUrl = new QLineEdit; webserviceUrlLabel->setBuddy(webserviceUrl); QGridLayout *layout = new QGridLayout; setLayout(layout); layout->setVerticalSpacing(15); layout->addWidget(webserviceUrlLabel, 0, 0); layout->addWidget(webserviceUrl, 0, 1); layout->addWidget(usernameLabel, 1, 0); layout->addWidget(username, 1, 1); layout->addWidget(passwordLabel, 2, 0); #ifndef _DEBUG webserviceUrlLabel->hide(); webserviceUrl->hide(); #endif QHBoxLayout *row = new QHBoxLayout; QPushButton *revealButton = new QPushButton(tr("Reveal")); connect(revealButton, SIGNAL(clicked()), this, SLOT(reveal())); row->addWidget(password); row->addWidget(revealButton); layout->addLayout(row, 2, 1); QFrame *line = new QFrame; line->setObjectName(QString::fromUtf8("line")); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); layout->addWidget(line, 3, 0, 1, 3); QLabel *systemLabel = new QLabel(tr("System:")); layout->addWidget(systemLabel, 5, 0); startAtLogin = new QCheckBox(tr("Start at Login")); layout->addWidget(startAtLogin, 5, 1); QSpacerItem *spacer = new QSpacerItem(40, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); layout->addItem(spacer, 6, 0); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(ok())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(cancel())); layout->addWidget(buttonBox, 7, 0, 1, 3); } void SettingsTab::reveal() { password->setEchoMode(QLineEdit::Normal); } void SettingsTab::conceal() { password->setEchoMode(QLineEdit::Password); } void SettingsTab::updateSettings() { Autostart autostart; username->setText(Tracker::Instance()->Username()); password->setText(Tracker::Instance()->Password()); webserviceUrl->setText(Tracker::Instance()->WebserviceURL()); conceal(); startAtLogin->setChecked(autostart.IsActive()); } void SettingsTab::applySettings() { Autostart autostart; Tracker::Instance()->SetUsername(username->text()); Tracker::Instance()->SetPassword(password->text()); Tracker::Instance()->SetWebserviceURL(webserviceUrl->text()); autostart.SetActive(startAtLogin->isChecked()); } void SettingsTab::ok() { applySettings(); window()->hide(); } void SettingsTab::cancel() { window()->hide(); } LogTab::LogTab(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout; logText = new QTextEdit; logText->setReadOnly(true); layout->addWidget(logText); setLayout(layout); connect(Logger::Instance(), SIGNAL(NewMessage(const string&)), this, SLOT(addLogEntry(const string&))); } void LogTab::addLogEntry(const string& msg) { logText->moveCursor(QTextCursor::End); logText->insertPlainText(msg.c_str()); logText->moveCursor(QTextCursor::End); } AboutTab::AboutTab(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout; QSpacerItem *topSpacer = new QSpacerItem(40, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); QSpacerItem *bottomSpacer = new QSpacerItem(40, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); QLabel *name = new QLabel(qApp->applicationName()); name->setStyleSheet("QLabel { font-size: 20px; }"); name->setAlignment(Qt::AlignHCenter); QLabel *version = new QLabel(VERSION); version->setAlignment(Qt::AlignHCenter); QPixmap logoImage(":/icons/logo.png"); QLabel *logo = new QLabel(); logo->setAlignment(Qt::AlignHCenter); logo->setPixmap(logoImage.scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation)); layout->addItem(topSpacer); layout->addWidget(logo); layout->addWidget(name); layout->addWidget(version); layout->addItem(bottomSpacer); setLayout(layout); } Window::Window() { setWindowTitle(qApp->applicationName()); Qt::WindowFlags flags = windowFlags(); flags |= Qt::CustomizeWindowHint; flags &= ~Qt::WindowMaximizeButtonHint; setWindowFlags(flags); createActions(); createTrayIcon(); tabWidget = new QTabWidget; settingsTab = new SettingsTab; logTab = new LogTab; aboutTab = new AboutTab; tabWidget->addTab(settingsTab, tr("Settings")); tabWidget->addTab(logTab, tr("Log")); tabWidget->addTab(aboutTab, tr("About")); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setSizeConstraint(QLayout::SetNoConstraint); mainLayout->addWidget(tabWidget); setLayout(mainLayout); setFixedSize(420, 250); } Window::~Window() { } void Window::showEvent(QShowEvent *event) { QDialog::showEvent(event); settingsTab->updateSettings(); } void Window::closeEvent(QCloseEvent *event) { if(trayIcon->isVisible()) { hide(); event->ignore(); } } // prevent esc from closing the app void Window::reject() { if(trayIcon->isVisible()) { hide(); } else { QDialog::reject(); } } void Window::createActions() { openProfileAction = new QAction(tr("Open Profile..."), this); connect(openProfileAction, SIGNAL(triggered()), this, SLOT(openProfile())); showAction = new QAction(tr("Settings..."), this); connect(showAction, SIGNAL(triggered()), this, SLOT(riseAndShine())); quitAction = new QAction(tr("Quit"), this); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } void Window::createTrayIcon() { trayIconMenu = new QMenu(this); trayIconMenu->addAction(openProfileAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(showAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); trayIcon = new QSystemTrayIcon(this); trayIcon->setContextMenu(trayIconMenu); #ifdef Q_WS_MAC QIcon icon = QIcon(":/icons/tray_mac.png"); icon.addFile(":/icons/tray_mac_selected.png", QSize(), QIcon::Selected); #elif defined Q_WS_WIN QIcon icon = QIcon(":/icons/tray_win.png"); #endif trayIcon->setIcon(icon); trayIcon->show(); } void Window::riseAndShine() { show(); raise(); } void Window::openProfile() { Tracker::Instance()->OpenProfile(); } <commit_msg>fix inconsistent OSX window display when using Qt::CustomizeWindowHint<commit_after>#include <QtGui> #include "window.h" SettingsTab::SettingsTab(QWidget *parent) : QWidget(parent) { QLabel *usernameLabel = new QLabel(tr("Username:")); username = new QLineEdit; usernameLabel->setBuddy(username); QLabel *passwordLabel = new QLabel(tr("Password:")); password = new QLineEdit; passwordLabel->setBuddy(password); QLabel *webserviceUrlLabel = new QLabel(tr("Webservice URL:")); webserviceUrl = new QLineEdit; webserviceUrlLabel->setBuddy(webserviceUrl); QGridLayout *layout = new QGridLayout; setLayout(layout); layout->setVerticalSpacing(15); layout->addWidget(webserviceUrlLabel, 0, 0); layout->addWidget(webserviceUrl, 0, 1); layout->addWidget(usernameLabel, 1, 0); layout->addWidget(username, 1, 1); layout->addWidget(passwordLabel, 2, 0); #ifndef _DEBUG webserviceUrlLabel->hide(); webserviceUrl->hide(); #endif QHBoxLayout *row = new QHBoxLayout; QPushButton *revealButton = new QPushButton(tr("Reveal")); connect(revealButton, SIGNAL(clicked()), this, SLOT(reveal())); row->addWidget(password); row->addWidget(revealButton); layout->addLayout(row, 2, 1); QFrame *line = new QFrame; line->setObjectName(QString::fromUtf8("line")); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); layout->addWidget(line, 3, 0, 1, 3); QLabel *systemLabel = new QLabel(tr("System:")); layout->addWidget(systemLabel, 5, 0); startAtLogin = new QCheckBox(tr("Start at Login")); layout->addWidget(startAtLogin, 5, 1); QSpacerItem *spacer = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); layout->addItem(spacer, 6, 0); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(ok())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(cancel())); layout->addWidget(buttonBox, 7, 0, 1, 3); } void SettingsTab::reveal() { password->setEchoMode(QLineEdit::Normal); } void SettingsTab::conceal() { password->setEchoMode(QLineEdit::Password); } void SettingsTab::updateSettings() { Autostart autostart; username->setText(Tracker::Instance()->Username()); password->setText(Tracker::Instance()->Password()); webserviceUrl->setText(Tracker::Instance()->WebserviceURL()); conceal(); startAtLogin->setChecked(autostart.IsActive()); } void SettingsTab::applySettings() { Autostart autostart; Tracker::Instance()->SetUsername(username->text()); Tracker::Instance()->SetPassword(password->text()); Tracker::Instance()->SetWebserviceURL(webserviceUrl->text()); autostart.SetActive(startAtLogin->isChecked()); } void SettingsTab::ok() { applySettings(); window()->hide(); } void SettingsTab::cancel() { window()->hide(); } LogTab::LogTab(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout; logText = new QTextEdit; logText->setReadOnly(true); layout->addWidget(logText); setLayout(layout); connect(Logger::Instance(), SIGNAL(NewMessage(const string&)), this, SLOT(addLogEntry(const string&))); } void LogTab::addLogEntry(const string& msg) { logText->moveCursor(QTextCursor::End); logText->insertPlainText(msg.c_str()); logText->moveCursor(QTextCursor::End); } AboutTab::AboutTab(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout; QSpacerItem *topSpacer = new QSpacerItem(40, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); QSpacerItem *bottomSpacer = new QSpacerItem(40, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); QLabel *name = new QLabel(qApp->applicationName()); name->setStyleSheet("QLabel { font-size: 20px; }"); name->setAlignment(Qt::AlignHCenter); QLabel *version = new QLabel(VERSION); version->setAlignment(Qt::AlignHCenter); QPixmap logoImage(":/icons/logo.png"); QLabel *logo = new QLabel(); logo->setAlignment(Qt::AlignHCenter); logo->setPixmap(logoImage.scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation)); layout->addItem(topSpacer); layout->addWidget(logo); layout->addWidget(name); layout->addWidget(version); layout->addItem(bottomSpacer); setLayout(layout); } Window::Window() { setWindowTitle(qApp->applicationName()); createActions(); createTrayIcon(); tabWidget = new QTabWidget; settingsTab = new SettingsTab; logTab = new LogTab; aboutTab = new AboutTab; tabWidget->addTab(settingsTab, tr("Settings")); tabWidget->addTab(logTab, tr("Log")); tabWidget->addTab(aboutTab, tr("About")); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setSizeConstraint(QLayout::SetNoConstraint); mainLayout->addWidget(tabWidget); setLayout(mainLayout); setMinimumSize(450, 250); resize(minimumSize()); } Window::~Window() { } void Window::showEvent(QShowEvent *event) { QDialog::showEvent(event); settingsTab->updateSettings(); } void Window::closeEvent(QCloseEvent *event) { if(trayIcon->isVisible()) { hide(); event->ignore(); } } // prevent esc from closing the app void Window::reject() { if(trayIcon->isVisible()) { hide(); } else { QDialog::reject(); } } void Window::createActions() { openProfileAction = new QAction(tr("Open Profile..."), this); connect(openProfileAction, SIGNAL(triggered()), this, SLOT(openProfile())); showAction = new QAction(tr("Settings..."), this); connect(showAction, SIGNAL(triggered()), this, SLOT(riseAndShine())); quitAction = new QAction(tr("Quit"), this); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); } void Window::createTrayIcon() { trayIconMenu = new QMenu(this); trayIconMenu->addAction(openProfileAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(showAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); trayIcon = new QSystemTrayIcon(this); trayIcon->setContextMenu(trayIconMenu); #ifdef Q_WS_MAC QIcon icon = QIcon(":/icons/tray_mac.png"); icon.addFile(":/icons/tray_mac_selected.png", QSize(), QIcon::Selected); #elif defined Q_WS_WIN QIcon icon = QIcon(":/icons/tray_win.png"); #endif trayIcon->setIcon(icon); trayIcon->show(); } void Window::riseAndShine() { show(); raise(); } void Window::openProfile() { Tracker::Instance()->OpenProfile(); } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "util/file_utils.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <dirent.h> #include <sstream> #include <algorithm> #include <iomanip> #include <boost/filesystem.hpp> #include <boost/system/error_code.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/trim.hpp> #include <openssl/md5.h> #include "olap/file_helper.h" #include "util/defer_op.h" namespace doris { Status FileUtils::create_dir(const std::string& dir_path) { try { if (boost::filesystem::exists(dir_path.c_str())) { // No need to create one if (!boost::filesystem::is_directory(dir_path.c_str())) { std::stringstream ss; ss << "Path(" << dir_path << ") already exists, but not a directory."; return Status(ss.str()); } } else { if (!boost::filesystem::create_directories(dir_path.c_str())) { std::stringstream ss; ss << "make directory failed. path=" << dir_path; return Status(ss.str()); } } } catch (...) { std::stringstream ss; ss << "make directory failed. path=" << dir_path; return Status(ss.str()); } return Status::OK; } Status FileUtils::remove_all(const std::string& file_path) { try { boost::filesystem::path boost_path(file_path); boost::system::error_code ec; boost::filesystem::remove_all(boost_path, ec); if (ec != boost::system::errc::success) { std::stringstream ss; ss << "remove all(" << file_path << ") failed, because: " << ec; return Status(ss.str()); } } catch (...) { std::stringstream ss; ss << "remove all(" << file_path << ") failed, because: exception"; return Status(ss.str()); } return Status::OK; } Status FileUtils::scan_dir( const std::string& dir_path, std::vector<std::string>* files, int64_t* file_count) { DIR* dir = opendir(dir_path.c_str()); if (dir == nullptr) { char buf[64]; std::stringstream ss; ss << "opendir(" << dir_path << ") failed, because: " << strerror_r(errno, buf, 64); return Status(ss.str()); } DeferOp close_dir(std::bind<void>(&closedir, dir)); int64_t count = 0; while (true) { auto result = readdir(dir.get()); if (result == nullptr) { break; } std::string file_name = result->d_name; if (file_name == "." || file_name == "..") { continue; } if (files != nullptr) { files->emplace_back(std::move(file_name)); } count++; } if (file_count != nullptr) { *file_count = count; } return Status::OK; } Status FileUtils::scan_dir( const std::string& dir_path, const std::function<bool(const std::string&, const std::string&)>& callback) { auto dir_closer = [] (DIR* dir) { closedir(dir); }; std::unique_ptr<DIR, decltype(dir_closer)> dir(opendir(dir_path.c_str()), dir_closer); if (dir == nullptr) { char buf[64]; LOG(WARNING) << "fail to open dir, dir=" << dir_path << ", errmsg=" << strerror_r(errno, buf, 64); return Status("fail to opendir"); } struct dirent* result = nullptr; while (true) { auto result = readdir(dir.get()); if (result == nullptr) { break; } std::string file_name = result->d_name; if (file_name == "." || file_name == "..") { continue; } auto is_continue = callback(dir_path, file_name); if (!is_continue) { break; } } return Status::OK; } bool FileUtils::is_dir(const std::string& path) { struct stat path_stat; if (stat(path.c_str(), &path_stat) != 0) { return false; } if (path_stat.st_mode & S_IFDIR) { return true; } return false; } // Through proc filesystem std::string FileUtils::path_of_fd(int fd) { const int PATH_SIZE = 256; char proc_path[PATH_SIZE]; snprintf(proc_path, PATH_SIZE, "/proc/self/fd/%d", fd); char path[PATH_SIZE]; if (readlink(proc_path, path, PATH_SIZE) < 0) { path[0] = '\0'; } return path; } Status FileUtils::split_pathes(const char* path, std::vector<std::string>* path_vec) { path_vec->clear(); try { boost::split(*path_vec, path, boost::is_any_of(";"), boost::token_compress_on); } catch (...) { std::stringstream ss; ss << "Boost split path failed.[path=" << path << "]"; return Status(ss.str()); } for (std::vector<std::string>::iterator it = path_vec->begin(); it != path_vec->end();) { boost::trim(*it); it->erase(it->find_last_not_of("/") + 1); if (it->size() == 0) { it = path_vec->erase(it); } else { ++it; } } // Check if std::sort(path_vec->begin(), path_vec->end()); if (std::unique(path_vec->begin(), path_vec->end()) != path_vec->end()) { std::stringstream ss; ss << "Same path in path.[path=" << path << "]"; return Status(ss.str()); } if (path_vec->size() == 0) { std::stringstream ss; ss << "Size of vector after split is zero.[path=" << path << "]"; return Status(ss.str()); } return Status::OK; } Status FileUtils::copy_file(const std::string& src_path, const std::string& dest_path) { // open src file FileHandler src_file; if (src_file.open(src_path.c_str(), O_RDONLY) != OLAP_SUCCESS) { char errmsg[64]; LOG(ERROR) << "open file failed: " << src_path << strerror_r(errno, errmsg, 64); return Status("Internal Error"); } // create dest file and overwrite existing file FileHandler dest_file; if (dest_file.open_with_mode(dest_path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, S_IRWXU) != OLAP_SUCCESS) { char errmsg[64]; LOG(ERROR) << "open file failed: " << dest_path << strerror_r(errno, errmsg, 64); return Status("Internal Error"); } const int64_t BUF_SIZE = 8192; char *buf = new char[BUF_SIZE]; DeferOp free_buf(std::bind<void>(std::default_delete<char[]>(), buf)); int64_t src_length = src_file.length(); int64_t offset = 0; while (src_length > 0) { int64_t to_read = BUF_SIZE < src_length ? BUF_SIZE : src_length; if (OLAP_SUCCESS != (src_file.pread(buf, to_read, offset))) { return Status("Internal Error"); } if (OLAP_SUCCESS != (dest_file.pwrite(buf, to_read, offset))) { return Status("Internal Error"); } offset += to_read; src_length -= to_read; } return Status::OK; } Status FileUtils::md5sum(const std::string& file, std::string* md5sum) { int fd = open(file.c_str(), O_RDONLY); if (fd < 0) { return Status("failed to open file"); } struct stat statbuf; if (fstat(fd, &statbuf) < 0) { close(fd); return Status("failed to stat file"); } size_t file_len = statbuf.st_size; void* buf = mmap(0, file_len, PROT_READ, MAP_SHARED, fd, 0); unsigned char result[MD5_DIGEST_LENGTH]; MD5((unsigned char*) buf, file_len, result); munmap(buf, file_len); std::stringstream ss; for (int32_t i = 0; i < MD5_DIGEST_LENGTH; i++) { ss << std::setfill('0') << std::setw(2) << std::hex << (int) result[i]; } ss >> *md5sum; close(fd); return Status::OK; } bool FileUtils::check_exist(const std::string& path) { boost::system::error_code errcode; bool exist = boost::filesystem::exists(path, errcode); if (errcode != boost::system::errc::success && errcode != boost::system::errc::no_such_file_or_directory) { LOG(WARNING) << "error when check path:" << path << ", error code:" << errcode; return false; } return exist; } } <commit_msg>Fix compile error (#461)<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "util/file_utils.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <dirent.h> #include <sstream> #include <algorithm> #include <iomanip> #include <boost/filesystem.hpp> #include <boost/system/error_code.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/trim.hpp> #include <openssl/md5.h> #include "olap/file_helper.h" #include "util/defer_op.h" namespace doris { Status FileUtils::create_dir(const std::string& dir_path) { try { if (boost::filesystem::exists(dir_path.c_str())) { // No need to create one if (!boost::filesystem::is_directory(dir_path.c_str())) { std::stringstream ss; ss << "Path(" << dir_path << ") already exists, but not a directory."; return Status(ss.str()); } } else { if (!boost::filesystem::create_directories(dir_path.c_str())) { std::stringstream ss; ss << "make directory failed. path=" << dir_path; return Status(ss.str()); } } } catch (...) { std::stringstream ss; ss << "make directory failed. path=" << dir_path; return Status(ss.str()); } return Status::OK; } Status FileUtils::remove_all(const std::string& file_path) { try { boost::filesystem::path boost_path(file_path); boost::system::error_code ec; boost::filesystem::remove_all(boost_path, ec); if (ec != boost::system::errc::success) { std::stringstream ss; ss << "remove all(" << file_path << ") failed, because: " << ec; return Status(ss.str()); } } catch (...) { std::stringstream ss; ss << "remove all(" << file_path << ") failed, because: exception"; return Status(ss.str()); } return Status::OK; } Status FileUtils::scan_dir( const std::string& dir_path, std::vector<std::string>* files, int64_t* file_count) { DIR* dir = opendir(dir_path.c_str()); if (dir == nullptr) { char buf[64]; std::stringstream ss; ss << "opendir(" << dir_path << ") failed, because: " << strerror_r(errno, buf, 64); return Status(ss.str()); } DeferOp close_dir(std::bind<void>(&closedir, dir)); int64_t count = 0; while (true) { auto result = readdir(dir); if (result == nullptr) { break; } std::string file_name = result->d_name; if (file_name == "." || file_name == "..") { continue; } if (files != nullptr) { files->emplace_back(std::move(file_name)); } count++; } if (file_count != nullptr) { *file_count = count; } return Status::OK; } Status FileUtils::scan_dir( const std::string& dir_path, const std::function<bool(const std::string&, const std::string&)>& callback) { auto dir_closer = [] (DIR* dir) { closedir(dir); }; std::unique_ptr<DIR, decltype(dir_closer)> dir(opendir(dir_path.c_str()), dir_closer); if (dir == nullptr) { char buf[64]; LOG(WARNING) << "fail to open dir, dir=" << dir_path << ", errmsg=" << strerror_r(errno, buf, 64); return Status("fail to opendir"); } while (true) { auto result = readdir(dir.get()); if (result == nullptr) { break; } std::string file_name = result->d_name; if (file_name == "." || file_name == "..") { continue; } auto is_continue = callback(dir_path, file_name); if (!is_continue) { break; } } return Status::OK; } bool FileUtils::is_dir(const std::string& path) { struct stat path_stat; if (stat(path.c_str(), &path_stat) != 0) { return false; } if (path_stat.st_mode & S_IFDIR) { return true; } return false; } // Through proc filesystem std::string FileUtils::path_of_fd(int fd) { const int PATH_SIZE = 256; char proc_path[PATH_SIZE]; snprintf(proc_path, PATH_SIZE, "/proc/self/fd/%d", fd); char path[PATH_SIZE]; if (readlink(proc_path, path, PATH_SIZE) < 0) { path[0] = '\0'; } return path; } Status FileUtils::split_pathes(const char* path, std::vector<std::string>* path_vec) { path_vec->clear(); try { boost::split(*path_vec, path, boost::is_any_of(";"), boost::token_compress_on); } catch (...) { std::stringstream ss; ss << "Boost split path failed.[path=" << path << "]"; return Status(ss.str()); } for (std::vector<std::string>::iterator it = path_vec->begin(); it != path_vec->end();) { boost::trim(*it); it->erase(it->find_last_not_of("/") + 1); if (it->size() == 0) { it = path_vec->erase(it); } else { ++it; } } // Check if std::sort(path_vec->begin(), path_vec->end()); if (std::unique(path_vec->begin(), path_vec->end()) != path_vec->end()) { std::stringstream ss; ss << "Same path in path.[path=" << path << "]"; return Status(ss.str()); } if (path_vec->size() == 0) { std::stringstream ss; ss << "Size of vector after split is zero.[path=" << path << "]"; return Status(ss.str()); } return Status::OK; } Status FileUtils::copy_file(const std::string& src_path, const std::string& dest_path) { // open src file FileHandler src_file; if (src_file.open(src_path.c_str(), O_RDONLY) != OLAP_SUCCESS) { char errmsg[64]; LOG(ERROR) << "open file failed: " << src_path << strerror_r(errno, errmsg, 64); return Status("Internal Error"); } // create dest file and overwrite existing file FileHandler dest_file; if (dest_file.open_with_mode(dest_path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, S_IRWXU) != OLAP_SUCCESS) { char errmsg[64]; LOG(ERROR) << "open file failed: " << dest_path << strerror_r(errno, errmsg, 64); return Status("Internal Error"); } const int64_t BUF_SIZE = 8192; char *buf = new char[BUF_SIZE]; DeferOp free_buf(std::bind<void>(std::default_delete<char[]>(), buf)); int64_t src_length = src_file.length(); int64_t offset = 0; while (src_length > 0) { int64_t to_read = BUF_SIZE < src_length ? BUF_SIZE : src_length; if (OLAP_SUCCESS != (src_file.pread(buf, to_read, offset))) { return Status("Internal Error"); } if (OLAP_SUCCESS != (dest_file.pwrite(buf, to_read, offset))) { return Status("Internal Error"); } offset += to_read; src_length -= to_read; } return Status::OK; } Status FileUtils::md5sum(const std::string& file, std::string* md5sum) { int fd = open(file.c_str(), O_RDONLY); if (fd < 0) { return Status("failed to open file"); } struct stat statbuf; if (fstat(fd, &statbuf) < 0) { close(fd); return Status("failed to stat file"); } size_t file_len = statbuf.st_size; void* buf = mmap(0, file_len, PROT_READ, MAP_SHARED, fd, 0); unsigned char result[MD5_DIGEST_LENGTH]; MD5((unsigned char*) buf, file_len, result); munmap(buf, file_len); std::stringstream ss; for (int32_t i = 0; i < MD5_DIGEST_LENGTH; i++) { ss << std::setfill('0') << std::setw(2) << std::hex << (int) result[i]; } ss >> *md5sum; close(fd); return Status::OK; } bool FileUtils::check_exist(const std::string& path) { boost::system::error_code errcode; bool exist = boost::filesystem::exists(path, errcode); if (errcode != boost::system::errc::success && errcode != boost::system::errc::no_such_file_or_directory) { LOG(WARNING) << "error when check path:" << path << ", error code:" << errcode; return false; } return exist; } } <|endoftext|>
<commit_before>/**********************************************************************************/ /* godotsharp_editor.cpp */ /**********************************************************************************/ /* The MIT License (MIT) */ /* */ /* Copyright (c) 2016 Ignacio Etcheverry */ /* */ /* 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 "godotsharp_editor.h" #include "scene/gui/control.h" #include "scene/main/node.h" #include "../csharp_script.h" #include "../godotsharp_dirs.h" #include "../mono_wrapper/gd_mono.h" #include "bindings_generator.h" #include "csharp_project.h" #include "net_solution.h" #ifdef WINDOWS_ENABLED #include "../utils/mono_reg_utils.h" #endif class MonoReloadNode : public Node { GDCLASS(MonoReloadNode, Node) protected: void _notification(int p_what) { switch (p_what) { case MainLoop::NOTIFICATION_WM_FOCUS_IN: { CSharpLanguage::get_singleton()->reload_assemblies_if_needed(true); } break; default: { } break; }; } }; GodotSharpEditor *GodotSharpEditor::singleton = NULL; bool GodotSharpEditor::_create_project_solution() { EditorProgress pr("create_csharp_solution", "Generating solution...", 2); pr.step("Generating C# project..."); String path = OS::get_singleton()->get_resource_dir(); String name = ProjectSettings::get_singleton()->get("application/config/name"); String guid = CSharpProject::generate_game_project(path, name); if (guid.length()) { NETSolution solution(name); if (!solution.set_path(path)) { show_error("Failed to create solution."); return false; } Vector<String> extra_configs; extra_configs.push_back("Tools"); solution.add_new_project(name, guid, extra_configs); Error sln_error = solution.save(); if (sln_error != OK) { show_error("Failed to save solution."); return false; } if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_CORE)) return false; if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_EDITOR)) return false; pr.step("Done"); // Here, after all calls to progress_task_step call_deferred("_remove_create_sln_menu_option"); } else { show_error("Failed to create C# project."); } return true; } void GodotSharpEditor::_remove_create_sln_menu_option() { menu_popup->remove_item(menu_popup->get_item_index(MENU_CREATE_SLN)); if (menu_popup->get_item_count() == 0) menu_button->hide(); } void GodotSharpEditor::_menu_option_pressed(int p_id) { switch (p_id) { case MENU_CREATE_SLN: { _create_project_solution(); } break; default: ERR_FAIL(); } } void GodotSharpEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_create_project_solution"), &GodotSharpEditor::_create_project_solution); ClassDB::bind_method(D_METHOD("_remove_create_sln_menu_option"), &GodotSharpEditor::_remove_create_sln_menu_option); ClassDB::bind_method(D_METHOD("_menu_option_pressed", "id"), &GodotSharpEditor::_menu_option_pressed); } void GodotSharpEditor::show_error(const String &p_message, const String &p_title) { error_dialog->set_title(p_title); error_dialog->set_text(p_message); error_dialog->popup_centered_minsize(); } GodotSharpEditor::GodotSharpEditor(EditorNode *p_editor) { singleton = this; editor = p_editor; menu_button = memnew(MenuButton); menu_button->set_text("Mono"); menu_popup = menu_button->get_popup(); if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path())) { menu_popup->add_item("Create C# solution", MENU_CREATE_SLN); } menu_popup->connect("id_pressed", this, "_menu_option_pressed"); if (menu_popup->get_item_count() == 0) menu_button->hide(); editor->get_menu_hb()->add_child(menu_button); error_dialog = memnew(AcceptDialog); editor->get_gui_base()->add_child(error_dialog); editor->add_bottom_panel_item("Mono", memnew(MonoBottomPanel(editor))); godotsharp_builds = memnew(GodotSharpBuilds); editor->add_child(memnew(MonoReloadNode)); } GodotSharpEditor::~GodotSharpEditor() { singleton = NULL; memdelete(godotsharp_builds); } <commit_msg>Check for csproj as well<commit_after>/**********************************************************************************/ /* godotsharp_editor.cpp */ /**********************************************************************************/ /* The MIT License (MIT) */ /* */ /* Copyright (c) 2016 Ignacio Etcheverry */ /* */ /* 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 "godotsharp_editor.h" #include "scene/gui/control.h" #include "scene/main/node.h" #include "../csharp_script.h" #include "../godotsharp_dirs.h" #include "../mono_wrapper/gd_mono.h" #include "bindings_generator.h" #include "csharp_project.h" #include "net_solution.h" #ifdef WINDOWS_ENABLED #include "../utils/mono_reg_utils.h" #endif class MonoReloadNode : public Node { GDCLASS(MonoReloadNode, Node) protected: void _notification(int p_what) { switch (p_what) { case MainLoop::NOTIFICATION_WM_FOCUS_IN: { CSharpLanguage::get_singleton()->reload_assemblies_if_needed(true); } break; default: { } break; }; } }; GodotSharpEditor *GodotSharpEditor::singleton = NULL; bool GodotSharpEditor::_create_project_solution() { EditorProgress pr("create_csharp_solution", "Generating solution...", 2); pr.step("Generating C# project..."); String path = OS::get_singleton()->get_resource_dir(); String name = ProjectSettings::get_singleton()->get("application/config/name"); String guid = CSharpProject::generate_game_project(path, name); if (guid.length()) { NETSolution solution(name); if (!solution.set_path(path)) { show_error("Failed to create solution."); return false; } Vector<String> extra_configs; extra_configs.push_back("Tools"); solution.add_new_project(name, guid, extra_configs); Error sln_error = solution.save(); if (sln_error != OK) { show_error("Failed to save solution."); return false; } if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_CORE)) return false; if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_EDITOR)) return false; pr.step("Done"); // Here, after all calls to progress_task_step call_deferred("_remove_create_sln_menu_option"); } else { show_error("Failed to create C# project."); } return true; } void GodotSharpEditor::_remove_create_sln_menu_option() { menu_popup->remove_item(menu_popup->get_item_index(MENU_CREATE_SLN)); if (menu_popup->get_item_count() == 0) menu_button->hide(); } void GodotSharpEditor::_menu_option_pressed(int p_id) { switch (p_id) { case MENU_CREATE_SLN: { _create_project_solution(); } break; default: ERR_FAIL(); } } void GodotSharpEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_create_project_solution"), &GodotSharpEditor::_create_project_solution); ClassDB::bind_method(D_METHOD("_remove_create_sln_menu_option"), &GodotSharpEditor::_remove_create_sln_menu_option); ClassDB::bind_method(D_METHOD("_menu_option_pressed", "id"), &GodotSharpEditor::_menu_option_pressed); } void GodotSharpEditor::show_error(const String &p_message, const String &p_title) { error_dialog->set_title(p_title); error_dialog->set_text(p_message); error_dialog->popup_centered_minsize(); } GodotSharpEditor::GodotSharpEditor(EditorNode *p_editor) { singleton = this; editor = p_editor; menu_button = memnew(MenuButton); menu_button->set_text("Mono"); menu_popup = menu_button->get_popup(); String sln_path = GodotSharpDirs::get_project_sln_path(); String csproj_path = GodotSharpDirs::get_project_csproj_path(); if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) { menu_popup->add_item("Create C# solution", MENU_CREATE_SLN); } menu_popup->connect("id_pressed", this, "_menu_option_pressed"); if (menu_popup->get_item_count() == 0) menu_button->hide(); editor->get_menu_hb()->add_child(menu_button); error_dialog = memnew(AcceptDialog); editor->get_gui_base()->add_child(error_dialog); editor->add_bottom_panel_item("Mono", memnew(MonoBottomPanel(editor))); godotsharp_builds = memnew(GodotSharpBuilds); editor->add_child(memnew(MonoReloadNode)); } GodotSharpEditor::~GodotSharpEditor() { singleton = NULL; memdelete(godotsharp_builds); } <|endoftext|>
<commit_before>#ifndef CHRONO_TIMER_HPP #define CHRONO_TIMER_HPP #include <chrono> #include <thread> class chrono_timer { std::chrono::time_point<std::chrono::high_resolution_clock> m_start; public: void reset() { m_start = std::chrono::high_resolution_clock::now(); } template <typename T> static void delay(std::size_t duration) { std::this_thread::sleep_for(T(duration)); } template <typename T> std::size_t count() const { return std::chrono::duration_cast<T> (std::chrono::high_resolution_clock::now() - m_start).count(); } }; #endif // CHRONO_TIMER_HPP <commit_msg>moved chrono_timer definition to benchmark.hpp<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers // Copyright (c) 2017-2020 The Peercoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <interfaces/node.h> #include <util/system.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent, uint64_t blockchain_size, uint64_t chain_state_size) : QDialog(parent), ui(new Ui::Intro), thread(nullptr), signalled(false), m_blockchain_size(blockchain_size), m_chain_state_size(chain_state_size) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(PACKAGE_NAME)); ui->storageLabel->setText(ui->storageLabel->text().arg(PACKAGE_NAME)); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(PACKAGE_NAME) .arg(m_blockchain_size) .arg(2012) .arg(tr("Peercoin")) ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(PACKAGE_NAME)); uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0)); if (pruneTarget > 1) { // -prune=1 means enabled, above that it's a size in MB ui->prune->setChecked(true); ui->prune->setEnabled(false); } ui->prune->setText(tr("Discard blocks after verification, except most recent %1 GB (prune)").arg(pruneTarget ? pruneTarget / 1000 : 2)); requiredSpace = m_blockchain_size; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (pruneTarget) { uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); if (prunedGBs <= requiredSpace) { requiredSpace = prunedGBs; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(true); } else { ui->lblExplanation3->setVisible(false); } requiredSpace += m_chain_state_size; ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the Peercoin block chain.").arg(PACKAGE_NAME) + " " + storageRequiresMsg.arg(requiredSpace) + " " + tr("The wallet will also be stored in this directory.") ); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ thread->quit(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == GUIUtil::getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } bool Intro::showIfNeeded(interfaces::Node& node, bool& did_show_intro, bool& prune) { did_show_intro = false; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = GUIUtil::getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false)) { /* Use selectParams here to guarantee Params() can be used by node interface */ try { node.selectParams(gArgs.GetChainName()); } catch (const std::exception&) { return false; } /* If current default data directory does not exist, let the user choose one */ Intro intro(0, node.getAssumedBlockchainSize(), node.getAssumedChainStateSize()); intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); did_show_intro = true; while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(nullptr, PACKAGE_NAME, tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } // Additional preferences: prune = intro.ui->prune->isChecked(); settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the bitcoin.conf file in the default data directory * (to be consistent with bitcoind behavior) */ if(dataDir != GUIUtil::getDefaultDataDirectory()) { node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting } return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %n GB needed)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); ui->prune->setChecked(true); } else if (bytesAvailable / GB_BYTES - requiredSpace < 10) { freeString += " " + tr("(%n GB needed for full chain)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #999900 }"); ui->prune->setChecked(true); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(GUIUtil::getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus); connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check); /* make sure executor object is deleted in its own thread */ connect(thread, &QThread::finished, executor, &QObject::deleteLater); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <commit_msg>qt: Change default size of intro frame<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers // Copyright (c) 2017-2020 The Peercoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <interfaces/node.h> #include <util/system.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent, uint64_t blockchain_size, uint64_t chain_state_size) : QDialog(parent), ui(new Ui::Intro), thread(nullptr), signalled(false), m_blockchain_size(blockchain_size), m_chain_state_size(chain_state_size) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(PACKAGE_NAME)); ui->storageLabel->setText(ui->storageLabel->text().arg(PACKAGE_NAME)); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(PACKAGE_NAME) .arg(m_blockchain_size) .arg(2012) .arg(tr("Peercoin")) ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(PACKAGE_NAME)); uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0)); if (pruneTarget > 1) { // -prune=1 means enabled, above that it's a size in MB ui->prune->setChecked(true); ui->prune->setEnabled(false); } ui->prune->setText(tr("Discard blocks after verification, except most recent %1 GB (prune)").arg(pruneTarget ? pruneTarget / 1000 : 2)); requiredSpace = m_blockchain_size; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (pruneTarget) { uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); if (prunedGBs <= requiredSpace) { requiredSpace = prunedGBs; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(true); } else { ui->lblExplanation3->setVisible(false); } requiredSpace += m_chain_state_size; ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the Peercoin block chain.").arg(PACKAGE_NAME) + " " + storageRequiresMsg.arg(requiredSpace) + " " + tr("The wallet will also be stored in this directory.") ); this->adjustSize(); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ thread->quit(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == GUIUtil::getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } bool Intro::showIfNeeded(interfaces::Node& node, bool& did_show_intro, bool& prune) { did_show_intro = false; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = GUIUtil::getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false)) { /* Use selectParams here to guarantee Params() can be used by node interface */ try { node.selectParams(gArgs.GetChainName()); } catch (const std::exception&) { return false; } /* If current default data directory does not exist, let the user choose one */ Intro intro(0, node.getAssumedBlockchainSize(), node.getAssumedChainStateSize()); intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); did_show_intro = true; while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(nullptr, PACKAGE_NAME, tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } // Additional preferences: prune = intro.ui->prune->isChecked(); settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the bitcoin.conf file in the default data directory * (to be consistent with bitcoind behavior) */ if(dataDir != GUIUtil::getDefaultDataDirectory()) { node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting } return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %n GB needed)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); ui->prune->setChecked(true); } else if (bytesAvailable / GB_BYTES - requiredSpace < 10) { freeString += " " + tr("(%n GB needed for full chain)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #999900 }"); ui->prune->setChecked(true); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(GUIUtil::getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus); connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check); /* make sure executor object is deleted in its own thread */ connect(thread, &QThread::finished, executor, &QObject::deleteLater); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_init.C $ */ /* */ /* 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 p9_pm_init.C /// @brief Wrapper that initializes or resets the OCC complex. /// // *HWP HWP Owner : Greg Still <[email protected]> // *HWP HWP Backup Owner : // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : HS /// /// High-level procedure flow: /// /// @verbatim /// /// PM_INIT /// Initialize Cores and Quads /// Initialize OCB channels /// Initialize PSS /// Initialize PBA /// Mask CME FIRs and Core-Quad Errors /// Initialize Stop GPE /// Initialize Pstate GPE /// Start OCC PPC405 /// Clear off pending Special Wakeup requests on all configured EX chiplets /// /// PM_RESET /// Invoke "p9_pm_reset()" to reset the PM OCC complex (Cores, Quads, CMEs, /// OCB channels, PBA bus, PSS, PPC405 and GPEs) /// /// @endverbatim /// // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <p9_pm_init.H> // ----------------------------------------------------------------------------- // Function prototypes // ----------------------------------------------------------------------------- /// /// @brief Call underlying unit procedures to initialize the PM complex. /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS on success, else error code. /// fapi2::ReturnCode pm_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// /// @brief Clears OCC special wake-up on all configured EX chiplets /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS on success, else error code. /// fapi2::ReturnCode clear_occ_special_wakeups( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); // ----------------------------------------------------------------------------- // Function definitions // ----------------------------------------------------------------------------- fapi2::ReturnCode p9_pm_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9pm::PM_FLOW_MODE i_mode) { FAPI_INF("Entering p9_pm_init ..."); fapi2::ReturnCode l_rc; if (i_mode == p9pm::PM_INIT) { FAPI_DBG("Initialize the OCC Complex."); FAPI_TRY(pm_init(i_target), "ERROR: Failed to initialize OCC Complex"); } else if (i_mode == p9pm::PM_RESET) { FAPI_DBG("Reset the OCC Complex."); FAPI_EXEC_HWP(l_rc, p9_pm_reset, i_target); FAPI_TRY(l_rc, "ERROR: Failed to reset OCC complex"); } else { FAPI_ASSERT(false, fapi2::PM_INIT_BAD_MODE().set_BADMODE(i_mode), "ERROR; Unknown mode passed to p9_pm_init. Mode %x", i_mode); } fapi_try_exit: FAPI_INF("Exiting p9_pm_init..."); return fapi2::current_err; } fapi2::ReturnCode pm_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Entering pm_init..."); fapi2::ReturnCode l_rc; // ************************************************************************ // Initialize Cores and Quads // ************************************************************************ FAPI_DBG("Executing p9_pm_corequad_init to initialize cores & quads"); FAPI_EXEC_HWP(l_rc, p9_pm_corequad_init, i_target, p9pm::PM_INIT, 0,//CME FIR MASK for reset 0,//Core Error Mask for reset 0 //Quad Error Mask for reset ); FAPI_TRY(l_rc, "ERROR: Failed to initialize cores & quads"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After cores & quads init")); // ************************************************************************ // Issue init to OCB // ************************************************************************ FAPI_DBG("Executing p9_pm_ocb_init to initialize OCB channels"); FAPI_EXEC_HWP(l_rc, p9_pm_ocb_init, i_target, p9pm::PM_INIT,// Channel setup type p9ocb::OCB_CHAN1,// Channel p9ocb:: OCB_TYPE_NULL,// Channel type 0,// Channel base address 0,// Push/Pull queue length p9ocb::OCB_Q_OUFLOW_NULL,// Channel flow control p9ocb::OCB_Q_ITPTYPE_NULL// Channel interrupt control ); FAPI_TRY(l_rc, "ERROR: Failed to initialize channel 1"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After OCB channels init")); // ************************************************************************ // Initializes P2S and HWC logic // ************************************************************************ FAPI_DBG("Executing p9_pm_pss_init to initialize P2S and HWC logic"); FAPI_EXEC_HWP(l_rc, p9_pm_pss_init, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to initialize PSS & HWC"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After PSS & HWC init")); // ************************************************************************ // Initializes PBA // Note: This voids the channel used by the GPEs // ************************************************************************ FAPI_DBG("Executing p9_pm_pba_init to initialize PBA"); FAPI_EXEC_HWP(l_rc, p9_pm_pba_init, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to initialize PBA BUS"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After PBA bus init")); // ************************************************************************ // Mask the FIRs as errors can occur in what follows // ************************************************************************ FAPI_DBG("Executing p9_pm_firinit to mask errors/FIRs"); FAPI_EXEC_HWP(l_rc, p9_pm_firinit, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to mask OCC,PBA & CME FIRs/Errors."); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After masking FIRs and Errors")); // ************************************************************************ // Initialize the STOP GPE Engine // ************************************************************************ FAPI_DBG("Executing p9_pm_stop_gpe_init to initialize SGPE"); FAPI_EXEC_HWP(l_rc, p9_pm_stop_gpe_init, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to initialize SGPE"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After SGPE initialization")); // ************************************************************************ // Switch off OCC initiated special wakeup on EX to allowSTOP functionality // ************************************************************************ FAPI_DBG("Clear off the wakeup"); FAPI_TRY(clear_occ_special_wakeups(i_target), "ERROR: Failed to clear off the wakeup"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "EX targets off special wakeup")); // ************************************************************************ // Take all EX chiplets out of special wakeup // ************************************************************************ FAPI_DBG("Disable special wakeup for all functional EX targets."); FAPI_TRY(special_wakeup_all(i_target, false),//Disable splwkup "ERROR: Failed to remove EX chiplets from special wakeup"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After EX out of special wakeup")); // ************************************************************************ // Initialize the PSTATE GPE Engine // ************************************************************************ /* TODO: RTC 157096: Enable pstate GPE initialization in PM_INIT phase FAPI_DBG("Executing p9_pm_pstate_gpe_init to initialize PGPE"); FAPI_EXEC_HWP(l_rc, p9_pm_pstate_gpe_init, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to initialize PGPE"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After PGPE initialization")); */ // ************************************************************************ // Start OCC PPC405 // ************************************************************************ FAPI_DBG("Executing p9_pm_occ_control to start OCC PPC405"); FAPI_EXEC_HWP(l_rc, p9_pm_occ_control, i_target, p9occ_ctrl::PPC405_START,// Operation on PPC405 p9occ_ctrl::PPC405_BOOT_MEM // PPC405 boot location ); FAPI_TRY(l_rc, "ERROR: Failed to initialize OCC PPC405"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After OCC PPC405 init")); fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode clear_occ_special_wakeups( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Entering clear_occ_special_wakeups..."); fapi2::buffer<uint64_t> l_data64; auto l_exChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EX> (fapi2::TARGET_STATE_FUNCTIONAL); FAPI_DBG("No. of functional EX chiplets: %u ", l_exChiplets.size()); // Iterate through the EX chiplets for (auto l_ex_chplt : l_exChiplets) { FAPI_DBG("Clear OCC special wakeup on ex chiplet 0x%08X", l_ex_chplt); FAPI_TRY(fapi2::getScom(i_target, EX_PPM_SPWKUP_OCC, l_data64), "ERROR: Failed to read OCC Spl wkup on EX 0x%08X", l_ex_chplt); l_data64.clearBit<0>(); FAPI_TRY(fapi2::putScom(i_target, EX_PPM_SPWKUP_OCC, l_data64), "ERROR: Failed to clear OCC Spl wkup on EX 0x%08X", l_ex_chplt); } fapi_try_exit: return fapi2::current_err; } <commit_msg>Modifications to reset/init procedures<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_init.C $ */ /* */ /* 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 p9_pm_init.C /// @brief Wrapper that initializes or resets the OCC complex. /// // *HWP HWP Owner : Greg Still <[email protected]> // *HWP HWP Backup Owner : // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : HS /// /// High-level procedure flow: /// /// @verbatim /// /// PM_INIT /// Initialize Cores and Quads /// Initialize OCB channels /// Initialize PSS /// Set the OCC FIR actions /// Set the CME, PPM and PBA FIR actions /// Initialize Stop GPE /// Initialize Pstate GPE /// Clear off pending Special Wakeup requests on all configured EX chiplets /// Disable special wakeup of all the EX chiplets /// Start OCC PPC405 /// /// PM_RESET /// Invoke "p9_pm_reset()" to reset the PM OCC complex (Cores, Quads, CMEs, /// OCB channels, PBA bus, PSS, PPC405 and GPEs) /// /// @endverbatim /// // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <p9_pm_init.H> // ----------------------------------------------------------------------------- // Function prototypes // ----------------------------------------------------------------------------- /// /// @brief Call underlying unit procedures to initialize the PM complex. /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS on success, else error code. /// fapi2::ReturnCode pm_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// /// @brief Clears OCC special wake-up on all configured EX chiplets /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS on success, else error code. /// fapi2::ReturnCode clear_occ_special_wakeups( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); // ----------------------------------------------------------------------------- // Function definitions // ----------------------------------------------------------------------------- fapi2::ReturnCode p9_pm_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9pm::PM_FLOW_MODE i_mode) { FAPI_INF("Entering p9_pm_init ..."); fapi2::ReturnCode l_rc; if (i_mode == p9pm::PM_INIT) { FAPI_DBG("Initialize the OCC Complex."); FAPI_TRY(pm_init(i_target), "ERROR: Failed to initialize OCC Complex"); } else if (i_mode == p9pm::PM_RESET) { FAPI_DBG("Reset the OCC Complex."); FAPI_EXEC_HWP(l_rc, p9_pm_reset, i_target); FAPI_TRY(l_rc, "ERROR: Failed to reset OCC complex"); } else { FAPI_ASSERT(false, fapi2::PM_INIT_BAD_MODE().set_BADMODE(i_mode), "ERROR; Unknown mode passed to p9_pm_init. Mode %x", i_mode); } fapi_try_exit: FAPI_INF("Exiting p9_pm_init..."); return fapi2::current_err; } fapi2::ReturnCode pm_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Entering pm_init..."); fapi2::ReturnCode l_rc; // ************************************************************************ // Initialize Cores and Quads // ************************************************************************ FAPI_DBG("Executing p9_pm_corequad_init to initialize cores & quads"); FAPI_EXEC_HWP(l_rc, p9_pm_corequad_init, i_target, p9pm::PM_INIT, 0,//CME FIR MASK for reset 0,//Core Error Mask for reset 0 //Quad Error Mask for reset ); FAPI_TRY(l_rc, "ERROR: Failed to initialize cores & quads"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After cores & quads init")); // ************************************************************************ // Issue init to OCB // ************************************************************************ FAPI_DBG("Executing p9_pm_ocb_init to initialize OCB channels"); FAPI_EXEC_HWP(l_rc, p9_pm_ocb_init, i_target, p9pm::PM_INIT,// Channel setup type p9ocb::OCB_CHAN1,// Channel p9ocb:: OCB_TYPE_NULL,// Channel type 0,// Channel base address 0,// Push/Pull queue length p9ocb::OCB_Q_OUFLOW_NULL,// Channel flow control p9ocb::OCB_Q_ITPTYPE_NULL// Channel interrupt control ); FAPI_TRY(l_rc, "ERROR: Failed to initialize channel 1"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After OCB channels init")); // ************************************************************************ // Initializes P2S and HWC logic // ************************************************************************ FAPI_DBG("Executing p9_pm_pss_init to initialize P2S and HWC logic"); FAPI_EXEC_HWP(l_rc, p9_pm_pss_init, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to initialize PSS & HWC"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After PSS & HWC init")); // ************************************************************************ // Set the OCC FIR actions // ************************************************************************ FAPI_DBG("Executing p9_pm_occ_firinit to set FIR actions."); FAPI_EXEC_HWP(l_rc, p9_pm_occ_firinit, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to set OCC FIR actions."); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After setting FIRs")); // ************************************************************************ // Set the FIR actions // ************************************************************************ FAPI_DBG("Executing p9_pm_firinit to set PBA, PPM, CME FIR actions"); FAPI_EXEC_HWP(l_rc, p9_pm_firinit, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to set PPM, PBA & CME FIRs."); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After setting FIRs")); // ************************************************************************ // Initialize the STOP GPE Engine // ************************************************************************ FAPI_DBG("Executing p9_pm_stop_gpe_init to initialize SGPE"); FAPI_EXEC_HWP(l_rc, p9_pm_stop_gpe_init, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to initialize SGPE"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After SGPE initialization")); // ************************************************************************ // Initialize the PSTATE GPE Engine // ************************************************************************ /* TODO: RTC 157096: Enable pstate GPE initialization in PM_INIT phase FAPI_DBG("Executing p9_pm_pstate_gpe_init to initialize PGPE"); FAPI_EXEC_HWP(l_rc, p9_pm_pstate_gpe_init, i_target, p9pm::PM_INIT); FAPI_TRY(l_rc, "ERROR: Failed to initialize PGPE"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After PGPE initialization")); */ // ************************************************************************ // Switch off OCC initiated special wakeup on EX to allowSTOP functionality // ************************************************************************ FAPI_DBG("Clear off the wakeup"); FAPI_TRY(clear_occ_special_wakeups(i_target), "ERROR: Failed to clear off the wakeup"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "EX targets off special wakeup")); // ************************************************************************ // Take all EX chiplets out of special wakeup // ************************************************************************ FAPI_DBG("Disable special wakeup for all functional EX targets."); FAPI_TRY(special_wakeup_all(i_target, false),//Disable splwkup "ERROR: Failed to remove EX chiplets from special wakeup"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After EX out of special wakeup")); // ************************************************************************ // Start OCC PPC405 // ************************************************************************ FAPI_DBG("Executing p9_pm_occ_control to start OCC PPC405"); FAPI_EXEC_HWP(l_rc, p9_pm_occ_control, i_target, p9occ_ctrl::PPC405_START,// Operation on PPC405 p9occ_ctrl::PPC405_BOOT_MEM // PPC405 boot location ); FAPI_TRY(l_rc, "ERROR: Failed to initialize OCC PPC405"); FAPI_TRY(p9_pm_glob_fir_trace(i_target, "After OCC PPC405 init")); fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode clear_occ_special_wakeups( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Entering clear_occ_special_wakeups..."); fapi2::buffer<uint64_t> l_data64; auto l_exChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EX> (fapi2::TARGET_STATE_FUNCTIONAL); FAPI_DBG("No. of functional EX chiplets: %u ", l_exChiplets.size()); // Iterate through the EX chiplets for (auto l_ex_chplt : l_exChiplets) { FAPI_DBG("Clear OCC special wakeup on ex chiplet 0x%08X", l_ex_chplt); FAPI_TRY(fapi2::getScom(i_target, EX_PPM_SPWKUP_OCC, l_data64), "ERROR: Failed to read OCC Spl wkup on EX 0x%08X", l_ex_chplt); l_data64.clearBit<0>(); FAPI_TRY(fapi2::putScom(i_target, EX_PPM_SPWKUP_OCC, l_data64), "ERROR: Failed to clear OCC Spl wkup on EX 0x%08X", l_ex_chplt); } fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* Copyright libCellML Contributors 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 "xmldoc.h" #include <cstring> #include <libxml/tree.h> #include <libxml/xmlerror.h> #include <sstream> #include <string> #include <vector> #include <zlib.h> #include "internaltypes.h" #include "libcellmlconfig_p.h" #include "mathmldtd.h" #include "xmlnode.h" namespace libcellml { /** * @brief Callback for errors from the libxml2 context parser. * * Structured callback @c xmlStructuredErrorFunc for errors * from the libxml2 context parser used to parse this document. * * @param userData Private data type used to store the libxml context. * * @param error The @c xmlErrorPtr to the error raised by libxml. */ void structuredErrorCallback(void *userData, xmlErrorPtr error) { std::string errorString = std::string(error->message); // Swap libxml2 carriage return for a period. if (errorString.substr(errorString.length() - 1) == "\n") { errorString.replace(errorString.end() - 1, errorString.end(), "."); } auto context = reinterpret_cast<xmlParserCtxtPtr>(userData); auto doc = reinterpret_cast<XmlDoc *>(context->_private); doc->addXmlError(errorString); } /** * @brief The XmlDoc::XmlDocImpl struct. * * This struct is the private implementation struct for the XmlDoc class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct XmlDoc::XmlDocImpl { xmlDocPtr mXmlDocPtr = nullptr; Strings mXmlErrors; size_t bufferPointer = 0; }; XmlDoc::XmlDoc() : mPimpl(new XmlDocImpl()) { } XmlDoc::~XmlDoc() { if (mPimpl->mXmlDocPtr != nullptr) { xmlFreeDoc(mPimpl->mXmlDocPtr); } delete mPimpl; } void XmlDoc::parse(const std::string &input) { xmlInitParser(); xmlParserCtxtPtr context = xmlNewParserCtxt(); context->_private = reinterpret_cast<void *>(this); xmlSetStructuredErrorFunc(context, structuredErrorCallback); mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, 0); xmlFreeParserCtxt(context); xmlSetStructuredErrorFunc(nullptr, nullptr); xmlCleanupParser(); xmlCleanupGlobals(); } std::string decompressMathMLDTD() { std::vector<unsigned char> mathmlDTD; UNCOMPRESS_SIZE_TYPE sizeMathmlDTDUncompressedResize = MATHML_DTD_LEN; mathmlDTD.resize(sizeMathmlDTDUncompressedResize); const unsigned char *a = compressedMathMLDTD(); uncompress(&mathmlDTD[0], &sizeMathmlDTDUncompressedResize, a, COMPRESSED_MATHML_DTD_LEN); return std::string(mathmlDTD.begin(), mathmlDTD.end()); } void XmlDoc::parseMathML(const std::string &input) { // Decompress the MathML DTD. int sizeMathmlDTDUncompressed = MATHML_DTD_LEN; std::string mathMLDTD = decompressMathMLDTD(); xmlInitParser(); xmlParserCtxtPtr context = xmlNewParserCtxt(); context->_private = reinterpret_cast<void *>(this); xmlSetStructuredErrorFunc(context, structuredErrorCallback); mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, 0); xmlParserInputBufferPtr buf = xmlParserInputBufferCreateMem(reinterpret_cast<const char *>(mathMLDTD.c_str()), sizeMathmlDTDUncompressed, XML_CHAR_ENCODING_ASCII); xmlDtdPtr dtd = xmlIOParseDTD(nullptr, buf, XML_CHAR_ENCODING_ASCII); xmlValidateDtd(&(context->vctxt), mPimpl->mXmlDocPtr, dtd); xmlFreeDtd(dtd); xmlFreeParserCtxt(context); xmlSetStructuredErrorFunc(nullptr, nullptr); xmlCleanupParser(); xmlCleanupGlobals(); } std::string XmlDoc::prettyPrint() const { xmlChar *buffer; int size = 0; xmlDocDumpFormatMemoryEnc(mPimpl->mXmlDocPtr, &buffer, &size, "UTF-8", 1); std::stringstream res; res << buffer; xmlFree(buffer); return res.str(); } XmlNodePtr XmlDoc::rootNode() const { xmlNodePtr root = xmlDocGetRootElement(mPimpl->mXmlDocPtr); XmlNodePtr rootHandle = nullptr; if (root != nullptr) { rootHandle = std::make_shared<XmlNode>(); rootHandle->setXmlNode(root); } return rootHandle; } void XmlDoc::addXmlError(const std::string &error) { mPimpl->mXmlErrors.push_back(error); } size_t XmlDoc::xmlErrorCount() const { return mPimpl->mXmlErrors.size(); } std::string XmlDoc::xmlError(size_t index) const { return mPimpl->mXmlErrors.at(index); } } // namespace libcellml <commit_msg>XmlDoc: compress the XHTML+MathML+SVG DTD only once.<commit_after>/* Copyright libCellML Contributors 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 "xmldoc.h" #include <cstring> #include <libxml/tree.h> #include <libxml/xmlerror.h> #include <sstream> #include <string> #include <vector> #include <zlib.h> #include "internaltypes.h" #include "libcellmlconfig_p.h" #include "mathmldtd.h" #include "xmlnode.h" namespace libcellml { /** * @brief Callback for errors from the libxml2 context parser. * * Structured callback @c xmlStructuredErrorFunc for errors * from the libxml2 context parser used to parse this document. * * @param userData Private data type used to store the libxml context. * * @param error The @c xmlErrorPtr to the error raised by libxml. */ void structuredErrorCallback(void *userData, xmlErrorPtr error) { std::string errorString = std::string(error->message); // Swap libxml2 carriage return for a period. if (errorString.substr(errorString.length() - 1) == "\n") { errorString.replace(errorString.end() - 1, errorString.end(), "."); } auto context = reinterpret_cast<xmlParserCtxtPtr>(userData); auto doc = reinterpret_cast<XmlDoc *>(context->_private); doc->addXmlError(errorString); } /** * @brief The XmlDoc::XmlDocImpl struct. * * This struct is the private implementation struct for the XmlDoc class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct XmlDoc::XmlDocImpl { xmlDocPtr mXmlDocPtr = nullptr; Strings mXmlErrors; size_t bufferPointer = 0; }; XmlDoc::XmlDoc() : mPimpl(new XmlDocImpl()) { } XmlDoc::~XmlDoc() { if (mPimpl->mXmlDocPtr != nullptr) { xmlFreeDoc(mPimpl->mXmlDocPtr); } delete mPimpl; } void XmlDoc::parse(const std::string &input) { xmlInitParser(); xmlParserCtxtPtr context = xmlNewParserCtxt(); context->_private = reinterpret_cast<void *>(this); xmlSetStructuredErrorFunc(context, structuredErrorCallback); mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, 0); xmlFreeParserCtxt(context); xmlSetStructuredErrorFunc(nullptr, nullptr); xmlCleanupParser(); xmlCleanupGlobals(); } std::string decompressMathMLDTD() { std::vector<unsigned char> mathmlDTD; UNCOMPRESS_SIZE_TYPE sizeMathmlDTDUncompressedResize = MATHML_DTD_LEN; mathmlDTD.resize(sizeMathmlDTDUncompressedResize); const unsigned char *a = compressedMathMLDTD(); uncompress(&mathmlDTD[0], &sizeMathmlDTDUncompressedResize, a, COMPRESSED_MATHML_DTD_LEN); return std::string(mathmlDTD.begin(), mathmlDTD.end()); } void XmlDoc::parseMathML(const std::string &input) { // Decompress the MathML DTD. int sizeMathmlDTDUncompressed = MATHML_DTD_LEN; static std::string mathMLDTD; if (mathMLDTD.empty()) { mathMLDTD = decompressMathMLDTD(); } xmlInitParser(); xmlParserCtxtPtr context = xmlNewParserCtxt(); context->_private = reinterpret_cast<void *>(this); xmlSetStructuredErrorFunc(context, structuredErrorCallback); mPimpl->mXmlDocPtr = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(input.c_str()), "/", nullptr, 0); xmlParserInputBufferPtr buf = xmlParserInputBufferCreateMem(reinterpret_cast<const char *>(mathMLDTD.c_str()), sizeMathmlDTDUncompressed, XML_CHAR_ENCODING_ASCII); xmlDtdPtr dtd = xmlIOParseDTD(nullptr, buf, XML_CHAR_ENCODING_ASCII); xmlValidateDtd(&(context->vctxt), mPimpl->mXmlDocPtr, dtd); xmlFreeDtd(dtd); xmlFreeParserCtxt(context); xmlSetStructuredErrorFunc(nullptr, nullptr); xmlCleanupParser(); xmlCleanupGlobals(); } std::string XmlDoc::prettyPrint() const { xmlChar *buffer; int size = 0; xmlDocDumpFormatMemoryEnc(mPimpl->mXmlDocPtr, &buffer, &size, "UTF-8", 1); std::stringstream res; res << buffer; xmlFree(buffer); return res.str(); } XmlNodePtr XmlDoc::rootNode() const { xmlNodePtr root = xmlDocGetRootElement(mPimpl->mXmlDocPtr); XmlNodePtr rootHandle = nullptr; if (root != nullptr) { rootHandle = std::make_shared<XmlNode>(); rootHandle->setXmlNode(root); } return rootHandle; } void XmlDoc::addXmlError(const std::string &error) { mPimpl->mXmlErrors.push_back(error); } size_t XmlDoc::xmlErrorCount() const { return mPimpl->mXmlErrors.size(); } std::string XmlDoc::xmlError(size_t index) const { return mPimpl->mXmlErrors.at(index); } } // namespace libcellml <|endoftext|>
<commit_before>/* * Reference counting API. * * author: Max Kellermann <[email protected]> */ #ifndef REFCOUNT_HXX #define REFCOUNT_HXX #include <glib.h> #include <assert.h> struct RefCount { volatile gint value; void Init() { g_atomic_int_set(&value, 1); } void Get() { assert(g_atomic_int_get(&value) > 0); g_atomic_int_inc(&value); } /** * Decreases the reference counter, and returns true if the counter * has reached 0. */ bool Put() { assert(value > 0); return g_atomic_int_dec_and_test(&value); } }; #endif <commit_msg>refcount: add static_assert on is_trivial<commit_after>/* * Reference counting API. * * author: Max Kellermann <[email protected]> */ #ifndef REFCOUNT_HXX #define REFCOUNT_HXX #include <glib.h> #include <type_traits> #include <assert.h> struct RefCount { volatile gint value; void Init() { g_atomic_int_set(&value, 1); } void Get() { assert(g_atomic_int_get(&value) > 0); g_atomic_int_inc(&value); } /** * Decreases the reference counter, and returns true if the counter * has reached 0. */ bool Put() { assert(value > 0); return g_atomic_int_dec_and_test(&value); } }; static_assert(std::is_trivial<RefCount>::value, "type is not trivial"); #endif <|endoftext|>
<commit_before>#ifndef PQRS_XML_COMPILER_HPP #define PQRS_XML_COMPILER_HPP #include <stack> #include <string> #include <stdexcept> #include <vector> #include <tr1/memory> #include <tr1/unordered_map> #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <boost/iterator_adaptors.hpp> #include <boost/optional.hpp> #include <boost/property_tree/ptree.hpp> #include "pqrs/string.hpp" namespace pqrs { class xml_compiler { public: typedef std::tr1::shared_ptr<boost::property_tree::ptree> ptree_ptr; #include "pqrs/xml_compiler/detail/exception.hpp" #include "pqrs/xml_compiler/detail/error_information.hpp" #include "pqrs/xml_compiler/detail/xml_file_path.hpp" #include "pqrs/xml_compiler/detail/extracted_ptree.hpp" #include "pqrs/xml_compiler/detail/replacement.hpp" #include "pqrs/xml_compiler/detail/symbol_map.hpp" #include "pqrs/xml_compiler/detail/app.hpp" #include "pqrs/xml_compiler/detail/device.hpp" #include "pqrs/xml_compiler/detail/preferences_node.hpp" #include "pqrs/xml_compiler/detail/essential_configuration.hpp" #include "pqrs/xml_compiler/detail/filter_vector.hpp" #include "pqrs/xml_compiler/detail/remapclasses_initialize_vector.hpp" #include "pqrs/xml_compiler/detail/remapclasses_initialize_vector_prepare_loader.hpp" #include "pqrs/xml_compiler/detail/loader_wrapper.hpp" xml_compiler(const std::string& system_xml_directory, const std::string& private_xml_directory) : system_xml_directory_(system_xml_directory), private_xml_directory_(private_xml_directory) {} void reload(void); const remapclasses_initialize_vector& get_remapclasses_initialize_vector(void) const { return remapclasses_initialize_vector_; } const error_information& get_error_information(void) const { return error_information_; } boost::optional<uint32_t> get_symbol_map_value(const std::string& name) const { return symbol_map_.get_optional(name); } void dump_symbol_map(void) const { symbol_map_.dump(); } boost::optional<const std::string&> get_identifier(int config_index) const; uint32_t get_appid(const std::string& application_identifier) const; boost::optional<const essential_configuration&> get_essential_configuration(size_t index) const { if (index >= essential_configurations_.size()) return boost::none; return *(essential_configurations_[index]); } const preferences_node_tree<preferences_checkbox_node>& get_preferences_checkbox_node_tree(void) const { return preferences_checkbox_node_tree_; } const preferences_node_tree<preferences_number_node>& get_preferences_number_node_tree(void) const { return preferences_number_node_tree_; } private: void read_xml_(ptree_ptr& out, const std::string& base_diretory, const std::string& relative_file_path, const pqrs::string::replacement& replacement) const; void read_xml_(ptree_ptr& out, const xml_file_path& xml_file_path, const pqrs::string::replacement& replacement) const; void read_xml_(ptree_ptr& out, const xml_file_path& xml_file_path) const { read_xml_(out, xml_file_path, replacement_); } extracted_ptree make_extracted_ptree(const boost::property_tree::ptree& pt) const { return extracted_ptree(*this, replacement_, pt); } static void normalize_identifier_(std::string& identifier); bool valid_identifier_(const std::string& identifier, const std::string& parent_tag_name) const; void traverse_identifier_(const extracted_ptree& pt, const std::string& parent_tag_name); void traverse_identifier_(const boost::property_tree::ptree& pt, const std::string& parent_tag_name) { traverse_identifier_(make_extracted_ptree(pt), parent_tag_name); } void traverse_autogen_(const extracted_ptree& pt, const std::string& identifier, const filter_vector& filter_vector, std::vector<uint32_t>& initialize_vector); void traverse_autogen_(const boost::property_tree::ptree& pt, const std::string& identifier, const filter_vector& filter_vector, std::vector<uint32_t>& initialize_vector) { traverse_autogen_(make_extracted_ptree(pt), identifier, filter_vector, initialize_vector); } void handle_autogen(const std::string& autogen, const std::string& raw_autogen, const filter_vector& filter_vector, std::vector<uint32_t>& initialize_vector); void add_to_initialize_vector(const std::string& params, uint32_t type, const filter_vector& filter_vector, std::vector<uint32_t>& initialize_vector) const; const std::string system_xml_directory_; const std::string private_xml_directory_; mutable error_information error_information_; pqrs::string::replacement replacement_; symbol_map symbol_map_; std::vector<std::tr1::shared_ptr<app> > app_vector_; std::tr1::unordered_map<uint32_t, std::string> identifier_map_; std::vector<std::tr1::shared_ptr<essential_configuration> > essential_configurations_; remapclasses_initialize_vector remapclasses_initialize_vector_; uint32_t simultaneous_keycode_index_; preferences_node_tree<preferences_checkbox_node> preferences_checkbox_node_tree_; preferences_node_tree<preferences_number_node> preferences_number_node_tree_; }; } #endif <commit_msg>cleanup<commit_after>#ifndef PQRS_XML_COMPILER_HPP #define PQRS_XML_COMPILER_HPP #include <stack> #include <string> #include <stdexcept> #include <vector> #include <tr1/memory> #include <tr1/unordered_map> #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <boost/iterator_adaptors.hpp> #include <boost/optional.hpp> #include <boost/property_tree/ptree.hpp> #include "pqrs/string.hpp" namespace pqrs { class xml_compiler { public: typedef std::tr1::shared_ptr<boost::property_tree::ptree> ptree_ptr; #include "pqrs/xml_compiler/detail/exception.hpp" #include "pqrs/xml_compiler/detail/error_information.hpp" #include "pqrs/xml_compiler/detail/xml_file_path.hpp" #include "pqrs/xml_compiler/detail/extracted_ptree.hpp" #include "pqrs/xml_compiler/detail/replacement.hpp" #include "pqrs/xml_compiler/detail/symbol_map.hpp" #include "pqrs/xml_compiler/detail/app.hpp" #include "pqrs/xml_compiler/detail/device.hpp" #include "pqrs/xml_compiler/detail/preferences_node.hpp" #include "pqrs/xml_compiler/detail/essential_configuration.hpp" #include "pqrs/xml_compiler/detail/filter_vector.hpp" #include "pqrs/xml_compiler/detail/remapclasses_initialize_vector.hpp" #include "pqrs/xml_compiler/detail/remapclasses_initialize_vector_prepare_loader.hpp" #include "pqrs/xml_compiler/detail/loader_wrapper.hpp" xml_compiler(const std::string& system_xml_directory, const std::string& private_xml_directory) : system_xml_directory_(system_xml_directory), private_xml_directory_(private_xml_directory) {} void reload(void); const remapclasses_initialize_vector& get_remapclasses_initialize_vector(void) const { return remapclasses_initialize_vector_; } const error_information& get_error_information(void) const { return error_information_; } boost::optional<uint32_t> get_symbol_map_value(const std::string& name) const { return symbol_map_.get_optional(name); } void dump_symbol_map(void) const { symbol_map_.dump(); } boost::optional<const std::string&> get_identifier(int config_index) const; uint32_t get_appid(const std::string& application_identifier) const; boost::optional<const essential_configuration&> get_essential_configuration(size_t index) const { if (index >= essential_configurations_.size()) return boost::none; return *(essential_configurations_[index]); } const preferences_node_tree<preferences_checkbox_node>& get_preferences_checkbox_node_tree(void) const { return preferences_checkbox_node_tree_; } const preferences_node_tree<preferences_number_node>& get_preferences_number_node_tree(void) const { return preferences_number_node_tree_; } private: void read_xml_(ptree_ptr& out, const std::string& base_diretory, const std::string& relative_file_path, const pqrs::string::replacement& replacement) const; void read_xml_(ptree_ptr& out, const xml_file_path& xml_file_path, const pqrs::string::replacement& replacement) const; void read_xml_(ptree_ptr& out, const xml_file_path& xml_file_path) const { read_xml_(out, xml_file_path, replacement_); } extracted_ptree make_extracted_ptree(const boost::property_tree::ptree& pt) const { return extracted_ptree(*this, replacement_, pt); } static void normalize_identifier_(std::string& identifier); bool valid_identifier_(const std::string& identifier, const std::string& parent_tag_name) const; void traverse_identifier_(const extracted_ptree& pt, const std::string& parent_tag_name); void traverse_autogen_(const extracted_ptree& pt, const std::string& identifier, const filter_vector& filter_vector, std::vector<uint32_t>& initialize_vector); void handle_autogen(const std::string& autogen, const std::string& raw_autogen, const filter_vector& filter_vector, std::vector<uint32_t>& initialize_vector); void add_to_initialize_vector(const std::string& params, uint32_t type, const filter_vector& filter_vector, std::vector<uint32_t>& initialize_vector) const; const std::string system_xml_directory_; const std::string private_xml_directory_; mutable error_information error_information_; pqrs::string::replacement replacement_; symbol_map symbol_map_; std::vector<std::tr1::shared_ptr<app> > app_vector_; std::tr1::unordered_map<uint32_t, std::string> identifier_map_; std::vector<std::tr1::shared_ptr<essential_configuration> > essential_configurations_; remapclasses_initialize_vector remapclasses_initialize_vector_; uint32_t simultaneous_keycode_index_; preferences_node_tree<preferences_checkbox_node> preferences_checkbox_node_tree_; preferences_node_tree<preferences_number_node> preferences_number_node_tree_; }; } #endif <|endoftext|>
<commit_before>/*========================================================================= Copyright (c) Kitware Inc. All rights reserved. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware SAS 2012 #include "vtkHyperTreeGrid.h" #include "vtkHyperTreeGridAxisCut.h" #include "vtkHyperTreeGridSource.h" #include "vtkCamera.h" #include "vtkCellData.h" #include "vtkNew.h" #include "vtkPolyDataMapper.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" int TestHyperTreeGridAxisCut( int argc, char* argv[] ) { vtkNew<vtkHyperTreeGridSource> fractal; fractal->SetMaximumLevel( 3 ); fractal->SetGridSize( 3, 4, 2 ); fractal->SetDimension( 3 ); fractal->SetAxisBranchFactor( 3 ); vtkNew<vtkHyperTreeGridAxisCut> axisCut; axisCut->SetInputConnection( fractal->GetOutputPort() ); axisCut->SetPlaneNormalAxis( 2 ); axisCut->SetPlanePosition( .1 ); axisCut->Update(); vtkPolyData* pd = axisCut->GetOutput(); vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputConnection( axisCut->GetOutputPort() ); mapper->SetScalarRange( pd->GetCellData()->GetScalars()->GetRange() ); vtkNew<vtkActor> actor; actor->SetMapper( mapper.GetPointer() ); // Create camera vtkHyperTreeGrid* ht = fractal->GetOutput(); double bd[3]; ht->GetBounds( bd ); vtkNew<vtkCamera> camera; camera->SetClippingRange( 1., 100. ); camera->SetFocalPoint( ht->GetCenter() ); camera->SetPosition( -.8 * bd[1], 2.1 * bd[3], -4.8 * bd[5] ); // Create a renderer, add actors to it vtkNew<vtkRenderer> renderer; renderer->SetActiveCamera( camera.GetPointer() ); renderer->SetBackground( 1., 1., 1. ); renderer->AddActor( actor.GetPointer() ); // Create a renderWindow vtkNew<vtkRenderWindow> renWin; renWin->AddRenderer( renderer.GetPointer() ); renWin->SetSize( 300, 300 ); renWin->SetMultiSamples( 0 ); // Create interactor vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow( renWin.GetPointer() ); // Render and test renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); } // Clean up return 0; } <commit_msg>Activate hyper tree grid axis cut<commit_after>/*========================================================================= Copyright (c) Kitware Inc. All rights reserved. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware SAS 2012 #include "vtkHyperTreeGrid.h" #include "vtkHyperTreeGridAxisCut.h" #include "vtkHyperTreeGridSource.h" #include "vtkCamera.h" #include "vtkCellData.h" #include "vtkNew.h" #include "vtkPolyDataMapper.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" int TestHyperTreeGridAxisCut( int argc, char* argv[] ) { vtkNew<vtkHyperTreeGridSource> fractal; fractal->SetMaximumLevel( 3 ); fractal->SetGridSize( 3, 4, 2 ); fractal->SetDimension( 3 ); fractal->SetAxisBranchFactor( 3 ); vtkNew<vtkHyperTreeGridAxisCut> axisCut; axisCut->SetInputConnection( fractal->GetOutputPort() ); axisCut->SetPlaneNormalAxis( 2 ); axisCut->SetPlanePosition( .1 ); axisCut->Update(); vtkPolyData* pd = axisCut->GetOutput(); vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputConnection( axisCut->GetOutputPort() ); mapper->SetScalarRange( pd->GetCellData()->GetScalars()->GetRange() ); vtkNew<vtkActor> actor; actor->SetMapper( mapper.GetPointer() ); // Create camera vtkHyperTreeGrid* ht = fractal->GetOutput(); double bd[3]; ht->GetBounds( bd ); vtkNew<vtkCamera> camera; camera->SetClippingRange( 1., 100. ); camera->SetFocalPoint( ht->GetCenter() ); camera->SetPosition( -.8 * bd[1], 2.1 * bd[3], -4.8 * bd[5] ); // Create a renderer, add actors to it vtkNew<vtkRenderer> renderer; renderer->SetActiveCamera( camera.GetPointer() ); renderer->SetBackground( 1., 1., 1. ); renderer->AddActor( actor.GetPointer() ); // Create a renderWindow vtkNew<vtkRenderWindow> renWin; renWin->AddRenderer( renderer.GetPointer() ); renWin->SetSize( 300, 300 ); renWin->SetMultiSamples( 0 ); // Create interactor vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow( renWin.GetPointer() ); // Render and test renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); } return !retVal; } <|endoftext|>
<commit_before>#include "SequentialFactorizer.h" #include <vector> using namespace std; SequentialFactorizer::SequentialFactorizer(const BigInt& number, const SmpFactorizationElf& e) : elf(e), m(number), p(0), q(0), distribution(), engine(e.randomSeed()), generator(bind(distribution, engine)) { } void SequentialFactorizer::run() { while (!elf.finished && p == 0 && q == 0) { BigInt a = generateRandomNumberSmallerThan(m); BigInt aSquared = a * a; BigInt remainder = aSquared % m; iterator_pair range = remainders.equal_range(remainder); for (iterator it = range.first; it != range.second; it++) { const BigInt& b = it->second; BigInt bSquared = b * b; if (a > b) { if (aSquared - bSquared == m) { BigInt tmp = a + b; if (tmp == BigInt::ONE || tmp == m) continue; p = tmp; q = a - b; return; } } else { if (bSquared - aSquared == m) { BigInt tmp = a + b; if (tmp == BigInt::ONE || tmp == m) continue; p = tmp; q = b - a; return; } } } remainders.insert(pair<BigInt, BigInt>(remainder, a)); } } BigInt SequentialFactorizer::generateRandomNumberSmallerThan(const BigInt& number) const { BigInt result; size_t maximumItems = number.buffer().size(); if (maximumItems == 1) { uint32_t n = number.buffer().back(); return BigInt(generator() % n); } do { size_t actualItems = generator() % maximumItems + 1; vector<uint32_t> items; for (size_t i=0; i<actualItems; i++) { items.push_back(generator()); } result = BigInt(items); } while (result >= number); return result; } <commit_msg>Refactoring: initializer list instead of Object instantiation as parameter<commit_after>#include "SequentialFactorizer.h" #include <vector> using namespace std; SequentialFactorizer::SequentialFactorizer(const BigInt& number, const SmpFactorizationElf& e) : elf(e), m(number), p(0), q(0), distribution(), engine(e.randomSeed()), generator(bind(distribution, engine)) { } void SequentialFactorizer::run() { while (!elf.finished && p == 0 && q == 0) { BigInt a = generateRandomNumberSmallerThan(m); BigInt aSquared = a * a; BigInt remainder = aSquared % m; iterator_pair range = remainders.equal_range(remainder); for (iterator it = range.first; it != range.second; it++) { const BigInt& b = it->second; BigInt bSquared = b * b; if (a > b) { if (aSquared - bSquared == m) { BigInt tmp = a + b; if (tmp == BigInt::ONE || tmp == m) continue; p = tmp; q = a - b; return; } } else { if (bSquared - aSquared == m) { BigInt tmp = a + b; if (tmp == BigInt::ONE || tmp == m) continue; p = tmp; q = b - a; return; } } } remainders.insert({remainder, a}); } } BigInt SequentialFactorizer::generateRandomNumberSmallerThan(const BigInt& number) const { BigInt result; size_t maximumItems = number.buffer().size(); if (maximumItems == 1) { uint32_t n = number.buffer().back(); return BigInt(generator() % n); } do { size_t actualItems = generator() % maximumItems + 1; vector<uint32_t> items; for (size_t i=0; i<actualItems; i++) { items.push_back(generator()); } result = BigInt(items); } while (result >= number); return result; } <|endoftext|>
<commit_before>#ifndef __RIGID_BODY_HPP__ #define __RIGID_BODY_HPP__ #include <btBulletDynamicsCommon.h> #include <Components/Component.hh> #include <Entities/EntityData.hh> #include <Entities/Entity.hh> #include <Core/Engine.hh> #include <Managers/BulletDynamicManager.hpp> #include <BulletCollision/CollisionShapes/btShapeHull.h> #include <HACD/hacdHACD.h> #include <Utils/BtConversion.hpp> #include <Utils/MatrixConversion.hpp> #include <MediaFiles/CollisionShapeStaticFile.hpp> #include <MediaFiles/CollisionShapeDynamicFile.hpp> #include <MediaFiles/CollisionBoxFile.hpp> #include <MediaFiles/CollisionSphereFile.hpp> #include <memory> #include <Components/CollisionLayers.hpp> #include <Serialize/BulletWorldImporter/btBulletWorldImporter.h> #include <MediaFiles/AssetsManager.hpp> #include <cereal/archives/binary.hpp> #include <cereal/archives/json.hpp> #include <cereal/archives/portable_binary.hpp> #include <cereal/archives/xml.hpp> #include <cereal/types/set.hpp> #include <cereal/types/base_class.hpp> namespace Component { ATTRIBUTE_ALIGNED16(struct) RigidBody : public Component::ComponentBase<RigidBody> { BT_DECLARE_ALIGNED_ALLOCATOR(); typedef enum { SPHERE, BOX, MESH, UNDEFINED } CollisionShape; RigidBody() : ComponentBase(), _manager(nullptr), shapeType(UNDEFINED), mass(0.0f), inertia(btVector3(0.0f, 0.0f, 0.0f)), rotationConstraint(glm::vec3(1,1,1)), transformConstraint(glm::vec3(1,1,1)), meshName(""), _collisionShape(nullptr), _motionState(nullptr), _rigidBody(nullptr) { } void init(float _mass = 1.0f) { auto test = _entity->getScene()->getInstance<BulletCollisionManager>(); _manager = std::dynamic_pointer_cast<BulletDynamicManager>(_entity->getScene()->getInstance<BulletCollisionManager>()); assert(_manager != nullptr); mass = _mass; } virtual void reset() { if (_rigidBody != nullptr) { _manager->getWorld()->removeRigidBody(_rigidBody.get()); _rigidBody = nullptr; } if (_motionState != nullptr) { _motionState = nullptr; } if (_collisionShape != nullptr) { _collisionShape = nullptr; } shapeType = UNDEFINED; mass = 0.0f; inertia = btVector3(0.0f, 0.0f, 0.0f); rotationConstraint = glm::vec3(1, 1, 1); transformConstraint = glm::vec3(1, 1, 1); } btMotionState &getMotionState() { assert(_motionState != nullptr && "Motion state is NULL, RigidBody error. Tips : Have you setAcollisionShape to Component ?."); return *_motionState; } btCollisionShape &getShape() { assert(_collisionShape != nullptr && "Shape is NULL, RigidBody error. Tips : Have you setAcollisionShape to Component ?."); return *_collisionShape; } btRigidBody &getBody() { assert(_rigidBody != nullptr && "RigidBody is NULL. Tips : Have you setAcollisionShape to Component ?."); return *_rigidBody; } void setMass(float _mass) { mass = btScalar(_mass); } void setInertia(btVector3 const &v) { inertia = v; } void setCollisionShape(CollisionShape c, const std::string &_meshName = "") { if (c == UNDEFINED) return; auto mediaManager = _entity->getScene()->getInstance<AssetsManager>(); meshName = _meshName; _reset(); shapeType = c; btTransform transform; glm::vec3 position = posFromMat4(_entity->getLocalTransform()); glm::vec3 scale = scaleFromMat4(_entity->getLocalTransform()); glm::vec3 rot = rotFromMat4(_entity->getLocalTransform(), true); transform.setIdentity(); transform.setOrigin(convertGLMVectorToBullet(position)); transform.setRotation(btQuaternion(rot.x, rot.y, rot.z)); _motionState = std::shared_ptr<btMotionState>(new btDefaultMotionState(transform)); if (c == BOX) { _collisionShape = std::shared_ptr<btCollisionShape>(new btBoxShape(btVector3(0.5, 0.5, 0.5))); } else if (c == SPHERE) { _collisionShape = std::shared_ptr<btCollisionShape>(new btSphereShape(0.5)); } else if (c == MESH) { auto media = mediaManager->get(_meshName); if (!media) return; if (media->getType() == AMediaFile::COLLISION_SHAPE_DYNAMIC) { auto s = std::dynamic_pointer_cast<CollisionShapeDynamicFile>(mediaManager->get(_meshName)); _collisionShape = std::shared_ptr<btCollisionShape>(new btConvexHullShape(*s->shape.get())); } else if (media->getType() == AMediaFile::COLLISION_SHAPE_STATIC) { auto s = std::dynamic_pointer_cast<CollisionShapeStaticFile>(mediaManager->get(_meshName)); _collisionShape = std::shared_ptr<btCollisionShape>(new btScaledBvhTriangleMeshShape(s->shape.get(), btVector3(1, 1, 1))); } else if (media->getType() == AMediaFile::COLLISION_BOX) { auto s = std::dynamic_pointer_cast<CollisionBoxFile>(mediaManager->get(_meshName)); _collisionShape = std::shared_ptr<btCollisionShape>(new btBoxShape(*s->shape.get())); } else if (media->getType() == AMediaFile::COLLISION_SPHERE) { auto s = std::dynamic_pointer_cast<CollisionSphereFile>(mediaManager->get(_meshName)); _collisionShape = std::shared_ptr<btCollisionShape>(new btSphereShape(*s->shape.get())); } else std::cerr << "Collision mesh not found." << std::endl; } if (mass != 0) _collisionShape->calculateLocalInertia(mass, inertia); _collisionShape->setLocalScaling(convertGLMVectorToBullet(scale)); _rigidBody = std::shared_ptr<btRigidBody>(new btRigidBody(mass, _motionState.get(), _collisionShape.get(), inertia)); _rigidBody->setUserPointer(&_entity); _rigidBody->setAngularFactor(convertGLMVectorToBullet(rotationConstraint)); _rigidBody->setLinearFactor(convertGLMVectorToBullet(transformConstraint)); if (_rigidBody->isStaticObject()) { _rigidBody->setActivationState(DISABLE_SIMULATION); } _manager->getWorld()->addRigidBody(_rigidBody.get()); } void setRotationConstraint(bool x, bool y, bool z) { rotationConstraint = glm::vec3(static_cast<unsigned int>(x), static_cast<unsigned int>(y), static_cast<unsigned int>(z)); if (!_rigidBody) return; _rigidBody->setAngularFactor(convertGLMVectorToBullet(rotationConstraint)); } void setTransformConstraint(bool x, bool y, bool z) { transformConstraint = glm::vec3(static_cast<unsigned int>(x), static_cast<unsigned int>(y), static_cast<unsigned int>(z)); if (!_rigidBody) return; _rigidBody->setLinearFactor(convertGLMVectorToBullet(transformConstraint)); } virtual ~RigidBody(void) { if (_rigidBody != nullptr) { _manager->getWorld()->removeRigidBody(_rigidBody.get()); _rigidBody = nullptr; } if (_motionState != nullptr) _motionState = nullptr; if (_collisionShape != nullptr) _collisionShape = nullptr; } ////// //// // Serialization template <typename Archive> Base *unserialize(Archive &ar, Entity e) { auto res = new RigidBody(); res->setEntity(e); res->init(); ar(*res); res->setCollisionShape(res->shapeType, res->meshName); return res; } template <typename Archive> void save(Archive &ar) const { float _mass = mass; glm::vec3 _inertia = convertBulletVectorToGLM(inertia); ar(_mass, shapeType, _inertia, rotationConstraint, transformConstraint, meshName); } template <typename Archive> void load(Archive &ar) { float _mass; glm::vec3 _inertia; ar(_mass, shapeType, _inertia, rotationConstraint, transformConstraint, meshName); mass = btScalar(_mass); inertia = convertGLMVectorToBullet(_inertia); } // !Serialization //// ////// std::shared_ptr<BulletDynamicManager> _manager; CollisionShape shapeType; btScalar mass; btVector3 inertia; glm::vec3 rotationConstraint; glm::vec3 transformConstraint; std::string meshName; std::shared_ptr<btCollisionShape> _collisionShape; std::shared_ptr<btMotionState> _motionState; std::shared_ptr<btRigidBody> _rigidBody; private: RigidBody(RigidBody const &); RigidBody &operator=(RigidBody const &); void _reset() { if (_rigidBody != nullptr) { _manager->getWorld()->removeRigidBody(_rigidBody.get()); _rigidBody = nullptr; } if (_motionState != nullptr) { _motionState = nullptr; } if (_collisionShape != nullptr) { _collisionShape = nullptr; } } }; } #endif //!__RIGID_BODY_HPP__<commit_msg>Close #105 Serialize bullet settings on Rigid body<commit_after>#ifndef __RIGID_BODY_HPP__ #define __RIGID_BODY_HPP__ #include <btBulletDynamicsCommon.h> #include <Components/Component.hh> #include <Entities/EntityData.hh> #include <Entities/Entity.hh> #include <Core/Engine.hh> #include <Managers/BulletDynamicManager.hpp> #include <BulletCollision/CollisionShapes/btShapeHull.h> #include <HACD/hacdHACD.h> #include <Utils/BtConversion.hpp> #include <Utils/MatrixConversion.hpp> #include <MediaFiles/CollisionShapeStaticFile.hpp> #include <MediaFiles/CollisionShapeDynamicFile.hpp> #include <MediaFiles/CollisionBoxFile.hpp> #include <MediaFiles/CollisionSphereFile.hpp> #include <memory> #include <Components/CollisionLayers.hpp> #include <Serialize/BulletWorldImporter/btBulletWorldImporter.h> #include <MediaFiles/AssetsManager.hpp> #include <cereal/archives/binary.hpp> #include <cereal/archives/json.hpp> #include <cereal/archives/portable_binary.hpp> #include <cereal/archives/xml.hpp> #include <cereal/types/set.hpp> #include <cereal/types/base_class.hpp> namespace Component { ATTRIBUTE_ALIGNED16(struct) RigidBody : public Component::ComponentBase<RigidBody> { BT_DECLARE_ALIGNED_ALLOCATOR(); typedef enum { SPHERE, BOX, MESH, UNDEFINED } CollisionShape; RigidBody() : ComponentBase(), _manager(nullptr), shapeType(UNDEFINED), mass(0.0f), inertia(btVector3(0.0f, 0.0f, 0.0f)), rotationConstraint(glm::vec3(1,1,1)), transformConstraint(glm::vec3(1,1,1)), meshName(""), _collisionShape(nullptr), _motionState(nullptr), _rigidBody(nullptr) { } void init(float _mass = 1.0f) { auto test = _entity->getScene()->getInstance<BulletCollisionManager>(); _manager = std::dynamic_pointer_cast<BulletDynamicManager>(_entity->getScene()->getInstance<BulletCollisionManager>()); assert(_manager != nullptr); mass = _mass; } virtual void reset() { if (_rigidBody != nullptr) { _manager->getWorld()->removeRigidBody(_rigidBody.get()); _rigidBody = nullptr; } if (_motionState != nullptr) { _motionState = nullptr; } if (_collisionShape != nullptr) { _collisionShape = nullptr; } shapeType = UNDEFINED; mass = 0.0f; inertia = btVector3(0.0f, 0.0f, 0.0f); rotationConstraint = glm::vec3(1, 1, 1); transformConstraint = glm::vec3(1, 1, 1); } btMotionState &getMotionState() { assert(_motionState != nullptr && "Motion state is NULL, RigidBody error. Tips : Have you setAcollisionShape to Component ?."); return *_motionState; } btCollisionShape &getShape() { assert(_collisionShape != nullptr && "Shape is NULL, RigidBody error. Tips : Have you setAcollisionShape to Component ?."); return *_collisionShape; } btRigidBody &getBody() { assert(_rigidBody != nullptr && "RigidBody is NULL. Tips : Have you setAcollisionShape to Component ?."); return *_rigidBody; } void setMass(float _mass) { mass = btScalar(_mass); } void setInertia(btVector3 const &v) { inertia = v; } void setCollisionShape(CollisionShape c, const std::string &_meshName = "") { if (c == UNDEFINED) return; auto mediaManager = _entity->getScene()->getInstance<AssetsManager>(); meshName = _meshName; _reset(); shapeType = c; btTransform transform; glm::vec3 position = posFromMat4(_entity->getLocalTransform()); glm::vec3 scale = scaleFromMat4(_entity->getLocalTransform()); glm::vec3 rot = rotFromMat4(_entity->getLocalTransform(), true); transform.setIdentity(); transform.setOrigin(convertGLMVectorToBullet(position)); transform.setRotation(btQuaternion(rot.x, rot.y, rot.z)); _motionState = std::shared_ptr<btMotionState>(new btDefaultMotionState(transform)); if (c == BOX) { _collisionShape = std::shared_ptr<btCollisionShape>(new btBoxShape(btVector3(0.5, 0.5, 0.5))); } else if (c == SPHERE) { _collisionShape = std::shared_ptr<btCollisionShape>(new btSphereShape(0.5)); } else if (c == MESH) { auto media = mediaManager->get(_meshName); if (!media) return; if (media->getType() == AMediaFile::COLLISION_SHAPE_DYNAMIC) { auto s = std::dynamic_pointer_cast<CollisionShapeDynamicFile>(mediaManager->get(_meshName)); _collisionShape = std::shared_ptr<btCollisionShape>(new btConvexHullShape(*s->shape.get())); } else if (media->getType() == AMediaFile::COLLISION_SHAPE_STATIC) { auto s = std::dynamic_pointer_cast<CollisionShapeStaticFile>(mediaManager->get(_meshName)); _collisionShape = std::shared_ptr<btCollisionShape>(new btScaledBvhTriangleMeshShape(s->shape.get(), btVector3(1, 1, 1))); } else if (media->getType() == AMediaFile::COLLISION_BOX) { auto s = std::dynamic_pointer_cast<CollisionBoxFile>(mediaManager->get(_meshName)); _collisionShape = std::shared_ptr<btCollisionShape>(new btBoxShape(*s->shape.get())); } else if (media->getType() == AMediaFile::COLLISION_SPHERE) { auto s = std::dynamic_pointer_cast<CollisionSphereFile>(mediaManager->get(_meshName)); _collisionShape = std::shared_ptr<btCollisionShape>(new btSphereShape(*s->shape.get())); } else std::cerr << "Collision mesh not found." << std::endl; } if (mass != 0) _collisionShape->calculateLocalInertia(mass, inertia); _collisionShape->setLocalScaling(convertGLMVectorToBullet(scale)); _rigidBody = std::shared_ptr<btRigidBody>(new btRigidBody(mass, _motionState.get(), _collisionShape.get(), inertia)); _rigidBody->setUserPointer(&_entity); _rigidBody->setAngularFactor(convertGLMVectorToBullet(rotationConstraint)); _rigidBody->setLinearFactor(convertGLMVectorToBullet(transformConstraint)); if (_rigidBody->isStaticObject()) { _rigidBody->setActivationState(DISABLE_SIMULATION); } _manager->getWorld()->addRigidBody(_rigidBody.get()); } void setRotationConstraint(bool x, bool y, bool z) { rotationConstraint = glm::vec3(static_cast<unsigned int>(x), static_cast<unsigned int>(y), static_cast<unsigned int>(z)); if (!_rigidBody) return; _rigidBody->setAngularFactor(convertGLMVectorToBullet(rotationConstraint)); } void setTransformConstraint(bool x, bool y, bool z) { transformConstraint = glm::vec3(static_cast<unsigned int>(x), static_cast<unsigned int>(y), static_cast<unsigned int>(z)); if (!_rigidBody) return; _rigidBody->setLinearFactor(convertGLMVectorToBullet(transformConstraint)); } virtual ~RigidBody(void) { if (_rigidBody != nullptr) { _manager->getWorld()->removeRigidBody(_rigidBody.get()); _rigidBody = nullptr; } if (_motionState != nullptr) _motionState = nullptr; if (_collisionShape != nullptr) _collisionShape = nullptr; } ////// //// // Serialization template <typename Archive> Base *unserialize(Archive &ar, Entity e) { auto res = new RigidBody(); res->setEntity(e); res->init(); ar(*res); return res; } template <typename Archive> void save(Archive &ar) const { float _mass = mass; glm::vec3 _inertia = convertBulletVectorToGLM(inertia); ar(_mass, shapeType, _inertia, rotationConstraint, transformConstraint, meshName); ar(_rigidBody->getBroadphaseHandle()->m_collisionFilterGroup, _rigidBody->getBroadphaseHandle()->m_collisionFilterMask); float friction = _rigidBody->getFriction(); float restitution = _rigidBody->getRestitution(); ar(friction, restitution); ar(_rigidBody->getFlags()); float margin = _collisionShape->getMargin(); ar(margin); } template <typename Archive> void load(Archive &ar) { float _mass; glm::vec3 _inertia; ar(_mass, shapeType, _inertia, rotationConstraint, transformConstraint, meshName); mass = btScalar(_mass); inertia = convertGLMVectorToBullet(_inertia); setCollisionShape(shapeType, meshName); short int layer; short int mask; ar(layer, mask); getBody().getBroadphaseHandle()->m_collisionFilterGroup = layer; getBody().getBroadphaseHandle()->m_collisionFilterMask = mask; float friction, restitution; ar(friction, restitution); getBody().setFriction(btScalar(friction)); getBody().setRestitution(btScalar(restitution)); int flags; ar(flags); getBody().setFlags(flags); float margin; ar(margin); _collisionShape->setMargin(margin); } // !Serialization //// ////// std::shared_ptr<BulletDynamicManager> _manager; CollisionShape shapeType; btScalar mass; btVector3 inertia; glm::vec3 rotationConstraint; glm::vec3 transformConstraint; std::string meshName; std::shared_ptr<btCollisionShape> _collisionShape; std::shared_ptr<btMotionState> _motionState; std::shared_ptr<btRigidBody> _rigidBody; private: RigidBody(RigidBody const &); RigidBody &operator=(RigidBody const &); void _reset() { if (_rigidBody != nullptr) { _manager->getWorld()->removeRigidBody(_rigidBody.get()); _rigidBody = nullptr; } if (_motionState != nullptr) { _motionState = nullptr; } if (_collisionShape != nullptr) { _collisionShape = nullptr; } } }; } #endif //!__RIGID_BODY_HPP__<|endoftext|>
<commit_before>// sdl_main.cpp #ifdef _WIN32 # define WINDOWS_LEAN_AND_MEAN # define NOMINMAX # include <windows.h> #endif #include <GL/glew.h> #include <SDL.h> #include <SDL_syswm.h> #undef main #include "ShaderFunctions.h" #include "Timer.h" #include "g_textures.h" Timer g_timer; int winw = 800; int winh = 600; struct renderpass { GLuint prog; GLint uloc_iResolution; GLint uloc_iGlobalTime; GLint uloc_iChannelResolution; //iChannelTime not implemented GLint uloc_iChannel0; GLint uloc_iChannel1; GLint uloc_iChannel2; GLint uloc_iChannel3; GLint uloc_iMouse; GLint uloc_iDate; GLint uloc_iBlockOffset; GLint uloc_iSampleRate; }; struct Shadertoy { renderpass image; renderpass sound; }; Shadertoy g_toy; void keyboard(const SDL_Event& event, int key, int codes, int action, int mods) { (void)codes; (void)mods; if (action == SDL_KEYDOWN) { switch (key) { default: break; case SDLK_ESCAPE: SDL_Quit(); exit(0); break; } } } void PollEvents() { SDL_Event event; while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: case SDL_KEYUP: keyboard(event, event.key.keysym.sym, 0, event.key.type, 0); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: break; case SDL_MOUSEMOTION: break; case SDL_MOUSEWHEEL: break; case SDL_WINDOWEVENT: break; case SDL_QUIT: exit(0); break; default: break; } } } void display() { const renderpass& r = g_toy.image; glUseProgram(r.prog); if (r.uloc_iResolution > -1) glUniform3f(r.uloc_iResolution, (float)winw, (float)winh, 1.f); if (r.uloc_iGlobalTime > -1) glUniform1f(r.uloc_iGlobalTime, g_timer.seconds()); if (r.uloc_iMouse > -1) glUniform4f(r.uloc_iMouse, 0.f, 0.f, 0.f, 0.f); if (r.uloc_iDate > -1) glUniform4f(r.uloc_iDate, 2015.f, 3.f, 6.f, 6.f); glRecti(-1,-1,1,1); } // // Audio // struct { SDL_AudioSpec spec; Uint8 *sound; /* Pointer to wave data */ Uint32 soundlen; /* Length of wave data */ int soundpos; /* Current play position */ } wave; void SDLCALL fillerup(void *unused, Uint8 * stream, int len) { Uint8 *waveptr; int waveleft; waveptr = wave.sound + wave.soundpos; waveleft = wave.soundlen - wave.soundpos; while (waveleft <= len) { // wrap condition SDL_memcpy(stream, waveptr, waveleft); stream += waveleft; len -= waveleft; waveptr = wave.sound; waveleft = wave.soundlen; wave.soundpos = 0; } SDL_memcpy(stream, waveptr, len); wave.soundpos += len; } void play_audio() { wave.spec.freq = 44100; wave.spec.format = AUDIO_U8; //AUDIO_S16LSB; wave.spec.channels = 2; wave.spec.callback = fillerup; const int mPlayTime = 60; // Shadertoy gives 60 seconds of audio wave.soundlen = mPlayTime * wave.spec.freq; wave.sound = new Uint8[2*wave.soundlen]; glViewport(0,0,512,512); const renderpass& r = g_toy.sound; glUseProgram(r.prog); unsigned char* mData = new unsigned char[512*512*4]; int mTmpBufferSamples = 262144; int mPlaySamples = wave.soundlen; int numBlocks = mPlaySamples / mTmpBufferSamples; for (int j=0; j<numBlocks; ++j) { int off = j * mTmpBufferSamples; if (r.uloc_iBlockOffset > -1) glUniform1f(r.uloc_iBlockOffset, (float)off / (float)wave.spec.freq); glRecti(-1,-1,1,1); // mData: Uint8Array[1048576] glReadPixels(0,0,512,512, GL_RGBA, GL_UNSIGNED_BYTE, mData); for (int i = 0; i<mTmpBufferSamples; ++i) { const float aL = -1.0f + 2.0f*((float)mData[4 * i + 0] + 256.0f*(float)mData[4 * i + 1]) / 65535.0f; const float aR = -1.0f + 2.0f*((float)mData[4 * i + 2] + 256.0f*(float)mData[4 * i + 3]) / 65535.0f; wave.sound[2*(off + i) ] = (unsigned char)(.5f*(1.f+aL) * 255.f); wave.sound[2*(off + i)+1] = (unsigned char)(.5f*(1.f+aR) * 255.f); } } delete [] mData; if (SDL_OpenAudio(&wave.spec, NULL) < 0) { SDL_FreeWAV(wave.sound); SDL_Quit(); exit(2); } SDL_PauseAudio(0); // Start playing } int main(void) { ///@todo cmd line aargs if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); int winw = 800; int winh = 600; SDL_Window* pWindow = SDL_CreateWindow( "kinderegg", 100,100, winw, winh, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); // thank you http://www.brandonfoltz.com/2013/12/example-using-opengl-3-0-with-sdl2-and-glew/ SDL_GLContext glContext = SDL_GL_CreateContext(pWindow); if (glContext == NULL) { printf("There was an error creating the OpenGL context!\n"); return 0; } const unsigned char *version = glGetString(GL_VERSION); if (version == NULL) { printf("There was an error creating the OpenGL context!\n"); return 1; } SDL_GL_MakeCurrent(pWindow, glContext); // Don't forget to initialize Glew, turn glewExperimental on to // avoid problems fetching function pointers... glewExperimental = GL_TRUE; const GLenum l_Result = glewInit(); if (l_Result != GLEW_OK) { exit(EXIT_FAILURE); } renderpass& r = g_toy.image; r.prog = makeShaderFromSource("passthru.vert", "image.frag"); r.uloc_iResolution = glGetUniformLocation(r.prog, "iResolution"); r.uloc_iGlobalTime = glGetUniformLocation(r.prog, "iGlobalTime"); r.uloc_iChannelResolution = glGetUniformLocation(r.prog, "iChannelResolution"); r.uloc_iChannel0 = glGetUniformLocation(r.prog, "iChannel0"); r.uloc_iChannel1 = glGetUniformLocation(r.prog, "iChannel1"); r.uloc_iChannel2 = glGetUniformLocation(r.prog, "iChannel2"); r.uloc_iChannel3 = glGetUniformLocation(r.prog, "iChannel3"); r.uloc_iMouse = glGetUniformLocation(r.prog, "iMouse"); r.uloc_iDate = glGetUniformLocation(r.prog, "iDate"); renderpass& s = g_toy.sound; s.prog = makeShaderFromSource("passthru.vert", "sound.frag"); s.uloc_iBlockOffset = glGetUniformLocation(s.prog, "iBlockOffset"); s.uloc_iSampleRate = glGetUniformLocation(s.prog, "iSampleRate"); play_audio(); glViewport(0,0, winw, winh); int quit = 0; while (quit == 0) { PollEvents(); display(); SDL_GL_SwapWindow(pWindow); } SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(pWindow); SDL_CloseAudio(); SDL_FreeWAV(wave.sound); SDL_Quit(); } <commit_msg>First pass at texture loading.<commit_after>// sdl_main.cpp #ifdef _WIN32 # define WINDOWS_LEAN_AND_MEAN # define NOMINMAX # include <windows.h> #endif #include <GL/glew.h> #include <SDL.h> #include <SDL_syswm.h> #undef main #include "ShaderFunctions.h" #include "Timer.h" #include "g_textures.h" Timer g_timer; int winw = 800; int winh = 600; struct renderpass { GLuint prog; GLint uloc_iResolution; GLint uloc_iGlobalTime; GLint uloc_iChannelResolution; //iChannelTime not implemented GLint uloc_iChannel0; GLint uloc_iChannel1; GLint uloc_iChannel2; GLint uloc_iChannel3; GLint uloc_iMouse; GLint uloc_iDate; GLint uloc_iBlockOffset; GLint uloc_iSampleRate; }; struct Shadertoy { renderpass image; renderpass sound; }; Shadertoy g_toy; void keyboard(const SDL_Event& event, int key, int codes, int action, int mods) { (void)codes; (void)mods; if (action == SDL_KEYDOWN) { switch (key) { default: break; case SDLK_ESCAPE: SDL_Quit(); exit(0); break; } } } void PollEvents() { SDL_Event event; while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: case SDL_KEYUP: keyboard(event, event.key.keysym.sym, 0, event.key.type, 0); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: break; case SDL_MOUSEMOTION: break; case SDL_MOUSEWHEEL: break; case SDL_WINDOWEVENT: break; case SDL_QUIT: exit(0); break; default: break; } } } void display() { const renderpass& r = g_toy.image; glUseProgram(r.prog); if (r.uloc_iResolution > -1) glUniform3f(r.uloc_iResolution, (float)winw, (float)winh, 1.f); if (r.uloc_iGlobalTime > -1) glUniform1f(r.uloc_iGlobalTime, g_timer.seconds()); if (r.uloc_iMouse > -1) glUniform4f(r.uloc_iMouse, 0.f, 0.f, 0.f, 0.f); if (r.uloc_iDate > -1) glUniform4f(r.uloc_iDate, 2015.f, 3.f, 6.f, 6.f); glRecti(-1,-1,1,1); } // // Audio // struct { SDL_AudioSpec spec; Uint8 *sound; /* Pointer to wave data */ Uint32 soundlen; /* Length of wave data */ int soundpos; /* Current play position */ } wave; void SDLCALL fillerup(void *unused, Uint8 * stream, int len) { Uint8 *waveptr; int waveleft; waveptr = wave.sound + wave.soundpos; waveleft = wave.soundlen - wave.soundpos; while (waveleft <= len) { // wrap condition SDL_memcpy(stream, waveptr, waveleft); stream += waveleft; len -= waveleft; waveptr = wave.sound; waveleft = wave.soundlen; wave.soundpos = 0; } SDL_memcpy(stream, waveptr, len); wave.soundpos += len; } void play_audio() { wave.spec.freq = 44100; wave.spec.format = AUDIO_U8; //AUDIO_S16LSB; wave.spec.channels = 2; wave.spec.callback = fillerup; const int mPlayTime = 60; // Shadertoy gives 60 seconds of audio wave.soundlen = mPlayTime * wave.spec.freq; wave.sound = new Uint8[2*wave.soundlen]; glViewport(0,0,512,512); const renderpass& r = g_toy.sound; glUseProgram(r.prog); unsigned char* mData = new unsigned char[512*512*4]; int mTmpBufferSamples = 262144; int mPlaySamples = wave.soundlen; int numBlocks = mPlaySamples / mTmpBufferSamples; for (int j=0; j<numBlocks; ++j) { int off = j * mTmpBufferSamples; if (r.uloc_iBlockOffset > -1) glUniform1f(r.uloc_iBlockOffset, (float)off / (float)wave.spec.freq); glRecti(-1,-1,1,1); // mData: Uint8Array[1048576] glReadPixels(0,0,512,512, GL_RGBA, GL_UNSIGNED_BYTE, mData); for (int i = 0; i<mTmpBufferSamples; ++i) { const float aL = -1.0f + 2.0f*((float)mData[4 * i + 0] + 256.0f*(float)mData[4 * i + 1]) / 65535.0f; const float aR = -1.0f + 2.0f*((float)mData[4 * i + 2] + 256.0f*(float)mData[4 * i + 3]) / 65535.0f; wave.sound[2*(off + i) ] = (unsigned char)(.5f*(1.f+aL) * 255.f); wave.sound[2*(off + i)+1] = (unsigned char)(.5f*(1.f+aR) * 255.f); } } delete [] mData; if (SDL_OpenAudio(&wave.spec, NULL) < 0) { SDL_FreeWAV(wave.sound); SDL_Quit(); exit(2); } SDL_PauseAudio(0); // Start playing } int main(void) { ///@todo cmd line aargs if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); int winw = 800; int winh = 600; SDL_Window* pWindow = SDL_CreateWindow( "kinderegg", 100,100, winw, winh, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); // thank you http://www.brandonfoltz.com/2013/12/example-using-opengl-3-0-with-sdl2-and-glew/ SDL_GLContext glContext = SDL_GL_CreateContext(pWindow); if (glContext == NULL) { printf("There was an error creating the OpenGL context!\n"); return 0; } const unsigned char *version = glGetString(GL_VERSION); if (version == NULL) { printf("There was an error creating the OpenGL context!\n"); return 1; } SDL_GL_MakeCurrent(pWindow, glContext); // Don't forget to initialize Glew, turn glewExperimental on to // avoid problems fetching function pointers... glewExperimental = GL_TRUE; const GLenum l_Result = glewInit(); if (l_Result != GLEW_OK) { exit(EXIT_FAILURE); } renderpass& r = g_toy.image; r.prog = makeShaderFromSource("passthru.vert", "image.frag"); r.uloc_iResolution = glGetUniformLocation(r.prog, "iResolution"); r.uloc_iGlobalTime = glGetUniformLocation(r.prog, "iGlobalTime"); r.uloc_iChannelResolution = glGetUniformLocation(r.prog, "iChannelResolution"); r.uloc_iChannel0 = glGetUniformLocation(r.prog, "iChannel0"); r.uloc_iChannel1 = glGetUniformLocation(r.prog, "iChannel1"); r.uloc_iChannel2 = glGetUniformLocation(r.prog, "iChannel2"); r.uloc_iChannel3 = glGetUniformLocation(r.prog, "iChannel3"); r.uloc_iMouse = glGetUniformLocation(r.prog, "iMouse"); r.uloc_iDate = glGetUniformLocation(r.prog, "iDate"); { GLuint t0 = 0; glActiveTexture(GL_TEXTURE0); glGenTextures(1, &t0); glBindTexture(GL_TEXTURE_2D, t0); GLuint mode = 0; switch (tex00d) { default:break; case 1: mode = GL_LUMINANCE; break; case 3: mode = GL_RGB; break; case 4: mode = GL_RGBA; break; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex00w, tex00h, 0, GL_RGB, GL_UNSIGNED_BYTE, tex00); if (r.uloc_iChannel0 > -1) glUniform1i(r.uloc_iChannel0, t0); } renderpass& s = g_toy.sound; s.prog = makeShaderFromSource("passthru.vert", "sound.frag"); s.uloc_iBlockOffset = glGetUniformLocation(s.prog, "iBlockOffset"); s.uloc_iSampleRate = glGetUniformLocation(s.prog, "iSampleRate"); play_audio(); glViewport(0,0, winw, winh); int quit = 0; while (quit == 0) { PollEvents(); display(); SDL_GL_SwapWindow(pWindow); } SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(pWindow); SDL_CloseAudio(); SDL_FreeWAV(wave.sound); SDL_Quit(); } <|endoftext|>
<commit_before>#include "selectors.hh" #include "string.hh" #include <algorithm> #include <boost/optional.hpp> namespace Kakoune { Selection select_line(const Buffer& buffer, const Selection& selection) { Utf8Iterator first = buffer.iterator_at(selection.last()); if (*first == '\n' and first + 1 != buffer.end()) ++first; while (first != buffer.begin() and *(first - 1) != '\n') --first; Utf8Iterator last = first; while (last + 1 != buffer.end() and *last != '\n') ++last; return utf8_range(first, last); } Selection select_matching(const Buffer& buffer, const Selection& selection) { std::vector<Codepoint> matching_pairs = { '(', ')', '{', '}', '[', ']', '<', '>' }; Utf8Iterator it = buffer.iterator_at(selection.last()); std::vector<Codepoint>::iterator match = matching_pairs.end(); while (not is_eol(*it)) { match = std::find(matching_pairs.begin(), matching_pairs.end(), *it); if (match != matching_pairs.end()) break; ++it; } if (match == matching_pairs.end()) return selection; Utf8Iterator begin = it; if (((match - matching_pairs.begin()) % 2) == 0) { int level = 0; const Codepoint opening = *match; const Codepoint closing = *(match+1); while (it != buffer.end()) { if (*it == opening) ++level; else if (*it == closing and --level == 0) return utf8_range(begin, it); ++it; } } else { int level = 0; const Codepoint opening = *(match-1); const Codepoint closing = *match; while (true) { if (*it == closing) ++level; else if (*it == opening and --level == 0) return utf8_range(begin, it); if (it == buffer.begin()) break; --it; } } return selection; } // c++14 will add std::optional, so we use boost::optional until then using boost::optional; static optional<Range> find_surrounding(const Buffer& buffer, BufferCoord coord, CodepointPair matching, ObjectFlags flags, int init_level) { const bool to_begin = flags & ObjectFlags::ToBegin; const bool to_end = flags & ObjectFlags::ToEnd; const bool nestable = matching.first != matching.second; auto pos = buffer.iterator_at(coord); Utf8Iterator first = pos; if (to_begin) { int level = nestable ? init_level : 0; while (first != buffer.begin()) { if (nestable and first != pos and *first == matching.second) ++level; else if (*first == matching.first) { if (level == 0) break; else --level; } --first; } if (level != 0 or *first != matching.first) return optional<Range>{}; } Utf8Iterator last = pos; if (to_end) { int level = nestable ? init_level : 0; while (last != buffer.end()) { if (nestable and last != pos and *last == matching.first) ++level; else if (*last == matching.second) { if (level == 0) break; else --level; } ++last; } if (level != 0 or last == buffer.end()) return optional<Range>{}; } if (flags & ObjectFlags::Inner) { if (to_begin and first != last) ++first; if (to_end and first != last) --last; } return to_end ? utf8_range(first, last) : utf8_range(last, first); } Selection select_surrounding(const Buffer& buffer, const Selection& selection, CodepointPair matching, int level, ObjectFlags flags) { const bool nestable = matching.first != matching.second; auto pos = selection.last(); if (not nestable or flags & ObjectFlags::Inner) { if (auto res = find_surrounding(buffer, pos, matching, flags, level)) return *res; return selection; } auto c = buffer.byte_at(pos); if ((flags == ObjectFlags::ToBegin and c == matching.first) or (flags == ObjectFlags::ToEnd and c == matching.second)) ++level; auto res = find_surrounding(buffer, pos, matching, flags, level); if (not res) return selection; if (flags == (ObjectFlags::ToBegin | ObjectFlags::ToEnd) and res->min() == selection.min() and res->max() == selection.max()) { if (auto res_parent = find_surrounding(buffer, pos, matching, flags, level+1)) return Selection{*res_parent}; } return *res; } Selection select_to(const Buffer& buffer, const Selection& selection, Codepoint c, int count, bool inclusive) { Utf8Iterator begin = buffer.iterator_at(selection.last()); Utf8Iterator end = begin; do { ++end; skip_while(end, buffer.end(), [c](Codepoint cur) { return cur != c; }); if (end == buffer.end()) return selection; } while (--count > 0); return utf8_range(begin, inclusive ? end : end-1); } Selection select_to_reverse(const Buffer& buffer, const Selection& selection, Codepoint c, int count, bool inclusive) { Utf8Iterator begin = buffer.iterator_at(selection.last()); Utf8Iterator end = begin; do { --end; skip_while_reverse(end, buffer.begin(), [c](Codepoint cur) { return cur != c; }); if (end == buffer.begin()) return selection; } while (--count > 0); return utf8_range(begin, inclusive ? end : end+1); } Selection select_to_eol(const Buffer& buffer, const Selection& selection) { Utf8Iterator begin = buffer.iterator_at(selection.last()); Utf8Iterator end = begin + 1; skip_while(end, buffer.end(), [](Codepoint cur) { return not is_eol(cur); }); return utf8_range(begin, end-1); } Selection select_to_eol_reverse(const Buffer& buffer, const Selection& selection) { Utf8Iterator begin = buffer.iterator_at(selection.last()); Utf8Iterator end = begin - 1; skip_while_reverse(end, buffer.begin(), [](Codepoint cur) { return not is_eol(cur); }); return utf8_range(begin, end == buffer.begin() ? end : end+1); } Selection select_whole_sentence(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { BufferIterator first = buffer.iterator_at(selection.last()); BufferIterator last = first; if (flags & ObjectFlags::ToBegin) { bool saw_non_blank = false; while (first != buffer.begin()) { char cur = *first; char prev = *(first-1); if (not is_blank(cur)) saw_non_blank = true; if (is_eol(prev) and is_eol(cur)) { ++first; break; } else if (prev == '.' or prev == ';' or prev == '!' or prev == '?') { if (saw_non_blank) break; else if (flags & ObjectFlags::ToEnd) last = first-1; } --first; } skip_while(first, buffer.end(), is_blank); } if (flags & ObjectFlags::ToEnd) { while (last != buffer.end()) { char cur = *last; if (cur == '.' or cur == ';' or cur == '!' or cur == '?' or (is_eol(cur) and (last+1 == buffer.end() or is_eol(*(last+1))))) break; ++last; } if (not (flags & ObjectFlags::Inner) and last != buffer.end()) { ++last; skip_while(last, buffer.end(), is_blank); --last; } } return (flags & ObjectFlags::ToEnd) ? Selection{first.coord(), last.coord()} : Selection{last.coord(), first.coord()}; } Selection select_whole_paragraph(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { BufferIterator first = buffer.iterator_at(selection.last()); BufferIterator last = first; if (flags & ObjectFlags::ToBegin and first != buffer.begin()) { skip_while_reverse(first, buffer.begin(), is_eol); if (flags & ObjectFlags::ToEnd) last = first; while (first != buffer.begin()) { char cur = *first; char prev = *(first-1); if (is_eol(prev) and is_eol(cur)) { ++first; break; } --first; } } if (flags & ObjectFlags::ToEnd) { while (last != buffer.end()) { char cur = *last; char prev = *(last-1); if (is_eol(cur) and is_eol(prev)) { if (not (flags & ObjectFlags::Inner)) skip_while(last, buffer.end(), is_eol); break; } ++last; } --last; } return (flags & ObjectFlags::ToEnd) ? Selection{first.coord(), last.coord()} : Selection{last.coord(), first.coord()}; } static CharCount get_indent(const String& str, int tabstop) { CharCount indent = 0; for (auto& c : str) { if (c == ' ') ++indent; else if (c =='\t') indent = (indent / tabstop + 1) * tabstop; else break; } return indent; } Selection select_whole_indent(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { int tabstop = buffer.options()["tabstop"].get<int>(); LineCount line = selection.last().line; auto indent = get_indent(buffer[line], tabstop); LineCount begin_line = line - 1; if (flags & ObjectFlags::ToBegin) { while (begin_line >= 0 and (buffer[begin_line] == "\n" or get_indent(buffer[begin_line], tabstop) >= indent)) --begin_line; } ++begin_line; LineCount end_line = line + 1; if (flags & ObjectFlags::ToEnd) { LineCount end = buffer.line_count(); while (end_line < end and (buffer[end_line] == "\n" or get_indent(buffer[end_line], tabstop) >= indent)) ++end_line; } --end_line; BufferCoord first = begin_line; // keep the first line indent in inner mode if (flags & ObjectFlags::Inner) { CharCount i = 0; for (; i < indent; ++first.column) { auto c = buffer.byte_at(first); if (c == ' ') ++i; if (c == '\t') i = (i / tabstop + 1) * tabstop; } } return Selection{first, {end_line, buffer[end_line].length() - 1}}; } Selection select_whole_lines(const Buffer& buffer, const Selection& selection) { // no need to be utf8 aware for is_eol as we only use \n as line seperator BufferIterator first = buffer.iterator_at(selection.first()); BufferIterator last = buffer.iterator_at(selection.last()); BufferIterator& to_line_start = first <= last ? first : last; BufferIterator& to_line_end = first <= last ? last : first; --to_line_start; skip_while_reverse(to_line_start, buffer.begin(), [](char cur) { return not is_eol(cur); }); if (is_eol(*to_line_start)) ++to_line_start; skip_while(to_line_end, buffer.end(), [](char cur) { return not is_eol(cur); }); if (to_line_end == buffer.end()) --to_line_end; return Selection(first.coord(), last.coord()); } Selection trim_partial_lines(const Buffer& buffer, const Selection& selection) { // same as select_whole_lines BufferIterator first = buffer.iterator_at(selection.first()); BufferIterator last = buffer.iterator_at(selection.last()); BufferIterator& to_line_start = first <= last ? first : last; BufferIterator& to_line_end = first <= last ? last : first; while (to_line_start != buffer.begin() and *(to_line_start-1) != '\n') ++to_line_start; while (*(to_line_end+1) != '\n' and to_line_end != to_line_start) --to_line_end; return Selection(first.coord(), last.coord()); } void select_whole_buffer(const Buffer& buffer, SelectionList& selections) { selections = SelectionList{ Selection({0,0}, buffer.back_coord()) }; } void select_all_matches(const Buffer& buffer, SelectionList& selections, const Regex& regex) { SelectionList result; for (auto& sel : selections) { auto sel_end = utf8::next(buffer.iterator_at(sel.max())); RegexIterator re_it(buffer.iterator_at(sel.min()), sel_end, regex); RegexIterator re_end; for (; re_it != re_end; ++re_it) { auto& begin = (*re_it)[0].first; auto& end = (*re_it)[0].second; if (begin == sel_end) continue; CaptureList captures; for (auto& match : *re_it) captures.emplace_back(match.first, match.second); result.emplace_back(begin.coord(), (begin == end ? end : utf8::previous(end)).coord(), std::move(captures)); } } if (result.empty()) throw runtime_error("nothing selected"); result.set_main_index(result.size() - 1); selections = std::move(result); } void split_selections(const Buffer& buffer, SelectionList& selections, const Regex& regex) { SelectionList result; for (auto& sel : selections) { auto begin = buffer.iterator_at(sel.min()); auto sel_end = utf8::next(buffer.iterator_at(sel.max())); RegexIterator re_it(begin, sel_end, regex, boost::regex_constants::match_nosubs); RegexIterator re_end; for (; re_it != re_end; ++re_it) { BufferIterator end = (*re_it)[0].first; result.emplace_back(begin.coord(), (begin == end) ? end.coord() : utf8::previous(end).coord()); begin = (*re_it)[0].second; } result.emplace_back(begin.coord(), sel.max()); } result.set_main_index(result.size() - 1); selections = std::move(result); } } <commit_msg>fix select_to_eol behaviour when on empty line<commit_after>#include "selectors.hh" #include "string.hh" #include <algorithm> #include <boost/optional.hpp> namespace Kakoune { Selection select_line(const Buffer& buffer, const Selection& selection) { Utf8Iterator first = buffer.iterator_at(selection.last()); if (*first == '\n' and first + 1 != buffer.end()) ++first; while (first != buffer.begin() and *(first - 1) != '\n') --first; Utf8Iterator last = first; while (last + 1 != buffer.end() and *last != '\n') ++last; return utf8_range(first, last); } Selection select_matching(const Buffer& buffer, const Selection& selection) { std::vector<Codepoint> matching_pairs = { '(', ')', '{', '}', '[', ']', '<', '>' }; Utf8Iterator it = buffer.iterator_at(selection.last()); std::vector<Codepoint>::iterator match = matching_pairs.end(); while (not is_eol(*it)) { match = std::find(matching_pairs.begin(), matching_pairs.end(), *it); if (match != matching_pairs.end()) break; ++it; } if (match == matching_pairs.end()) return selection; Utf8Iterator begin = it; if (((match - matching_pairs.begin()) % 2) == 0) { int level = 0; const Codepoint opening = *match; const Codepoint closing = *(match+1); while (it != buffer.end()) { if (*it == opening) ++level; else if (*it == closing and --level == 0) return utf8_range(begin, it); ++it; } } else { int level = 0; const Codepoint opening = *(match-1); const Codepoint closing = *match; while (true) { if (*it == closing) ++level; else if (*it == opening and --level == 0) return utf8_range(begin, it); if (it == buffer.begin()) break; --it; } } return selection; } // c++14 will add std::optional, so we use boost::optional until then using boost::optional; static optional<Range> find_surrounding(const Buffer& buffer, BufferCoord coord, CodepointPair matching, ObjectFlags flags, int init_level) { const bool to_begin = flags & ObjectFlags::ToBegin; const bool to_end = flags & ObjectFlags::ToEnd; const bool nestable = matching.first != matching.second; auto pos = buffer.iterator_at(coord); Utf8Iterator first = pos; if (to_begin) { int level = nestable ? init_level : 0; while (first != buffer.begin()) { if (nestable and first != pos and *first == matching.second) ++level; else if (*first == matching.first) { if (level == 0) break; else --level; } --first; } if (level != 0 or *first != matching.first) return optional<Range>{}; } Utf8Iterator last = pos; if (to_end) { int level = nestable ? init_level : 0; while (last != buffer.end()) { if (nestable and last != pos and *last == matching.first) ++level; else if (*last == matching.second) { if (level == 0) break; else --level; } ++last; } if (level != 0 or last == buffer.end()) return optional<Range>{}; } if (flags & ObjectFlags::Inner) { if (to_begin and first != last) ++first; if (to_end and first != last) --last; } return to_end ? utf8_range(first, last) : utf8_range(last, first); } Selection select_surrounding(const Buffer& buffer, const Selection& selection, CodepointPair matching, int level, ObjectFlags flags) { const bool nestable = matching.first != matching.second; auto pos = selection.last(); if (not nestable or flags & ObjectFlags::Inner) { if (auto res = find_surrounding(buffer, pos, matching, flags, level)) return *res; return selection; } auto c = buffer.byte_at(pos); if ((flags == ObjectFlags::ToBegin and c == matching.first) or (flags == ObjectFlags::ToEnd and c == matching.second)) ++level; auto res = find_surrounding(buffer, pos, matching, flags, level); if (not res) return selection; if (flags == (ObjectFlags::ToBegin | ObjectFlags::ToEnd) and res->min() == selection.min() and res->max() == selection.max()) { if (auto res_parent = find_surrounding(buffer, pos, matching, flags, level+1)) return Selection{*res_parent}; } return *res; } Selection select_to(const Buffer& buffer, const Selection& selection, Codepoint c, int count, bool inclusive) { Utf8Iterator begin = buffer.iterator_at(selection.last()); Utf8Iterator end = begin; do { ++end; skip_while(end, buffer.end(), [c](Codepoint cur) { return cur != c; }); if (end == buffer.end()) return selection; } while (--count > 0); return utf8_range(begin, inclusive ? end : end-1); } Selection select_to_reverse(const Buffer& buffer, const Selection& selection, Codepoint c, int count, bool inclusive) { Utf8Iterator begin = buffer.iterator_at(selection.last()); Utf8Iterator end = begin; do { --end; skip_while_reverse(end, buffer.begin(), [c](Codepoint cur) { return cur != c; }); if (end == buffer.begin()) return selection; } while (--count > 0); return utf8_range(begin, inclusive ? end : end+1); } Selection select_to_eol(const Buffer& buffer, const Selection& selection) { Utf8Iterator begin = buffer.iterator_at(selection.last()); Utf8Iterator end = begin; skip_while(end, buffer.end(), [](Codepoint cur) { return not is_eol(cur); }); return utf8_range(begin, end != begin ? end-1 : end); } Selection select_to_eol_reverse(const Buffer& buffer, const Selection& selection) { Utf8Iterator begin = buffer.iterator_at(selection.last()); Utf8Iterator end = begin - 1; skip_while_reverse(end, buffer.begin(), [](Codepoint cur) { return not is_eol(cur); }); return utf8_range(begin, end == buffer.begin() ? end : end+1); } Selection select_whole_sentence(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { BufferIterator first = buffer.iterator_at(selection.last()); BufferIterator last = first; if (flags & ObjectFlags::ToBegin) { bool saw_non_blank = false; while (first != buffer.begin()) { char cur = *first; char prev = *(first-1); if (not is_blank(cur)) saw_non_blank = true; if (is_eol(prev) and is_eol(cur)) { ++first; break; } else if (prev == '.' or prev == ';' or prev == '!' or prev == '?') { if (saw_non_blank) break; else if (flags & ObjectFlags::ToEnd) last = first-1; } --first; } skip_while(first, buffer.end(), is_blank); } if (flags & ObjectFlags::ToEnd) { while (last != buffer.end()) { char cur = *last; if (cur == '.' or cur == ';' or cur == '!' or cur == '?' or (is_eol(cur) and (last+1 == buffer.end() or is_eol(*(last+1))))) break; ++last; } if (not (flags & ObjectFlags::Inner) and last != buffer.end()) { ++last; skip_while(last, buffer.end(), is_blank); --last; } } return (flags & ObjectFlags::ToEnd) ? Selection{first.coord(), last.coord()} : Selection{last.coord(), first.coord()}; } Selection select_whole_paragraph(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { BufferIterator first = buffer.iterator_at(selection.last()); BufferIterator last = first; if (flags & ObjectFlags::ToBegin and first != buffer.begin()) { skip_while_reverse(first, buffer.begin(), is_eol); if (flags & ObjectFlags::ToEnd) last = first; while (first != buffer.begin()) { char cur = *first; char prev = *(first-1); if (is_eol(prev) and is_eol(cur)) { ++first; break; } --first; } } if (flags & ObjectFlags::ToEnd) { while (last != buffer.end()) { char cur = *last; char prev = *(last-1); if (is_eol(cur) and is_eol(prev)) { if (not (flags & ObjectFlags::Inner)) skip_while(last, buffer.end(), is_eol); break; } ++last; } --last; } return (flags & ObjectFlags::ToEnd) ? Selection{first.coord(), last.coord()} : Selection{last.coord(), first.coord()}; } static CharCount get_indent(const String& str, int tabstop) { CharCount indent = 0; for (auto& c : str) { if (c == ' ') ++indent; else if (c =='\t') indent = (indent / tabstop + 1) * tabstop; else break; } return indent; } Selection select_whole_indent(const Buffer& buffer, const Selection& selection, ObjectFlags flags) { int tabstop = buffer.options()["tabstop"].get<int>(); LineCount line = selection.last().line; auto indent = get_indent(buffer[line], tabstop); LineCount begin_line = line - 1; if (flags & ObjectFlags::ToBegin) { while (begin_line >= 0 and (buffer[begin_line] == "\n" or get_indent(buffer[begin_line], tabstop) >= indent)) --begin_line; } ++begin_line; LineCount end_line = line + 1; if (flags & ObjectFlags::ToEnd) { LineCount end = buffer.line_count(); while (end_line < end and (buffer[end_line] == "\n" or get_indent(buffer[end_line], tabstop) >= indent)) ++end_line; } --end_line; BufferCoord first = begin_line; // keep the first line indent in inner mode if (flags & ObjectFlags::Inner) { CharCount i = 0; for (; i < indent; ++first.column) { auto c = buffer.byte_at(first); if (c == ' ') ++i; if (c == '\t') i = (i / tabstop + 1) * tabstop; } } return Selection{first, {end_line, buffer[end_line].length() - 1}}; } Selection select_whole_lines(const Buffer& buffer, const Selection& selection) { // no need to be utf8 aware for is_eol as we only use \n as line seperator BufferIterator first = buffer.iterator_at(selection.first()); BufferIterator last = buffer.iterator_at(selection.last()); BufferIterator& to_line_start = first <= last ? first : last; BufferIterator& to_line_end = first <= last ? last : first; --to_line_start; skip_while_reverse(to_line_start, buffer.begin(), [](char cur) { return not is_eol(cur); }); if (is_eol(*to_line_start)) ++to_line_start; skip_while(to_line_end, buffer.end(), [](char cur) { return not is_eol(cur); }); if (to_line_end == buffer.end()) --to_line_end; return Selection(first.coord(), last.coord()); } Selection trim_partial_lines(const Buffer& buffer, const Selection& selection) { // same as select_whole_lines BufferIterator first = buffer.iterator_at(selection.first()); BufferIterator last = buffer.iterator_at(selection.last()); BufferIterator& to_line_start = first <= last ? first : last; BufferIterator& to_line_end = first <= last ? last : first; while (to_line_start != buffer.begin() and *(to_line_start-1) != '\n') ++to_line_start; while (*(to_line_end+1) != '\n' and to_line_end != to_line_start) --to_line_end; return Selection(first.coord(), last.coord()); } void select_whole_buffer(const Buffer& buffer, SelectionList& selections) { selections = SelectionList{ Selection({0,0}, buffer.back_coord()) }; } void select_all_matches(const Buffer& buffer, SelectionList& selections, const Regex& regex) { SelectionList result; for (auto& sel : selections) { auto sel_end = utf8::next(buffer.iterator_at(sel.max())); RegexIterator re_it(buffer.iterator_at(sel.min()), sel_end, regex); RegexIterator re_end; for (; re_it != re_end; ++re_it) { auto& begin = (*re_it)[0].first; auto& end = (*re_it)[0].second; if (begin == sel_end) continue; CaptureList captures; for (auto& match : *re_it) captures.emplace_back(match.first, match.second); result.emplace_back(begin.coord(), (begin == end ? end : utf8::previous(end)).coord(), std::move(captures)); } } if (result.empty()) throw runtime_error("nothing selected"); result.set_main_index(result.size() - 1); selections = std::move(result); } void split_selections(const Buffer& buffer, SelectionList& selections, const Regex& regex) { SelectionList result; for (auto& sel : selections) { auto begin = buffer.iterator_at(sel.min()); auto sel_end = utf8::next(buffer.iterator_at(sel.max())); RegexIterator re_it(begin, sel_end, regex, boost::regex_constants::match_nosubs); RegexIterator re_end; for (; re_it != re_end; ++re_it) { BufferIterator end = (*re_it)[0].first; result.emplace_back(begin.coord(), (begin == end) ? end.coord() : utf8::previous(end).coord()); begin = (*re_it)[0].second; } result.emplace_back(begin.coord(), sel.max()); } result.set_main_index(result.size() - 1); selections = std::move(result); } } <|endoftext|>
<commit_before>/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <android/log.h> #include "AudioEngine.h" #include <thread> #include <mutex> aaudio_data_callback_result_t dataCallback( AAudioStream *stream, void *userData, void *audioData, int32_t numFrames) { ((Oscillator *) (userData))->render(static_cast<float *>(audioData), numFrames); return AAUDIO_CALLBACK_RESULT_CONTINUE; } void errorCallback(AAudioStream *stream, void *userData, aaudio_result_t error){ if (error == AAUDIO_ERROR_DISCONNECTED){ std::function<void(void)> restartFunction = std::bind(&AudioEngine::restart, static_cast<AudioEngine *>(userData)); new std::thread(restartFunction); } } bool AudioEngine::start() { AAudioStreamBuilder *streamBuilder; AAudio_createStreamBuilder(&streamBuilder); AAudioStreamBuilder_setFormat(streamBuilder, AAUDIO_FORMAT_PCM_FLOAT); AAudioStreamBuilder_setChannelCount(streamBuilder, 1); AAudioStreamBuilder_setPerformanceMode(streamBuilder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); AAudioStreamBuilder_setDataCallback(streamBuilder, ::dataCallback, &oscillator_); AAudioStreamBuilder_setErrorCallback(streamBuilder, ::errorCallback, this); // Opens the stream. aaudio_result_t result = AAudioStreamBuilder_openStream(streamBuilder, &stream_); if (result != AAUDIO_OK) { __android_log_print(ANDROID_LOG_ERROR, "AudioEngine", "Error opening stream %s", AAudio_convertResultToText(result)); return false; } // Retrieves the sample rate of the stream for our oscillator. int32_t sampleRate = AAudioStream_getSampleRate(stream_); oscillator_.setSampleRate(sampleRate); // Starts the stream. result = AAudioStream_requestStart(stream_); if (result != AAUDIO_OK) { __android_log_print(ANDROID_LOG_ERROR, "AudioEngine", "Error starting stream %s", AAudio_convertResultToText(result)); return false; } AAudioStreamBuilder_delete(streamBuilder); return true; } void AudioEngine::stop() { if (stream_ != nullptr) { AAudioStream_requestStop(stream_); AAudioStream_close(stream_); } } void AudioEngine::restart(){ static std::mutex restartingLock; if (restartingLock.try_lock()){ stop(); start(); restartingLock.unlock(); } } void AudioEngine::setToneOn(bool isToneOn) { oscillator_.setWaveOn(isToneOn); } <commit_msg>Specify buffer size of 2 bursts<commit_after>/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <android/log.h> #include "AudioEngine.h" #include <thread> #include <mutex> constexpr int32_t kBufferSizeInBursts = 2; aaudio_data_callback_result_t dataCallback( AAudioStream *stream, void *userData, void *audioData, int32_t numFrames) { ((Oscillator *) (userData))->render(static_cast<float *>(audioData), numFrames); return AAUDIO_CALLBACK_RESULT_CONTINUE; } void errorCallback(AAudioStream *stream, void *userData, aaudio_result_t error){ if (error == AAUDIO_ERROR_DISCONNECTED){ std::function<void(void)> restartFunction = std::bind(&AudioEngine::restart, static_cast<AudioEngine *>(userData)); new std::thread(restartFunction); } } bool AudioEngine::start() { AAudioStreamBuilder *streamBuilder; AAudio_createStreamBuilder(&streamBuilder); AAudioStreamBuilder_setFormat(streamBuilder, AAUDIO_FORMAT_PCM_FLOAT); AAudioStreamBuilder_setChannelCount(streamBuilder, 1); AAudioStreamBuilder_setPerformanceMode(streamBuilder, AAUDIO_PERFORMANCE_MODE_LOW_LATENCY); AAudioStreamBuilder_setDataCallback(streamBuilder, ::dataCallback, &oscillator_); AAudioStreamBuilder_setErrorCallback(streamBuilder, ::errorCallback, this); // Opens the stream. aaudio_result_t result = AAudioStreamBuilder_openStream(streamBuilder, &stream_); if (result != AAUDIO_OK) { __android_log_print(ANDROID_LOG_ERROR, "AudioEngine", "Error opening stream %s", AAudio_convertResultToText(result)); return false; } // Retrieves the sample rate of the stream for our oscillator. int32_t sampleRate = AAudioStream_getSampleRate(stream_); oscillator_.setSampleRate(sampleRate); // Sets the buffer size. AAudioStream_setBufferSizeInFrames( stream_, AAudioStream_getFramesPerBurst(stream_) * kBufferSizeInBursts); // Starts the stream. result = AAudioStream_requestStart(stream_); if (result != AAUDIO_OK) { __android_log_print(ANDROID_LOG_ERROR, "AudioEngine", "Error starting stream %s", AAudio_convertResultToText(result)); return false; } AAudioStreamBuilder_delete(streamBuilder); return true; } void AudioEngine::stop() { if (stream_ != nullptr) { AAudioStream_requestStop(stream_); AAudioStream_close(stream_); } } void AudioEngine::restart(){ static std::mutex restartingLock; if (restartingLock.try_lock()){ stop(); start(); restartingLock.unlock(); } } void AudioEngine::setToneOn(bool isToneOn) { oscillator_.setWaveOn(isToneOn); } <|endoftext|>
<commit_before>/* * This file is part of WinSparkle (http://winsparkle.org) * * Copyright (C) 2009-2010 Vaclav Slavik * * 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 "settings.h" #include "error.h" #include "utils.h" namespace winsparkle { std::string Settings::ms_appcastURL; /*--------------------------------------------------------------------------* resources access *--------------------------------------------------------------------------*/ namespace { struct TranslationInfo { WORD wLanguage; WORD wCodePage; }; // return language code for the resource to query std::wstring GetVerInfoLang(void *fi) { struct TranslationInfo { WORD language; WORD codepage; } *translations; unsigned translationsCnt; if ( !VerQueryValue(fi, TEXT("\\VarFileInfo\\Translation"), (LPVOID*)&translations, &translationsCnt) ) throw Win32Exception("Executable doesn't have required VERSIONINFO\\VarFileInfo resource"); translationsCnt /= sizeof(struct TranslationInfo); if ( translationsCnt == 0 ) throw std::runtime_error("No translations in VarFileInfo resource?"); // TODO: be smarter about which language to use: // 1. use app main thread's locale // 2. failing that, try language-neutral or English // 3. use the first one as fallback const size_t idx = 0; wchar_t lang[9]; HRESULT hr = _snwprintf_s(lang, 9, 8, L"%04x%04x", translations[idx].language, translations[idx].codepage); if ( FAILED(hr) ) throw Win32Exception(); return lang; } } // anonymous namespace std::wstring Settings::DoGetVerInfoField(const wchar_t *field, bool fatal) { TCHAR exeFilename[MAX_PATH + 1]; if ( !GetModuleFileName(NULL, exeFilename, MAX_PATH) ) throw Win32Exception(); DWORD unusedHandle; DWORD fiSize = GetFileVersionInfoSize(exeFilename, &unusedHandle); if ( fiSize == 0 ) throw Win32Exception("Executable doesn't have the required VERSIONINFO resource"); DataBuffer fi(fiSize); if ( !GetFileVersionInfo(exeFilename, unusedHandle, fiSize, fi.data) ) throw Win32Exception(); const std::wstring key = TEXT("\\StringFileInfo\\") + GetVerInfoLang(fi.data) + TEXT("\\") + field; TCHAR *value; UINT len; if ( !VerQueryValue(fi.data, key.c_str(), (LPVOID*)&value, &len) ) { if ( fatal ) throw Win32Exception("Executable doesn't have required key in StringFileInfo"); else return std::wstring(); } return value; } /*--------------------------------------------------------------------------* runtime config access *--------------------------------------------------------------------------*/ namespace { std::string MakeSubKey(const char *name) { std::string s("Software\\"); std::wstring vendor = Settings::GetCompanyName(); if ( !vendor.empty() ) s += WideToAnsi(vendor) + "\\"; s += WideToAnsi(Settings::GetAppName()); s += "\\WinSparkle"; return s; } void RegistryWrite(const char *name, const char *value) { const std::string subkey = MakeSubKey(name); HKEY key; LONG result = RegCreateKeyExA ( HKEY_CURRENT_USER, subkey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &key, NULL ); if ( result != ERROR_SUCCESS ) throw Win32Exception("Cannot write settings to registry"); result = RegSetValueExA ( key, name, 0, REG_SZ, (const BYTE*)value, strlen(value) + 1 ); if ( result != ERROR_SUCCESS ) throw Win32Exception("Cannot write settings to registry"); RegCloseKey(key); } int RegistryRead(const char *name, char *buf, size_t len) { const std::string subkey = MakeSubKey(name); HKEY key; LONG result = RegOpenKeyExA ( HKEY_CURRENT_USER, subkey.c_str(), 0, KEY_QUERY_VALUE, &key ); if ( result != ERROR_SUCCESS ) { if ( result == ERROR_FILE_NOT_FOUND ) return 0; throw Win32Exception("Cannot write settings to registry"); } DWORD buflen = len; DWORD type; result = RegQueryValueExA ( key, name, 0, &type, (BYTE*)buf, &buflen ); RegCloseKey(key); if ( result != ERROR_SUCCESS ) { if ( result == ERROR_FILE_NOT_FOUND ) return 0; throw Win32Exception("Cannot write settings to registry"); } if ( type != REG_SZ ) { // incorrect type -- pretend that the setting doesn't exist, it will // be newly written by WinSparkle anyway return 0; } return 1; } } // anonymous namespace void Settings::DoWriteConfigValue(const char *name, const char *value) { RegistryWrite(name, value); } std::string Settings::DoReadConfigValue(const char *name) { char buf[512]; if ( RegistryRead(name, buf, sizeof(buf)) ) return buf; else return std::string(); } } // namespace winsparkle <commit_msg>Serialize access to registry-stored config values.<commit_after>/* * This file is part of WinSparkle (http://winsparkle.org) * * Copyright (C) 2009-2010 Vaclav Slavik * * 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 "settings.h" #include "error.h" #include "utils.h" #include "threads.h" namespace winsparkle { std::string Settings::ms_appcastURL; /*--------------------------------------------------------------------------* resources access *--------------------------------------------------------------------------*/ namespace { struct TranslationInfo { WORD wLanguage; WORD wCodePage; }; // return language code for the resource to query std::wstring GetVerInfoLang(void *fi) { struct TranslationInfo { WORD language; WORD codepage; } *translations; unsigned translationsCnt; if ( !VerQueryValue(fi, TEXT("\\VarFileInfo\\Translation"), (LPVOID*)&translations, &translationsCnt) ) throw Win32Exception("Executable doesn't have required VERSIONINFO\\VarFileInfo resource"); translationsCnt /= sizeof(struct TranslationInfo); if ( translationsCnt == 0 ) throw std::runtime_error("No translations in VarFileInfo resource?"); // TODO: be smarter about which language to use: // 1. use app main thread's locale // 2. failing that, try language-neutral or English // 3. use the first one as fallback const size_t idx = 0; wchar_t lang[9]; HRESULT hr = _snwprintf_s(lang, 9, 8, L"%04x%04x", translations[idx].language, translations[idx].codepage); if ( FAILED(hr) ) throw Win32Exception(); return lang; } } // anonymous namespace std::wstring Settings::DoGetVerInfoField(const wchar_t *field, bool fatal) { TCHAR exeFilename[MAX_PATH + 1]; if ( !GetModuleFileName(NULL, exeFilename, MAX_PATH) ) throw Win32Exception(); DWORD unusedHandle; DWORD fiSize = GetFileVersionInfoSize(exeFilename, &unusedHandle); if ( fiSize == 0 ) throw Win32Exception("Executable doesn't have the required VERSIONINFO resource"); DataBuffer fi(fiSize); if ( !GetFileVersionInfo(exeFilename, unusedHandle, fiSize, fi.data) ) throw Win32Exception(); const std::wstring key = TEXT("\\StringFileInfo\\") + GetVerInfoLang(fi.data) + TEXT("\\") + field; TCHAR *value; UINT len; if ( !VerQueryValue(fi.data, key.c_str(), (LPVOID*)&value, &len) ) { if ( fatal ) throw Win32Exception("Executable doesn't have required key in StringFileInfo"); else return std::wstring(); } return value; } /*--------------------------------------------------------------------------* runtime config access *--------------------------------------------------------------------------*/ namespace { std::string MakeSubKey(const char *name) { std::string s("Software\\"); std::wstring vendor = Settings::GetCompanyName(); if ( !vendor.empty() ) s += WideToAnsi(vendor) + "\\"; s += WideToAnsi(Settings::GetAppName()); s += "\\WinSparkle"; return s; } void RegistryWrite(const char *name, const char *value) { const std::string subkey = MakeSubKey(name); HKEY key; LONG result = RegCreateKeyExA ( HKEY_CURRENT_USER, subkey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &key, NULL ); if ( result != ERROR_SUCCESS ) throw Win32Exception("Cannot write settings to registry"); result = RegSetValueExA ( key, name, 0, REG_SZ, (const BYTE*)value, strlen(value) + 1 ); if ( result != ERROR_SUCCESS ) throw Win32Exception("Cannot write settings to registry"); RegCloseKey(key); } int RegistryRead(const char *name, char *buf, size_t len) { const std::string subkey = MakeSubKey(name); HKEY key; LONG result = RegOpenKeyExA ( HKEY_CURRENT_USER, subkey.c_str(), 0, KEY_QUERY_VALUE, &key ); if ( result != ERROR_SUCCESS ) { if ( result == ERROR_FILE_NOT_FOUND ) return 0; throw Win32Exception("Cannot write settings to registry"); } DWORD buflen = len; DWORD type; result = RegQueryValueExA ( key, name, 0, &type, (BYTE*)buf, &buflen ); RegCloseKey(key); if ( result != ERROR_SUCCESS ) { if ( result == ERROR_FILE_NOT_FOUND ) return 0; throw Win32Exception("Cannot write settings to registry"); } if ( type != REG_SZ ) { // incorrect type -- pretend that the setting doesn't exist, it will // be newly written by WinSparkle anyway return 0; } return 1; } // Critical section to guard DoWriteConfigValue/DoReadConfigValue. CriticalSection g_csConfigValues; } // anonymous namespace void Settings::DoWriteConfigValue(const char *name, const char *value) { CriticalSectionLocker lock(g_csConfigValues); RegistryWrite(name, value); } std::string Settings::DoReadConfigValue(const char *name) { CriticalSectionLocker lock(g_csConfigValues); char buf[512]; if ( RegistryRead(name, buf, sizeof(buf)) ) return buf; else return std::string(); } } // namespace winsparkle <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iree/compiler/Dialect/HAL/Target/LLVM/AOT/LinkerTool.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/FormatVariadic.h" #define DEBUG_TYPE "llvmaot-linker" namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { // Unix linker (ld-like); for ELF files. class UnixLinkerTool : public LinkerTool { public: using LinkerTool::LinkerTool; std::string getToolPath() const override { auto toolPath = LinkerTool::getToolPath(); return toolPath.empty() ? "ld.lld" : toolPath; } LogicalResult configureModule(llvm::Module *llvmModule, ArrayRef<StringRef> entryPointNames) override { // Possibly a no-op in ELF files; needs to be verified. return success(); } Optional<Artifacts> linkDynamicLibrary( StringRef libraryName, ArrayRef<Artifact> objectFiles) override { Artifacts artifacts; // Create the shared object name; if we only have a single input object we // can just reuse that. if (objectFiles.size() == 1) { artifacts.libraryFile = Artifact::createVariant(objectFiles.front().path, "so"); } else { artifacts.libraryFile = Artifact::createTemporary(libraryName, "so"); } artifacts.libraryFile.close(); SmallVector<std::string, 8> flags = { getToolPath(), "-shared", "-o " + artifacts.libraryFile.path, }; // TODO(ataei): add flags based on targetTriple.isAndroid(), like // -static-libstdc++ (if this is needed, which it shouldn't be). // Link all input objects. Note that we are not linking whole-archive as we // want to allow dropping of unused codegen outputs. for (auto &objectFile : objectFiles) { flags.push_back(objectFile.path); } auto commandLine = llvm::join(flags, " "); if (failed(runLinkCommand(commandLine))) return llvm::None; return artifacts; } }; std::unique_ptr<LinkerTool> createUnixLinkerTool( llvm::Triple &targetTriple, LLVMTargetOptions &targetOptions) { return std::make_unique<UnixLinkerTool>(targetTriple, targetOptions); } } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir <commit_msg>Always emitting framepointers in generated ELFs (#3987)<commit_after>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iree/compiler/Dialect/HAL/Target/LLVM/AOT/LinkerTool.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/FormatVariadic.h" #define DEBUG_TYPE "llvmaot-linker" namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { // Unix linker (ld-like); for ELF files. class UnixLinkerTool : public LinkerTool { public: using LinkerTool::LinkerTool; std::string getToolPath() const override { auto toolPath = LinkerTool::getToolPath(); return toolPath.empty() ? "ld.lld" : toolPath; } LogicalResult configureModule(llvm::Module *llvmModule, ArrayRef<StringRef> entryPointNames) override { // Enable frame pointers to ensure that stack unwinding works, e.g. in // Tracy. In principle this could also be achieved by enabling unwind // tables, but we tried that and that didn't work in Tracy (which uses // libbacktrace), while enabling frame pointers worked. // https://github.com/google/iree/issues/3957 for (auto &func : *llvmModule) { auto attrs = func.getAttributes(); attrs = attrs.addAttribute(llvmModule->getContext(), llvm::AttributeList::FunctionIndex, "frame-pointer", "all"); func.setAttributes(attrs); } return success(); } Optional<Artifacts> linkDynamicLibrary( StringRef libraryName, ArrayRef<Artifact> objectFiles) override { Artifacts artifacts; // Create the shared object name; if we only have a single input object we // can just reuse that. if (objectFiles.size() == 1) { artifacts.libraryFile = Artifact::createVariant(objectFiles.front().path, "so"); } else { artifacts.libraryFile = Artifact::createTemporary(libraryName, "so"); } artifacts.libraryFile.close(); SmallVector<std::string, 8> flags = { getToolPath(), "-shared", "-o " + artifacts.libraryFile.path, }; // TODO(ataei): add flags based on targetTriple.isAndroid(), like // -static-libstdc++ (if this is needed, which it shouldn't be). // Link all input objects. Note that we are not linking whole-archive as we // want to allow dropping of unused codegen outputs. for (auto &objectFile : objectFiles) { flags.push_back(objectFile.path); } auto commandLine = llvm::join(flags, " "); if (failed(runLinkCommand(commandLine))) return llvm::None; return artifacts; } }; std::unique_ptr<LinkerTool> createUnixLinkerTool( llvm::Triple &targetTriple, LLVMTargetOptions &targetOptions) { return std::make_unique<UnixLinkerTool>(targetTriple, targetOptions); } } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>// Make sure ASan removes the runtime library from DYLD_INSERT_LIBRARIES before // executing other programs. // RUN: %clangxx_asan %s -o %t // RUN: %clangxx %p/../SharedLibs/darwin-dummy-shared-lib-so.cc \ // RUN: -dynamiclib -o darwin-dummy-shared-lib-so.dylib // Make sure DYLD_INSERT_LIBRARIES doesn't contain the runtime library before // execl(). // RUN: %t >/dev/null 2>&1 // RUN: DYLD_INSERT_LIBRARIES=darwin-dummy-shared-lib-so.dylib \ // RUN: %t 2>&1 | FileCheck %s || exit 1 #include <unistd.h> int main() { execl("/bin/bash", "/bin/bash", "-c", "echo DYLD_INSERT_LIBRARIES=$DYLD_INSERT_LIBRARIES", NULL); // CHECK: {{DYLD_INSERT_LIBRARIES=.*darwin-dummy-shared-lib-so.dylib.*}} return 0; } <commit_msg>[ASan] fix test case to use absolute paths<commit_after>// Make sure ASan removes the runtime library from DYLD_INSERT_LIBRARIES before // executing other programs. // RUN: %clangxx_asan %s -o %t // RUN: %clangxx %p/../SharedLibs/darwin-dummy-shared-lib-so.cc \ // RUN: -dynamiclib -o %t-darwin-dummy-shared-lib-so.dylib // Make sure DYLD_INSERT_LIBRARIES doesn't contain the runtime library before // execl(). // RUN: %t >/dev/null 2>&1 // RUN: DYLD_INSERT_LIBRARIES=%t-darwin-dummy-shared-lib-so.dylib \ // RUN: %t 2>&1 | FileCheck %s || exit 1 #include <unistd.h> int main() { execl("/bin/bash", "/bin/bash", "-c", "echo DYLD_INSERT_LIBRARIES=$DYLD_INSERT_LIBRARIES", NULL); // CHECK: {{DYLD_INSERT_LIBRARIES=.*darwin-dummy-shared-lib-so.dylib.*}} return 0; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved */ #ifndef _Stroika_Foundation_Traversal_Partition_inl_ #define _Stroika_Foundation_Traversal_Partition_inl_ #include "../Containers/SortedMapping.h" #include "../Debug/Assertions.h" #include "../Debug/Trace.h" namespace Stroika::Foundation::Traversal { namespace Private_ { template <typename RANGETYPE, typename RANGE_ELT_COMPARER> bool IsPartition_Helper_ (const Iterable<RANGETYPE>& iterable, RANGE_ELT_COMPARER comparer /*, enable_if_t <isomethingto check for operator <> usesInsertPair = 0*/) { using Common::KeyValuePair; using Containers::SortedMapping; using Debug::TraceContextBumper; TraceContextBumper ctx{"IsPartition_Helper_"}; using namespace Traversal; using value_type = typename RANGETYPE::value_type; SortedMapping<value_type, RANGETYPE> tmp; for (RANGETYPE r : iterable) { tmp.Add (r.GetLowerBound (), r); } optional<value_type> upperBoundSeenSoFar; Openness upperBoundSeenSoFarOpenness{}; for (KeyValuePair<value_type, RANGETYPE> i : tmp) { //DbgTrace ("i.fKey = %f, i.fValue = (%f,%f, ol=%d, or=%d)", i.fKey, i.fValue.GetLowerBound (), i.fValue.GetUpperBound (), i.fValue.GetLowerBoundOpenness (), i.fValue.GetUpperBoundOpenness ()); if (upperBoundSeenSoFar) { if (not comparer (*upperBoundSeenSoFar, i.fValue.GetLowerBound ())) { //DbgTrace ("i.fKey = %f, i.fValue = (%f,%f, ol=%d, or=%d)", i.fKey, i.fValue.GetLowerBound (), i.fValue.GetUpperBound (), i.fValue.GetLowerBoundOpenness (), i.fValue.GetUpperBoundOpenness ()); //DbgTrace ("return false cuz boudns no match"); return false; } if (upperBoundSeenSoFarOpenness == i.fValue.GetLowerBoundOpenness ()) { //DbgTrace ("i.fKey = %f, i.fValue = (%f,%f, ol=%d, or=%d)", i.fKey, i.fValue.GetLowerBound (), i.fValue.GetUpperBound (), i.fValue.GetLowerBoundOpenness (), i.fValue.GetUpperBoundOpenness ()); //DbgTrace ("return false cuz boudns openness no match: upperBoundSeenSoFarOpenness =%d, and i.fValue.GetLowerBoundOpenness ()=%d)", upperBoundSeenSoFarOpenness, i.fValue.GetLowerBoundOpenness ()); return false; } } upperBoundSeenSoFar = i.fValue.GetUpperBound (); upperBoundSeenSoFarOpenness = i.fValue.GetUpperBoundOpenness (); } return true; } } /** */ template <typename RANGETYPE> inline bool IsPartition (const Iterable<RANGETYPE>& iterable) { return Private_::IsPartition_Helper_<RANGETYPE> (iterable, [] (typename RANGETYPE::value_type lhs, typename RANGETYPE::value_type rhs) { return Math::NearlyEquals (lhs, rhs); }); } template <typename RANGETYPE, typename RANGE_ELT_COMPARER> inline bool IsPartition (const Iterable<RANGETYPE>& iterable, RANGE_ELT_COMPARER comparer) { return Private_::IsPartition_Helper_<RANGETYPE, RANGE_ELT_COMPARER> (iterable, comparer); } } #endif /* _Stroika_Foundation_Traversal_Partition_inl_ */ <commit_msg>use const& in one for loop<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved */ #ifndef _Stroika_Foundation_Traversal_Partition_inl_ #define _Stroika_Foundation_Traversal_Partition_inl_ #include "../Containers/SortedMapping.h" #include "../Debug/Assertions.h" #include "../Debug/Trace.h" namespace Stroika::Foundation::Traversal { namespace Private_ { template <typename RANGETYPE, typename RANGE_ELT_COMPARER> bool IsPartition_Helper_ (const Iterable<RANGETYPE>& iterable, RANGE_ELT_COMPARER comparer /*, enable_if_t <isomethingto check for operator <> usesInsertPair = 0*/) { using Common::KeyValuePair; using Containers::SortedMapping; using Debug::TraceContextBumper; TraceContextBumper ctx{"IsPartition_Helper_"}; using namespace Traversal; using value_type = typename RANGETYPE::value_type; SortedMapping<value_type, RANGETYPE> tmp; for (RANGETYPE r : iterable) { tmp.Add (r.GetLowerBound (), r); } optional<value_type> upperBoundSeenSoFar; Openness upperBoundSeenSoFarOpenness{}; for (const KeyValuePair<value_type, RANGETYPE>& i : tmp) { //DbgTrace ("i.fKey = %f, i.fValue = (%f,%f, ol=%d, or=%d)", i.fKey, i.fValue.GetLowerBound (), i.fValue.GetUpperBound (), i.fValue.GetLowerBoundOpenness (), i.fValue.GetUpperBoundOpenness ()); if (upperBoundSeenSoFar) { if (not comparer (*upperBoundSeenSoFar, i.fValue.GetLowerBound ())) { //DbgTrace ("i.fKey = %f, i.fValue = (%f,%f, ol=%d, or=%d)", i.fKey, i.fValue.GetLowerBound (), i.fValue.GetUpperBound (), i.fValue.GetLowerBoundOpenness (), i.fValue.GetUpperBoundOpenness ()); //DbgTrace ("return false cuz boudns no match"); return false; } if (upperBoundSeenSoFarOpenness == i.fValue.GetLowerBoundOpenness ()) { //DbgTrace ("i.fKey = %f, i.fValue = (%f,%f, ol=%d, or=%d)", i.fKey, i.fValue.GetLowerBound (), i.fValue.GetUpperBound (), i.fValue.GetLowerBoundOpenness (), i.fValue.GetUpperBoundOpenness ()); //DbgTrace ("return false cuz boudns openness no match: upperBoundSeenSoFarOpenness =%d, and i.fValue.GetLowerBoundOpenness ()=%d)", upperBoundSeenSoFarOpenness, i.fValue.GetLowerBoundOpenness ()); return false; } } upperBoundSeenSoFar = i.fValue.GetUpperBound (); upperBoundSeenSoFarOpenness = i.fValue.GetUpperBoundOpenness (); } return true; } } /** */ template <typename RANGETYPE> inline bool IsPartition (const Iterable<RANGETYPE>& iterable) { return Private_::IsPartition_Helper_<RANGETYPE> (iterable, [] (typename RANGETYPE::value_type lhs, typename RANGETYPE::value_type rhs) { return Math::NearlyEquals (lhs, rhs); }); } template <typename RANGETYPE, typename RANGE_ELT_COMPARER> inline bool IsPartition (const Iterable<RANGETYPE>& iterable, RANGE_ELT_COMPARER comparer) { return Private_::IsPartition_Helper_<RANGETYPE, RANGE_ELT_COMPARER> (iterable, comparer); } } #endif /* _Stroika_Foundation_Traversal_Partition_inl_ */ <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #include "../StroikaPreComp.h" #include <random> #include "../../Foundation/Characters/StringBuilder.h" #include "../../Foundation/Characters/ToString.h" #include "../../Foundation/Containers/Collection.h" #include "../../Foundation/Execution/Sleep.h" #include "../../Foundation/Execution/TimeOutException.h" #include "../../Foundation/IO/Network/InternetProtocol/ICMP.h" #include "../../Foundation/IO/Network/InternetProtocol/IP.h" #include "../../Foundation/IO/Network/Socket.h" #include "../../Foundation/IO/Network/SocketAddress.h" #include "../../Foundation/Traversal/DiscreteRange.h" #include "Ping.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Debug; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Foundation::IO::Network::InternetProtocol; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::NetworkMonitor; using namespace Stroika::Frameworks::NetworkMonitor::Ping; using Memory::Byte; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ********************** NetworkMonitor::Ping::Options *************************** ******************************************************************************** */ constexpr Traversal::Range<size_t> Ping::Options::kAllowedICMPPayloadSizeRange; const Duration Ping::Options::kDefaultTimeout{1.0}; String Ping::Options::ToString () const { StringBuilder sb; sb += L"{"; if (fMaxHops) { sb += L"Max-Hops: " + Characters::Format (L"%d", *fMaxHops) + L", "; } if (fTimeout) { sb += L"Timeout: " + Characters::ToString (*fTimeout) + L", "; } if (fPacketPayloadSize) { sb += L"Packet-Payload-Size: " + Characters::Format (L"%d", *fPacketPayloadSize) + L", "; } sb += L"}"; return sb.str (); } /* ******************************************************************************** ********************** NetworkMonitor::Ping::Pinger::ResultType **************** ******************************************************************************** */ String Pinger::ResultType::ToString () const { StringBuilder sb; sb += L"{"; sb += L"Ping-Time: " + Characters::ToString (fPingTime) + L", "; sb += L"Hop-Count: " + Characters::Format (L"%d", fHopCount) + L", "; sb += L"}"; return sb.str (); } /* ******************************************************************************** *************************** NetworkMonitor::Ping::Pinger *********************** ******************************************************************************** */ namespace { std::mt19937 sRng_{std::random_device () ()}; // not sure if this needs to be synchonized? std::uniform_int_distribution<std::mt19937::result_type> skAllUInt16Distribution_ (0, numeric_limits<uint16_t>::max ()); } Pinger::Pinger (const InternetAddress& addr, const Options& options) : fDestination_ (addr) , fOptions_ (options) , fICMPPacketSize_{Options::kAllowedICMPPayloadSizeRange.Pin (options.fPacketPayloadSize.Value (Options::kDefaultPayloadSize)) + sizeof (ICMP::V4::PacketHeader)} , fSendPacket_{fICMPPacketSize_} , fSocket_{Socket::ProtocolFamily::INET, Socket::SocketKind::RAW, IPPROTO_ICMP} , fNextSequenceNumber_{static_cast<uint16_t> (skAllUInt16Distribution_ (sRng_))} , fPingTimeout{options.fTimeout.Value (Options::kDefaultTimeout).As<Time::DurationSecondsType> ()} { DbgTrace (L"Frameworks::NetworkMonitor::Ping::Pinger::CTOR", L"addr=%s, options=%s", Characters::ToString (fDestination_).c_str (), Characters::ToString (fOptions_).c_str ()); // use random data as a payload for (Byte* p = (Byte*)fSendPacket_.begin () + sizeof (ICMP::V4::PacketHeader); p < fSendPacket_.end (); ++p) { static const std::uniform_int_distribution<std::mt19937::result_type> kAllByteDistribution_ (0, numeric_limits<Byte>::max ()); *p = kAllByteDistribution_ (sRng_); } } Pinger::ResultType Pinger::RunOnce (const Optional<unsigned int>& ttl) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Frameworks::NetworkMonitor::Ping::Pinger::RunOnce", L"ttl=%s", Characters::ToString (ttl).c_str ())}; return RunOnce_ICMP_ (ttl.Value (fOptions_.fMaxHops.Value (Options::kDefaultMaxHops))); } Pinger::ResultType Pinger::RunOnce_ICMP_ (unsigned int ttl) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Frameworks::NetworkMonitor::Ping::Pinger::RunOnce_ICMP_", L"ttl=%d", ttl)}; fSocket_.setsockopt (IPPROTO_IP, IP_TTL, ttl); // max # of hops ICMP::V4::PacketHeader pingRequest = [&]() { ICMP::V4::PacketHeader tmp{}; tmp.type = ICMP::V4::ICMP_ECHO_REQUEST; tmp.id = skAllUInt16Distribution_ (sRng_); tmp.seq = fNextSequenceNumber_++; tmp.timestamp = static_cast<uint32_t> (Time::GetTickCount () * 1000); return tmp; }(); (void)::memcpy (fSendPacket_.begin (), &pingRequest, sizeof (pingRequest)); reinterpret_cast<ICMP::V4::PacketHeader*> (fSendPacket_.begin ())->checksum = IP::ip_checksum (fSendPacket_.begin (), fSendPacket_.begin () + fICMPPacketSize_); fSocket_.SendTo (fSendPacket_.begin (), fSendPacket_.end (), SocketAddress{fDestination_, 0}); // Find first packet responding (some packets could be bogus/ignored) Time::DurationSecondsType pingTimeoutAfter = Time::GetTickCount () + fPingTimeout; while (true) { ThrowTimeoutExceptionAfter (pingTimeoutAfter); SocketAddress fromAddress; constexpr size_t kExtraSluff_{100}; // Leave a little extra room in case some packets return extra SmallStackBuffer<Byte> recv_buf (fICMPPacketSize_ + sizeof (ICMP::V4::PacketHeader) + 2 * sizeof (IP::V4::PacketHeader) + kExtraSluff_); // icmpPacketSize includes ONE ICMP header and payload, but we get 2 IP and 2 ICMP headers in TTL Exceeded response size_t n = fSocket_.ReceiveFrom (begin (recv_buf), end (recv_buf), 0, &fromAddress, fPingTimeout); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"got back packet from %s", Characters::ToString (fromAddress).c_str ()); #endif const IP::V4::PacketHeader* replyIPHeader = reinterpret_cast<const IP::V4::PacketHeader*> (recv_buf.begin ()); // Skip ahead to the ICMP header within the IP packet unsigned short header_len = replyIPHeader->ihl * 4; const ICMP::V4::PacketHeader* replyICMPHeader = (const ICMP::V4::PacketHeader*)((const Byte*)replyIPHeader + header_len); // Make sure the reply is sane if (n < header_len + ICMP::V4::ICMP_MIN) { Execution::Throw (Execution::StringException (L"too few bytes from " + Characters::ToString (fromAddress))); // draft @todo fix } /* * If we got a response id, compare it with the request we sent to make sure we're reading a resposne to the request we sent */ Optional<uint16_t> echoedID; switch (replyICMPHeader->type) { case ICMP::V4::ICMP_ECHO_REPLY: { echoedID = replyICMPHeader->id; } break; case ICMP::V4::ICMP_TTL_EXPIRE: { // According to https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Time_exceeded - we also can find the first 8 bytes of original datagram's data const ICMP::V4::PacketHeader* echoedICMPHeader = (const ICMP::V4::PacketHeader*)((const Byte*)replyICMPHeader + 8 + sizeof (IP::V4::PacketHeader)); echoedID = echoedICMPHeader->id; } break; case ICMP::V4::ICMP_DEST_UNREACH: { // According to https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Destination_unreachable - we also can find the first 8 bytes of original datagram's data const ICMP::V4::PacketHeader* echoedICMPHeader = (const ICMP::V4::PacketHeader*)((const Byte*)replyICMPHeader + 8 + sizeof (IP::V4::PacketHeader)); echoedID = echoedICMPHeader->id; } break; } if (echoedID and echoedID != pingRequest.id) { DbgTrace (L"echoedID (%s != pingRequest.id (%x) so ignoring this reply", Characters::ToString (echoedID).c_str (), pingRequest.id); // Must be a reply for another pinger running locally, so just // ignore it. continue; } /* * Handle differnt response messages differntly - but looking for ICMP_ECHO_REPLY, or ICMP_TTL_EXPIRE (for traceroute) */ switch (replyICMPHeader->type) { case ICMP::V4::ICMP_ECHO_REPLY: { // Different operating systems use different starting values for TTL. TTL here is the original number used, // less the number of hops. So we are left with making an educated guess. Need refrence and would be nice to find better // way, but this seems to work pretty often. unsigned int nHops{}; if (replyIPHeader->ttl > 128) { nHops = 257 - replyIPHeader->ttl; } else if (replyIPHeader->ttl > 64) { nHops = 129 - replyIPHeader->ttl; } else { nHops = 65 - replyIPHeader->ttl; } #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"reply->ttl = %d, nHops = %d", replyIPHeader->ttl, nHops); #endif return ResultType{Duration (Time::GetTickCount () - replyICMPHeader->timestamp / 1000.0), nHops}; } case ICMP::V4::ICMP_TTL_EXPIRE: { Execution::Throw (ICMP::V4::TTLExpiredException (InternetAddress{replyIPHeader->saddr})); } case ICMP::V4::ICMP_DEST_UNREACH: { Execution::Throw (ICMP::V4::DestinationUnreachableException (replyICMPHeader->code, InternetAddress{replyIPHeader->saddr})); }; default: { Execution::Throw (ICMP::V4::UnknownICMPPacket (replyICMPHeader->type)); } } } AssertNotReached (); return ResultType{}; } /* ******************************************************************************** ********************** NetworkMonitor::Ping::SampleOptions ********************* ******************************************************************************** */ Characters::String SampleOptions::ToString () const { StringBuilder sb; sb += L"{"; sb += L"Interval: " + Characters::ToString (fInterval) + L", "; sb += L"Count: " + Characters::Format (L"%d", fSampleCount) + L", "; sb += L"}"; return sb.str (); } /* ******************************************************************************** ******************* NetworkMonitor::Ping::SampleResults ************************ ******************************************************************************** */ String SampleResults::ToString () const { StringBuilder sb; sb += L"{"; if (fMedianPingTime) { sb += L"Median-Ping-Time: " + Characters::ToString (*fMedianPingTime) + L", "; } if (fMedianHopCount) { sb += L"Median-Hop-Count: " + Characters::Format (L"%d", *fMedianHopCount) + L", "; } if (fExceptionCount != 0) { sb += L"Exception-Count: " + Characters::Format (L"%d", fExceptionCount) + L", "; // to see exceptions - run with sample-count = 1 } sb += L"}"; return sb.str (); } /* ******************************************************************************** ************************* NetworkMonitor::Ping::Sample ************************* ******************************************************************************** */ SampleResults NetworkMonitor::Ping::Sample (const InternetAddress& addr, const SampleOptions& sampleOptions, const Options& options) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Frameworks::NetworkMonitor::Ping::Sample", L"addr=%s, sampleOptions=%s, options=%s", Characters::ToString (addr).c_str (), Characters::ToString (sampleOptions).c_str (), Characters::ToString (options).c_str ())}; Pinger pinger{addr, options}; Collection<DurationSecondsType> sampleTimes; Collection<unsigned int> sampleHopCounts; unsigned int samplesTaken{}; while (samplesTaken < sampleOptions.fSampleCount) { if (samplesTaken != 0) { Execution::Sleep (sampleOptions.fInterval); } try { Pinger::ResultType tmp = pinger.RunOnce (); sampleTimes += tmp.fPingTime.As<DurationSecondsType> (); sampleHopCounts += tmp.fHopCount; samplesTaken++; } catch (...) { samplesTaken++; } } return sampleTimes.empty () ? SampleResults{{}, {}, samplesTaken} : SampleResults{Duration (*sampleTimes.Median ()), *sampleHopCounts.Median (), static_cast<unsigned int> (samplesTaken - sampleTimes.size ())}; } <commit_msg>uniform_int_distribution<> must be non-const<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #include "../StroikaPreComp.h" #include <random> #include "../../Foundation/Characters/StringBuilder.h" #include "../../Foundation/Characters/ToString.h" #include "../../Foundation/Containers/Collection.h" #include "../../Foundation/Execution/Sleep.h" #include "../../Foundation/Execution/TimeOutException.h" #include "../../Foundation/IO/Network/InternetProtocol/ICMP.h" #include "../../Foundation/IO/Network/InternetProtocol/IP.h" #include "../../Foundation/IO/Network/Socket.h" #include "../../Foundation/IO/Network/SocketAddress.h" #include "../../Foundation/Traversal/DiscreteRange.h" #include "Ping.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Debug; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Foundation::IO::Network::InternetProtocol; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::NetworkMonitor; using namespace Stroika::Frameworks::NetworkMonitor::Ping; using Memory::Byte; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ********************** NetworkMonitor::Ping::Options *************************** ******************************************************************************** */ constexpr Traversal::Range<size_t> Ping::Options::kAllowedICMPPayloadSizeRange; const Duration Ping::Options::kDefaultTimeout{1.0}; String Ping::Options::ToString () const { StringBuilder sb; sb += L"{"; if (fMaxHops) { sb += L"Max-Hops: " + Characters::Format (L"%d", *fMaxHops) + L", "; } if (fTimeout) { sb += L"Timeout: " + Characters::ToString (*fTimeout) + L", "; } if (fPacketPayloadSize) { sb += L"Packet-Payload-Size: " + Characters::Format (L"%d", *fPacketPayloadSize) + L", "; } sb += L"}"; return sb.str (); } /* ******************************************************************************** ********************** NetworkMonitor::Ping::Pinger::ResultType **************** ******************************************************************************** */ String Pinger::ResultType::ToString () const { StringBuilder sb; sb += L"{"; sb += L"Ping-Time: " + Characters::ToString (fPingTime) + L", "; sb += L"Hop-Count: " + Characters::Format (L"%d", fHopCount) + L", "; sb += L"}"; return sb.str (); } /* ******************************************************************************** *************************** NetworkMonitor::Ping::Pinger *********************** ******************************************************************************** */ namespace { std::mt19937 sRng_{std::random_device () ()}; // not sure if this needs to be synchonized? std::uniform_int_distribution<std::mt19937::result_type> skAllUInt16Distribution_ (0, numeric_limits<uint16_t>::max ()); } Pinger::Pinger (const InternetAddress& addr, const Options& options) : fDestination_ (addr) , fOptions_ (options) , fICMPPacketSize_{Options::kAllowedICMPPayloadSizeRange.Pin (options.fPacketPayloadSize.Value (Options::kDefaultPayloadSize)) + sizeof (ICMP::V4::PacketHeader)} , fSendPacket_{fICMPPacketSize_} , fSocket_{Socket::ProtocolFamily::INET, Socket::SocketKind::RAW, IPPROTO_ICMP} , fNextSequenceNumber_{static_cast<uint16_t> (skAllUInt16Distribution_ (sRng_))} , fPingTimeout{options.fTimeout.Value (Options::kDefaultTimeout).As<Time::DurationSecondsType> ()} { DbgTrace (L"Frameworks::NetworkMonitor::Ping::Pinger::CTOR", L"addr=%s, options=%s", Characters::ToString (fDestination_).c_str (), Characters::ToString (fOptions_).c_str ()); // use random data as a payload for (Byte* p = (Byte*)fSendPacket_.begin () + sizeof (ICMP::V4::PacketHeader); p < fSendPacket_.end (); ++p) { static std::uniform_int_distribution<std::mt19937::result_type> sAnyByteDistribution_ (0, numeric_limits<Byte>::max ()); *p = sAnyByteDistribution_ (sRng_); } } Pinger::ResultType Pinger::RunOnce (const Optional<unsigned int>& ttl) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Frameworks::NetworkMonitor::Ping::Pinger::RunOnce", L"ttl=%s", Characters::ToString (ttl).c_str ())}; return RunOnce_ICMP_ (ttl.Value (fOptions_.fMaxHops.Value (Options::kDefaultMaxHops))); } Pinger::ResultType Pinger::RunOnce_ICMP_ (unsigned int ttl) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Frameworks::NetworkMonitor::Ping::Pinger::RunOnce_ICMP_", L"ttl=%d", ttl)}; fSocket_.setsockopt (IPPROTO_IP, IP_TTL, ttl); // max # of hops ICMP::V4::PacketHeader pingRequest = [&]() { ICMP::V4::PacketHeader tmp{}; tmp.type = ICMP::V4::ICMP_ECHO_REQUEST; tmp.id = skAllUInt16Distribution_ (sRng_); tmp.seq = fNextSequenceNumber_++; tmp.timestamp = static_cast<uint32_t> (Time::GetTickCount () * 1000); return tmp; }(); (void)::memcpy (fSendPacket_.begin (), &pingRequest, sizeof (pingRequest)); reinterpret_cast<ICMP::V4::PacketHeader*> (fSendPacket_.begin ())->checksum = IP::ip_checksum (fSendPacket_.begin (), fSendPacket_.begin () + fICMPPacketSize_); fSocket_.SendTo (fSendPacket_.begin (), fSendPacket_.end (), SocketAddress{fDestination_, 0}); // Find first packet responding (some packets could be bogus/ignored) Time::DurationSecondsType pingTimeoutAfter = Time::GetTickCount () + fPingTimeout; while (true) { ThrowTimeoutExceptionAfter (pingTimeoutAfter); SocketAddress fromAddress; constexpr size_t kExtraSluff_{100}; // Leave a little extra room in case some packets return extra SmallStackBuffer<Byte> recv_buf (fICMPPacketSize_ + sizeof (ICMP::V4::PacketHeader) + 2 * sizeof (IP::V4::PacketHeader) + kExtraSluff_); // icmpPacketSize includes ONE ICMP header and payload, but we get 2 IP and 2 ICMP headers in TTL Exceeded response size_t n = fSocket_.ReceiveFrom (begin (recv_buf), end (recv_buf), 0, &fromAddress, fPingTimeout); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"got back packet from %s", Characters::ToString (fromAddress).c_str ()); #endif const IP::V4::PacketHeader* replyIPHeader = reinterpret_cast<const IP::V4::PacketHeader*> (recv_buf.begin ()); // Skip ahead to the ICMP header within the IP packet unsigned short header_len = replyIPHeader->ihl * 4; const ICMP::V4::PacketHeader* replyICMPHeader = (const ICMP::V4::PacketHeader*)((const Byte*)replyIPHeader + header_len); // Make sure the reply is sane if (n < header_len + ICMP::V4::ICMP_MIN) { Execution::Throw (Execution::StringException (L"too few bytes from " + Characters::ToString (fromAddress))); // draft @todo fix } /* * If we got a response id, compare it with the request we sent to make sure we're reading a resposne to the request we sent */ Optional<uint16_t> echoedID; switch (replyICMPHeader->type) { case ICMP::V4::ICMP_ECHO_REPLY: { echoedID = replyICMPHeader->id; } break; case ICMP::V4::ICMP_TTL_EXPIRE: { // According to https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Time_exceeded - we also can find the first 8 bytes of original datagram's data const ICMP::V4::PacketHeader* echoedICMPHeader = (const ICMP::V4::PacketHeader*)((const Byte*)replyICMPHeader + 8 + sizeof (IP::V4::PacketHeader)); echoedID = echoedICMPHeader->id; } break; case ICMP::V4::ICMP_DEST_UNREACH: { // According to https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Destination_unreachable - we also can find the first 8 bytes of original datagram's data const ICMP::V4::PacketHeader* echoedICMPHeader = (const ICMP::V4::PacketHeader*)((const Byte*)replyICMPHeader + 8 + sizeof (IP::V4::PacketHeader)); echoedID = echoedICMPHeader->id; } break; } if (echoedID and echoedID != pingRequest.id) { DbgTrace (L"echoedID (%s != pingRequest.id (%x) so ignoring this reply", Characters::ToString (echoedID).c_str (), pingRequest.id); // Must be a reply for another pinger running locally, so just // ignore it. continue; } /* * Handle differnt response messages differntly - but looking for ICMP_ECHO_REPLY, or ICMP_TTL_EXPIRE (for traceroute) */ switch (replyICMPHeader->type) { case ICMP::V4::ICMP_ECHO_REPLY: { // Different operating systems use different starting values for TTL. TTL here is the original number used, // less the number of hops. So we are left with making an educated guess. Need refrence and would be nice to find better // way, but this seems to work pretty often. unsigned int nHops{}; if (replyIPHeader->ttl > 128) { nHops = 257 - replyIPHeader->ttl; } else if (replyIPHeader->ttl > 64) { nHops = 129 - replyIPHeader->ttl; } else { nHops = 65 - replyIPHeader->ttl; } #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"reply->ttl = %d, nHops = %d", replyIPHeader->ttl, nHops); #endif return ResultType{Duration (Time::GetTickCount () - replyICMPHeader->timestamp / 1000.0), nHops}; } case ICMP::V4::ICMP_TTL_EXPIRE: { Execution::Throw (ICMP::V4::TTLExpiredException (InternetAddress{replyIPHeader->saddr})); } case ICMP::V4::ICMP_DEST_UNREACH: { Execution::Throw (ICMP::V4::DestinationUnreachableException (replyICMPHeader->code, InternetAddress{replyIPHeader->saddr})); }; default: { Execution::Throw (ICMP::V4::UnknownICMPPacket (replyICMPHeader->type)); } } } AssertNotReached (); return ResultType{}; } /* ******************************************************************************** ********************** NetworkMonitor::Ping::SampleOptions ********************* ******************************************************************************** */ Characters::String SampleOptions::ToString () const { StringBuilder sb; sb += L"{"; sb += L"Interval: " + Characters::ToString (fInterval) + L", "; sb += L"Count: " + Characters::Format (L"%d", fSampleCount) + L", "; sb += L"}"; return sb.str (); } /* ******************************************************************************** ******************* NetworkMonitor::Ping::SampleResults ************************ ******************************************************************************** */ String SampleResults::ToString () const { StringBuilder sb; sb += L"{"; if (fMedianPingTime) { sb += L"Median-Ping-Time: " + Characters::ToString (*fMedianPingTime) + L", "; } if (fMedianHopCount) { sb += L"Median-Hop-Count: " + Characters::Format (L"%d", *fMedianHopCount) + L", "; } if (fExceptionCount != 0) { sb += L"Exception-Count: " + Characters::Format (L"%d", fExceptionCount) + L", "; // to see exceptions - run with sample-count = 1 } sb += L"}"; return sb.str (); } /* ******************************************************************************** ************************* NetworkMonitor::Ping::Sample ************************* ******************************************************************************** */ SampleResults NetworkMonitor::Ping::Sample (const InternetAddress& addr, const SampleOptions& sampleOptions, const Options& options) { Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Frameworks::NetworkMonitor::Ping::Sample", L"addr=%s, sampleOptions=%s, options=%s", Characters::ToString (addr).c_str (), Characters::ToString (sampleOptions).c_str (), Characters::ToString (options).c_str ())}; Pinger pinger{addr, options}; Collection<DurationSecondsType> sampleTimes; Collection<unsigned int> sampleHopCounts; unsigned int samplesTaken{}; while (samplesTaken < sampleOptions.fSampleCount) { if (samplesTaken != 0) { Execution::Sleep (sampleOptions.fInterval); } try { Pinger::ResultType tmp = pinger.RunOnce (); sampleTimes += tmp.fPingTime.As<DurationSecondsType> (); sampleHopCounts += tmp.fHopCount; samplesTaken++; } catch (...) { samplesTaken++; } } return sampleTimes.empty () ? SampleResults{{}, {}, samplesTaken} : SampleResults{Duration (*sampleTimes.Median ()), *sampleHopCounts.Median (), static_cast<unsigned int> (samplesTaken - sampleTimes.size ())}; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkExceptionObject.h" #include "otbImage.h" #include "otbImageFileReader.h" // Software Guide : BeginCommandLineArgs // INPUTS: {ROISpot5.png} // 2 2 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example illustrates the use of the \doxygen{otb}{ComplexMomentImageFunction}. // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbComplexMomentImageFunction.h" // Software Guide : EndCodeSnippet int main(int argc, char * argv[]) { if (argc != 4) { std::cerr << "Usage: " << argv[0] << " inputImageFile "; std::cerr << " p q" << std::endl; return EXIT_FAILURE; } const char * inputFilename = argv[1]; unsigned int P((unsigned char) ::atoi(argv[2])); unsigned int Q((unsigned char) ::atoi(argv[3])); typedef unsigned char InputPixelType; const unsigned int Dimension = 2; typedef otb::Image<InputPixelType, Dimension> InputImageType; typedef otb::ImageFileReader<InputImageType> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(inputFilename); // Software Guide : BeginLatex // // The \doxygen{otb}{ComplexMomentImageFunction} is templated over the // input image type and the output complex type value, so we start by // defining: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::ComplexMomentImageFunction<InputImageType> CMType; typedef CMType::ComplexType ComplexType; CMType::Pointer cmFunction = CMType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next, we plug the input image into the complex moment fucntion // and we set its parameters. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet reader->Update(); cmFunction->SetInputImage(reader->GetOutput()); cmFunction->SetQmax(Q); cmFunction->SetPmax(P); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // We can chose the pixel of the image which will used as center // for the moment computation // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet InputImageType::IndexType center; center[0] = 50; center[1] = 50; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // We can also choose the size of the neighborhood around the // center pixel for the moment computation. // // Software Guide : EndLatex cmFunction->SetNeighborhoodRadius(15); // Software Guide : BeginLatex // In order to get the value of the moment, we call the // \code{EvaluateAtIndex} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ComplexType Result = cmFunction->EvaluateAtIndex(center); std::cout << "The moment of order (" << P << "," << Q << ") is equal to " << Result.at(P).at(Q) << std::endl; // Software Guide : EndCodeSnippet return EXIT_SUCCESS; } <commit_msg>COMP: updated ComplexMomentImageExample<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkExceptionObject.h" #include "otbImage.h" #include "otbImageFileReader.h" // Software Guide : BeginCommandLineArgs // INPUTS: {ROISpot5.png} // 2 2 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example illustrates the use of the \doxygen{otb}{ComplexMomentImageFunction}. // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbComplexMomentImageFunction.h" // Software Guide : EndCodeSnippet int main(int argc, char * argv[]) { if (argc != 4) { std::cerr << "Usage: " << argv[0] << " inputImageFile "; std::cerr << " p q" << std::endl; return EXIT_FAILURE; } const char * inputFilename = argv[1]; unsigned int P((unsigned char) ::atoi(argv[2])); unsigned int Q((unsigned char) ::atoi(argv[3])); typedef unsigned char InputPixelType; const unsigned int Dimension = 2; typedef otb::Image<InputPixelType, Dimension> InputImageType; typedef otb::ImageFileReader<InputImageType> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(inputFilename); // Software Guide : BeginLatex // // The \doxygen{otb}{ComplexMomentImageFunction} is templated over the // input image type and the output complex type value, so we start by // defining: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::ComplexMomentImageFunction<InputImageType> CMType; typedef CMType::OutputType OutputType; CMType::Pointer cmFunction = CMType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next, we plug the input image into the complex moment fucntion // and we set its parameters. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet reader->Update(); cmFunction->SetInputImage(reader->GetOutput()); cmFunction->SetQmax(Q); cmFunction->SetPmax(P); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // We can chose the pixel of the image which will used as center // for the moment computation // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet InputImageType::IndexType center; center[0] = 50; center[1] = 50; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // We can also choose the size of the neighborhood around the // center pixel for the moment computation. // // Software Guide : EndLatex cmFunction->SetNeighborhoodRadius(15); // Software Guide : BeginLatex // In order to get the value of the moment, we call the // \code{EvaluateAtIndex} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet OutputType Result = cmFunction->EvaluateAtIndex(center); std::cout << "The moment of order (" << P << "," << Q << ") is equal to " << Result.at(P).at(Q) << std::endl; // Software Guide : EndCodeSnippet return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> #include "itkOpenCVImageBridge.h" #include "itkRGBPixel.h" #include "itkImageFileReader.h" #include "itkDifferenceImageFilter.h" //DEBUG #include "itkImageFileWriter.h" // // Templated test function to do the heavy lifting // template<class TPixelType, unsigned int VDimension> int itkOpenCVImageBridgeTestTemplated(char* filename) { // typedefs const unsigned int Dimension = VDimension; typedef TPixelType PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; typedef itk::DifferenceImageFilter<ImageType, ImageType> DifferenceFilterType; // // Read the image directly // typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(filename); reader->Update(); typename ImageType::Pointer baselineImage = reader->GetOutput(); // // Test IplImage -> itk::Image // IplImage* inIpl; inIpl = cvLoadImage(filename); if (!inIpl) { std::cerr << "Could not load scalar input as IplImage" << std::endl; return EXIT_FAILURE; } typename ImageType::Pointer outIplITK = itk::OpenCVImageBridge::IplImageToITKImage< ImageType >(inIpl); // // Check results // typename DifferenceFilterType::Pointer differ = DifferenceFilterType::New(); differ->SetValidInput(baselineImage); differ->SetTestInput(outIplITK); differ->Update(); typename DifferenceFilterType::AccumulateType total = differ->GetTotalDifference(); if (total != 0) { std::cerr << "Images didn't match for pixel type " << typeid(PixelType).name() << std::endl; return EXIT_FAILURE; } //DEBUG //std::cout << "Total Difference: " << total << std::endl; // Return successfully return EXIT_SUCCESS; } // // Main test // int itkOpenCVImageBridgeTest ( int argc, char *argv[] ) { // // Check arguments // if (argc < 3) { std::cerr << "Usage: " << argv[0] << " scalar_image color_image" << std::endl; return EXIT_FAILURE; } #define RUN_TEST(_PixelType, _inFile)\ if (itkOpenCVImageBridgeTestTemplated< _PixelType, 2 >(_inFile) == EXIT_FAILURE)\ {\ return EXIT_FAILURE;\ } // // Test for supported types // RUN_TEST(char, argv[1]); RUN_TEST(unsigned char, argv[1]); RUN_TEST(short, argv[1]); RUN_TEST(unsigned short, argv[1]); RUN_TEST(int, argv[1]); RUN_TEST(unsigned int, argv[1]); RUN_TEST(float, argv[1]); RUN_TEST(double, argv[1]); //RUN_TEST(itk::RGBPixel<unsigned char>, argv[1]); std::cout << "STUB!!" << std::endl; return EXIT_SUCCESS; } <commit_msg>ENH: Finalize test for IplImage to ITK<commit_after>#include <iostream> #include "itkOpenCVImageBridge.h" #include "itkRGBPixel.h" #include "itkImageFileReader.h" #include "itkDifferenceImageFilter.h" #include "itkImageRegionConstIterator.h" //DEBUG #include "itkImageFileWriter.h" // // Compare RGBPixel Images // template<class TPixelValue, unsigned int VDimension> TPixelValue RGBImageTotalAbsDifference( itk::Image<itk::RGBPixel<TPixelValue>, VDimension>* valid, itk::Image<itk::RGBPixel<TPixelValue>, VDimension>* test) { typedef itk::RGBPixel<TPixelValue> PixelType; typedef itk::Image<PixelType, VDimension> RGBImageType; typedef itk::ImageRegionConstIterator<RGBImageType> IterType; IterType validIt(valid, valid->GetLargestPossibleRegion()); IterType testIt(test, test->GetLargestPossibleRegion()); TPixelValue totalDiff = 0; while(!validIt.IsAtEnd()) { PixelType validPx = validIt.Get(); PixelType testPx = testIt.Get(); totalDiff += std::abs(validPx[0] - testPx[0]); totalDiff += std::abs(validPx[1] - testPx[1]); totalDiff += std::abs(validPx[2] - testPx[2]); ++validIt; ++testIt; } return totalDiff; } // // Templated test function to do the heavy lifting for scalar case // template<class TPixelType, unsigned int VDimension> int itkOpenCVImageBridgeTestTemplatedScalar(char* filename) { // typedefs const unsigned int Dimension = VDimension; typedef TPixelType PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; typedef itk::DifferenceImageFilter<ImageType, ImageType> DifferenceFilterType; // // Read the image directly // typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(filename); reader->Update(); typename ImageType::Pointer baselineImage = reader->GetOutput(); // // Test IplImage -> itk::Image // IplImage* inIpl; inIpl = cvLoadImage(filename); if (!inIpl) { std::cerr << "Could not load input as IplImage" << std::endl; return EXIT_FAILURE; } typename ImageType::Pointer outIplITK = itk::OpenCVImageBridge::IplImageToITKImage< ImageType >(inIpl); // // Check results // typename DifferenceFilterType::Pointer differ = DifferenceFilterType::New(); differ->SetValidInput(baselineImage); differ->SetTestInput(outIplITK); differ->Update(); typename DifferenceFilterType::AccumulateType total = differ->GetTotalDifference(); if (total != 0) { std::cerr << "Images didn't match for pixel type " << typeid(PixelType).name() << std::endl; return EXIT_FAILURE; } // Return successfully return EXIT_SUCCESS; } // // Templated test function to do the heavy lifting for RGB case // template<class TPixelType, unsigned int VDimension> int itkOpenCVImageBridgeTestTemplatedRGB(char* filename) { // typedefs const unsigned int Dimension = VDimension; typedef TPixelType PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; typedef itk::DifferenceImageFilter<ImageType, ImageType> DifferenceFilterType; // // Read the image directly // typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(filename); reader->Update(); typename ImageType::Pointer baselineImage = reader->GetOutput(); // // Test IplImage -> itk::Image // IplImage* inIpl; inIpl = cvLoadImage(filename); if (!inIpl) { std::cerr << "Could not load input as IplImage" << std::endl; return EXIT_FAILURE; } typename ImageType::Pointer outIplITK = itk::OpenCVImageBridge::IplImageToITKImage< ImageType >(inIpl); // // Check results // if (RGBImageTotalAbsDifference<typename PixelType::ComponentType, Dimension>( baselineImage, outIplITK) != 0) { std::cerr << "Images didn't match for pixel type " << typeid(PixelType).name() << std::endl; return EXIT_FAILURE; } // Return successfully return EXIT_SUCCESS; } // // Main test // int itkOpenCVImageBridgeTest ( int argc, char *argv[] ) { // // Check arguments // if (argc < 3) { std::cerr << "Usage: " << argv[0] << " scalar_image color_image" << std::endl; return EXIT_FAILURE; } #define RUN_SCALAR_TEST(_PixelType, _inFile)\ if (itkOpenCVImageBridgeTestTemplatedScalar< _PixelType, 2 >(_inFile) == EXIT_FAILURE)\ {\ return EXIT_FAILURE;\ } #define RUN_RGB_TEST(_PixelType, _inFile)\ if (itkOpenCVImageBridgeTestTemplatedRGB< itk::RGBPixel<_PixelType>, 2 >(_inFile) == EXIT_FAILURE)\ {\ return EXIT_FAILURE;\ } // // Test for scalar types // RUN_SCALAR_TEST(char, argv[1]); RUN_SCALAR_TEST(unsigned char, argv[1]); RUN_SCALAR_TEST(short, argv[1]); RUN_SCALAR_TEST(unsigned short, argv[1]); RUN_SCALAR_TEST(int, argv[1]); RUN_SCALAR_TEST(unsigned int, argv[1]); RUN_SCALAR_TEST(float, argv[1]); RUN_SCALAR_TEST(double, argv[1]); // // Test for RGB types // RUN_RGB_TEST(char, argv[1]); RUN_RGB_TEST(unsigned char, argv[1]); RUN_RGB_TEST(short, argv[1]); RUN_RGB_TEST(unsigned short, argv[1]); RUN_RGB_TEST(int, argv[1]); RUN_RGB_TEST(unsigned int, argv[1]); RUN_RGB_TEST(float, argv[1]); RUN_RGB_TEST(double, argv[1]); std::cout << "STUB!!" << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <assert.h> #include "../generated/generatedStub.h" #include "../generated/genmech.nsmap" using std::string; using std::vector; struct arguments { string sourceFile; string sourcePath; string targetFile; }; void printHelp(); int doWork(char *sourceFile, char *sourcePath, char *targetFile); int main(int argc, char **argv) { const char *s_HELP = "-h"; const char *l_HELP = "--help"; char *sourceFile; char *sourcePath; char *targetFile; // Help! if (argc == 2 && (strcmp(argv[1], s_HELP)==0 || strcmp(argv[1], l_HELP)==0)) { printHelp(); return 0; } else if (argc == 4) { sourceFile = argv[1]; sourcePath = argv[2]; targetFile = argv[3]; return doWork(sourceFile, sourcePath, targetFile); } else { std::cout << "Invalid arguments, run \"createmech\" " << s_HELP << "\" for help" << std::endl; return 1; } return 0; } void printHelp() { using std::cout; using std::endl; cout << "\nUsage: createmech source_mesh_name path/to/sourcefile targetfilename" << endl; cout << "\nThis utility program takes a blender->ogre imported mesh.xml and skeleton.xml" << endl; cout << "and creates a corresponding blank new mech description XML file with given mesh" << endl; cout << "file and generated equipment slot defintions from the skeleton bones." << endl; cout << "Source mesh name should exclude the file extensions: MyFile.mesh.xml --> MyFile" << endl; cout << "\nOPTIONS:" << endl; cout << "-h, --help\t\tPrints this help" << endl; } int doWork(char *sourceFile, char *sourcePath, char *targetFile) { struct soap strsoap; _genmesh__mesh mesh; _genskel__skeleton skeleton; _genmech__mech mech; soap_init(&strsoap); soap_begin(&strsoap); std::ifstream mesh_ifs; char *inputFile; inputFile = (char *) malloc(strlen(sourceFile)+strlen(sourcePath)+strlen(".mesh.xml")+2); strcpy(inputFile, sourcePath); strcat(inputFile, "/"); strcat(inputFile, sourceFile); strcat(inputFile, ".mesh.xml"); mesh_ifs.open(inputFile, std::ifstream::in); if (mesh_ifs.fail()) { std::cout << "Could not open file " << inputFile << std::endl; free(inputFile); return 1; } strsoap.socket = -1; strsoap.is = &mesh_ifs; // Read MESH from file. soap_begin_recv(&strsoap); if (0 == soap_get__genmesh__mesh(&strsoap, &mesh, "mesh", NULL)) { std::cout << "Unable to read mesh from file!" << std::endl; free(inputFile); return 2; } soap_end_recv(&strsoap); free(inputFile); if (mesh.genmesh__skeletonlink == 0) { std::cout << "Given mesh does not have a skeleton, aborting!" << std::endl; return 3; } std::string skeletonName(mesh.genmesh__skeletonlink->name.c_str()); // Close mesh file, delete temporaries. mesh_ifs.close(); soap_destroy(&strsoap); soap_end(&strsoap); soap_done(&strsoap); // Initialize context for reading from SKELETON soap_init(&strsoap); soap_begin(&strsoap); std::ifstream skeleton_ifs; char *skeletonFile = (char *) malloc(strlen(sourcePath) + strlen(".xml") + strlen(skeletonName.c_str()) + 2); strcpy(skeletonFile, sourcePath); strcat(skeletonFile, "/"); strcat(skeletonFile, skeletonName.c_str()); strcat(skeletonFile, ".xml\0"); skeleton_ifs.open(skeletonFile, std::ifstream::in); if (skeleton_ifs.fail()) { std::cout << "Failed to open skeleton file " << skeletonFile << std::endl; free(skeletonFile); return 4; } strsoap.socket = -1; strsoap.is = &skeleton_ifs; // Reading SKELETON from file. soap_begin_recv(&strsoap); if (!soap_get__genskel__skeleton(&strsoap, &skeleton, "skeleton", NULL)) { std::cout << "Error reading skeleton from " << skeletonFile << std::endl; free(skeletonFile); return 5; } soap_end_recv(&strsoap); assert(skeleton.bones!=0); std::vector<std::string> slotBones; std::vector<std::string> rotateBones; std::vector<genskel__bone *>::iterator it; std::vector<genskel__bone *>::iterator end = skeleton.bones->bone.end(); for (it = skeleton.bones->bone.begin(); it<end; ++it) { if (!strncmp("B_SLOT", (*it)->name.c_str(), 6)) { slotBones.push_back(std::string((*it)->name.c_str())); continue; } if (!strncmp("B_ROTATE", (*it)->name.c_str(), 8)) { rotateBones.push_back(std::string((*it)->name.c_str())); } } std::cout << skeleton.bones->bone.size() << " bones in skeleton" << std::endl; std::cout << slotBones.size() << " slot bones in skeleton" << std::endl; std::cout << rotateBones.size() << " rotate bones in skeleton" << std::endl; soap_destroy(&strsoap); soap_end(&strsoap); soap_done(&strsoap); std::cout << "Read skeleton OK!" << std::endl; free(skeletonFile); return 0; } <commit_msg>Mech file writing works now. Still missing meshes<commit_after>#include <iostream> #include <fstream> #include <vector> #include <assert.h> #include "../generated/generatedStub.h" #include "../generated/genmech.nsmap" using std::string; using std::vector; struct arguments { string sourceFile; string sourcePath; string targetFile; }; void printHelp(); int doWork(char *sourceFile, char *sourcePath, char *targetFile); int main(int argc, char **argv) { const char *s_HELP = "-h"; const char *l_HELP = "--help"; char *sourceFile; char *sourcePath; char *targetFile; // Help! if (argc == 2 && (strcmp(argv[1], s_HELP)==0 || strcmp(argv[1], l_HELP)==0)) { printHelp(); return 0; } else if (argc == 4) { sourceFile = argv[1]; sourcePath = argv[2]; targetFile = argv[3]; return doWork(sourceFile, sourcePath, targetFile); } else { std::cout << "Invalid arguments, run \"createmech\" " << s_HELP << "\" for help" << std::endl; return 1; } return 0; } void printHelp() { using std::cout; using std::endl; cout << "\nUsage: createmech source_mesh_name path/to/sourcefile targetfilename" << endl; cout << "\nThis utility program takes a blender->ogre imported mesh.xml and skeleton.xml" << endl; cout << "and creates a corresponding blank new mech description XML file with given mesh" << endl; cout << "file and generated equipment slot defintions from the skeleton bones." << endl; cout << "Source mesh name should exclude the file extensions: MyFile.mesh.xml --> MyFile" << endl; cout << "\nOPTIONS:" << endl; cout << "-h, --help\t\tPrints this help" << endl; } _genmech__mech *constructEmptyMech(); genmech__equSlot *constructEquSlot(const char *boneName); int doWork(char *sourceFile, char *sourcePath, char *targetFile) { struct soap strsoap; _genmesh__mesh mesh; _genskel__skeleton skeleton; _genmech__mech *mech; soap_init(&strsoap); soap_begin(&strsoap); std::ifstream mesh_ifs; char *inputFile; inputFile = (char *) malloc(strlen(sourceFile)+strlen(sourcePath)+strlen(".mesh.xml")+2); strcpy(inputFile, sourcePath); strcat(inputFile, "/"); strcat(inputFile, sourceFile); strcat(inputFile, ".mesh.xml"); mesh_ifs.open(inputFile, std::ifstream::in); if (mesh_ifs.fail()) { std::cout << "Could not open file " << inputFile << std::endl; free(inputFile); return 1; } strsoap.socket = -1; strsoap.is = &mesh_ifs; // Read MESH from file. soap_begin_recv(&strsoap); if (0 == soap_get__genmesh__mesh(&strsoap, &mesh, "mesh", NULL)) { std::cout << "Unable to read mesh from file!" << std::endl; free(inputFile); return 2; } soap_end_recv(&strsoap); free(inputFile); if (mesh.genmesh__skeletonlink == 0) { std::cout << "Given mesh does not have a skeleton, aborting!" << std::endl; return 3; } std::string skeletonName(mesh.genmesh__skeletonlink->name.c_str()); // Close mesh file, delete temporaries. mesh_ifs.close(); soap_destroy(&strsoap); soap_end(&strsoap); soap_done(&strsoap); // Initialize context for reading from SKELETON soap_init(&strsoap); soap_begin(&strsoap); std::ifstream skeleton_ifs; char *skeletonFile = (char *) malloc(strlen(sourcePath) + strlen(".xml") + strlen(skeletonName.c_str()) + 2); strcpy(skeletonFile, sourcePath); strcat(skeletonFile, "/"); strcat(skeletonFile, skeletonName.c_str()); strcat(skeletonFile, ".xml\0"); skeleton_ifs.open(skeletonFile, std::ifstream::in); if (skeleton_ifs.fail()) { std::cout << "Failed to open skeleton file " << skeletonFile << std::endl; free(skeletonFile); return 4; } strsoap.socket = -1; strsoap.is = &skeleton_ifs; // Reading SKELETON from file. soap_begin_recv(&strsoap); if (!soap_get__genskel__skeleton(&strsoap, &skeleton, "skeleton", NULL)) { std::cout << "Error reading skeleton from " << skeletonFile << std::endl; free(skeletonFile); return 5; } soap_end_recv(&strsoap); assert(skeleton.bones!=0); mech = constructEmptyMech(); mech->name = std::string(sourceFile); std::vector<std::string> slotBones; std::vector<std::string> rotateBones; std::vector<genskel__bone *>::iterator it; std::vector<genskel__bone *>::iterator end = skeleton.bones->bone.end(); for (it = skeleton.bones->bone.begin(); it<end; ++it) { const char *boneName = (*it)->name.c_str(); if (strncmp("B_SLOT", boneName, 6) == 0) { slotBones.push_back(std::string(boneName)); mech->design->equipmentSlots->slot.push_back(constructEquSlot(boneName)); continue; } if (strncmp("B_ROTATE", boneName, 8) == 0) { mech->design->torsoBone = std::string(boneName); rotateBones.push_back(std::string(boneName)); } } std::cout << skeleton.bones->bone.size() << " bones in skeleton" << std::endl; std::cout << slotBones.size() << " slot bones in skeleton" << std::endl; std::cout << rotateBones.size() << " rotate bones in skeleton" << std::endl; if (rotateBones.size() != 1) { std::cout << "Expected just one rotate bone (torso), had more. This may be a problem." << std::endl; } soap_destroy(&strsoap); soap_end(&strsoap); soap_done(&strsoap); std::cout << "Read skeleton OK!" << std::endl; free(skeletonFile); soap_init(&strsoap); soap_begin(&strsoap); soap_set_omode(&strsoap, SOAP_XML_GRAPH); mech->soap_serialize(&strsoap); std::ofstream os; os.open(targetFile, std::ios_base::out | std::ios_base::trunc); if (os.fail()) { std::cout << "Error opening [" << targetFile << "] for write!"; return 6; } strsoap.os = &os; strsoap.socket = -1; soap_begin_send(&strsoap); mech->soap_put(&strsoap, "mech", NULL); soap_end_send(&strsoap); os.close(); soap_destroy(&strsoap); soap_end(&strsoap); soap_done(&strsoap); return 0; } /** * Constructs a new mech object, initializing it correctly. * User must delete the mech after using it. */ _genmech__mech *constructEmptyMech() { _genmech__mech *mech = new _genmech__mech(); mech->stats = new genmech__stats(); mech->stats->maxTurnRate = 5; mech->stats->maxForwardAcceleration = 5; mech->stats->maxBackwardAcceleration = 5; mech->stats->maxSpeed = 5; mech->design = new genmech__design(); mech->design->torso = new genmech__torso(); mech->design->equipmentSlots = new genmech__equSlots(); mech->media = new genmech__media(); return mech; } /** * Constructs a new equ slot object with given bone name value */ genmech__equSlot *constructEquSlot(const char *boneName) { genmech__equSlot *slot = new genmech__equSlot(); slot->boneName = std::string(boneName); return slot; } <|endoftext|>
<commit_before>#include <cstdlib> #include <ctime> #include <list> #include <vector> #include "AIPlayer.h" #include "ChessBoard.h" AIPlayer::AIPlayer(int color, int search_depth) : ChessPlayer(color), search_depth(search_depth) { srand(time(NULL)); } AIPlayer::~AIPlayer() {} bool AIPlayer::getMove(ChessBoard & board, Move & move) { list<Move> regulars, nulls; vector<Move> candidates; bool quiescent = false; int best, tmp; // first assume we are loosing best = -KING_VALUE; // get all moves board.getMoves(this->color, regulars, regulars, nulls); // execute maintenance moves for(list<Move>::iterator it = nulls.begin(); it != nulls.end(); ++it) board.move(*it); // loop over all moves for(list<Move>::iterator it = regulars.begin(); it != regulars.end(); ++it) { // execute move board.move(*it); // check if own king is vulnerable now if(!board.isVulnerable((this->color ? board.black_king_pos : board.white_king_pos), this->color)) { if((*it).capture != EMPTY) { quiescent = true; } // recursion tmp = -evalAlphaBeta(board, TOGGLE_COLOR(this->color), this->search_depth - 1, -WIN_VALUE, -best, quiescent); if(tmp > best) { best = tmp; candidates.clear(); candidates.push_back(*it); } else if(tmp == best) { candidates.push_back(*it); } } // undo move and inc iterator board.undoMove(*it); } // undo maintenance moves for(list<Move>::iterator it = nulls.begin(); it != nulls.end(); ++it) board.undoMove(*it); // loosing the game? if(best < -WIN_VALUE) { return false; } else { // select random move from candidate moves move = candidates[rand() % candidates.size()]; return true; } } int AIPlayer::evalAlphaBeta(ChessBoard & board, int color, int search_depth, int alpha, int beta, bool quiescent) { list<Move> regulars, nulls; int best, tmp; if(search_depth <= 0 && !quiescent) { if(color) return -evaluateBoard(board); else return +evaluateBoard(board); } // first assume we are loosing best = -WIN_VALUE; // get all moves board.getMoves(color, regulars, regulars, nulls); // execute maintenance moves for(list<Move>::iterator it = nulls.begin(); it != nulls.end(); ++it) board.move(*it); // loop over all moves for(list<Move>::iterator it = regulars.begin(); alpha <= beta && it != regulars.end(); ++it) { // execute move board.move(*it); // check if own king is vulnerable now if(!board.isVulnerable((color ? board.black_king_pos : board.white_king_pos), color)) { if((*it).capture == EMPTY) { quiescent = false; } else { quiescent = true; } // recursion 'n' pruning tmp = -evalAlphaBeta(board, TOGGLE_COLOR(color), search_depth - 1, -beta, -alpha, quiescent); if(tmp > best) { best = tmp; if(tmp > alpha) { alpha = tmp; } } } // undo move and inc iterator board.undoMove(*it); } // undo maintenance moves for(list<Move>::iterator it = nulls.begin(); it != nulls.end(); ++it) board.undoMove(*it); return best; } int AIPlayer::evaluateBoard(ChessBoard & board) { int figure, pos, sum = 0, summand; for(pos = 0; pos < 64; pos++) { figure = board.square[pos]; switch(FIGURE(figure)) { case PAWN: summand = PAWN_VALUE; break; case ROOK: summand = ROOK_VALUE; break; case KNIGHT: summand = KNIGHT_VALUE; break; case BISHOP: summand = BISHOP_VALUE; break; case QUEEN: summand = QUEEN_VALUE; break; case KING: summand = KING_VALUE; break; default: summand = 0; break; } sum += IS_BLACK(figure) ? -summand : summand; } return sum; } <commit_msg>Remove braces from single-line if..else.. bodies<commit_after>#include <cstdlib> #include <ctime> #include <list> #include <vector> #include "AIPlayer.h" #include "ChessBoard.h" AIPlayer::AIPlayer(int color, int search_depth) : ChessPlayer(color), search_depth(search_depth) { srand(time(NULL)); } AIPlayer::~AIPlayer() {} bool AIPlayer::getMove(ChessBoard & board, Move & move) { list<Move> regulars, nulls; vector<Move> candidates; bool quiescent = false; int best, tmp; // first assume we are loosing best = -KING_VALUE; // get all moves board.getMoves(this->color, regulars, regulars, nulls); // execute maintenance moves for(list<Move>::iterator it = nulls.begin(); it != nulls.end(); ++it) board.move(*it); // loop over all moves for(list<Move>::iterator it = regulars.begin(); it != regulars.end(); ++it) { // execute move board.move(*it); // check if own king is vulnerable now if(!board.isVulnerable((this->color ? board.black_king_pos : board.white_king_pos), this->color)) { if((*it).capture != EMPTY) { quiescent = true; } // recursion tmp = -evalAlphaBeta(board, TOGGLE_COLOR(this->color), this->search_depth - 1, -WIN_VALUE, -best, quiescent); if(tmp > best) { best = tmp; candidates.clear(); candidates.push_back(*it); } else if(tmp == best) { candidates.push_back(*it); } } // undo move and inc iterator board.undoMove(*it); } // undo maintenance moves for(list<Move>::iterator it = nulls.begin(); it != nulls.end(); ++it) board.undoMove(*it); // loosing the game? if(best < -WIN_VALUE) { return false; } else { // select random move from candidate moves move = candidates[rand() % candidates.size()]; return true; } } int AIPlayer::evalAlphaBeta(ChessBoard & board, int color, int search_depth, int alpha, int beta, bool quiescent) { list<Move> regulars, nulls; int best, tmp; if(search_depth <= 0 && !quiescent) { if(color) return -evaluateBoard(board); else return +evaluateBoard(board); } // first assume we are loosing best = -WIN_VALUE; // get all moves board.getMoves(color, regulars, regulars, nulls); // execute maintenance moves for(list<Move>::iterator it = nulls.begin(); it != nulls.end(); ++it) board.move(*it); // loop over all moves for(list<Move>::iterator it = regulars.begin(); alpha <= beta && it != regulars.end(); ++it) { // execute move board.move(*it); // check if own king is vulnerable now if(!board.isVulnerable((color ? board.black_king_pos : board.white_king_pos), color)) { if((*it).capture == EMPTY) quiescent = false; else quiescent = true; // recursion 'n' pruning tmp = -evalAlphaBeta(board, TOGGLE_COLOR(color), search_depth - 1, -beta, -alpha, quiescent); if(tmp > best) { best = tmp; if(tmp > alpha) { alpha = tmp; } } } // undo move and inc iterator board.undoMove(*it); } // undo maintenance moves for(list<Move>::iterator it = nulls.begin(); it != nulls.end(); ++it) board.undoMove(*it); return best; } int AIPlayer::evaluateBoard(ChessBoard & board) { int figure, pos, sum = 0, summand; for(pos = 0; pos < 64; pos++) { figure = board.square[pos]; switch(FIGURE(figure)) { case PAWN: summand = PAWN_VALUE; break; case ROOK: summand = ROOK_VALUE; break; case KNIGHT: summand = KNIGHT_VALUE; break; case BISHOP: summand = BISHOP_VALUE; break; case QUEEN: summand = QUEEN_VALUE; break; case KING: summand = KING_VALUE; break; default: summand = 0; break; } sum += IS_BLACK(figure) ? -summand : summand; } return sum; } <|endoftext|>
<commit_before>// Copyright (c) 2015 // Author: Chrono Law #include <std.hpp> using namespace std; #include <boost/utility/string_ref.hpp> #include <boost/algorithm/string.hpp> using namespace boost; ////////////////////////////////////////// void case1() { string str("readme.txt"); if (ends_with(str, "txt")) { cout << to_upper_copy(str) + " UPPER" << endl; assert(ends_with(str, "txt")); } replace_first(str, "readme", "followme"); cout << str << endl; vector<char> v(str.begin(), str.end()); vector<char> v2 = to_upper_copy( erase_first_copy(v, "txt")); for (auto ch : v2) { cout << ch; } } ////////////////////////////////////////// void case2() { string str("I Don't Know.\n"); cout << to_upper_copy(str); cout << str; to_lower(str); cout << str; } ////////////////////////////////////////// void case3() { string str("Power Bomb"); assert(iends_with(str, "bomb")); assert(!ends_with(str, "bomb")); assert(starts_with(str, "Pow")); assert(contains(str, "er")); string str2 = to_lower_copy(str); assert(iequals(str, str2)); string str3("power suit"); assert(ilexicographical_compare(str, str3)); assert(all(str2.substr(0, 5), is_lower())); } ////////////////////////////////////////// void case4() { string str1("Samus"), str2("samus"); assert(!is_equal()(str1, str2)); assert( is_less()(str1, str2)); //cout << (to_upper_copy(str1) == to_upper_copy(str2)) << endl; //cout << is_iequal()(str1, str2) << endl; assert(!is_equal()(str1, string_ref(str2))); } ////////////////////////////////////////// #include <boost/format.hpp> struct is_zero_or_one { bool operator()(char x) { return x == '0' || x == '1';} }; auto is01 = [](char x) { return x == '0' || x == '1';}; void case5() { format fmt("|%s|\n"); string str = " samus aran "; cout << fmt % trim_copy(str); cout << fmt % trim_left_copy(str); trim_right(str); cout << fmt % str; string str2 = "2015 Happy new Year!!!"; cout << fmt % trim_left_copy_if(str2, is_digit()); cout << fmt % trim_right_copy_if(str2, is_punct()); cout << fmt % trim_copy_if(str2, is_punct() || is_digit() || is_space()); } ////////////////////////////////////////// void case6() { format fmt("|%s|. pos = %d\n"); string str = "Long long ago, there was a king."; iterator_range<string::iterator> rge; rge = find_first(str, "long"); cout << fmt % rge % (rge.begin() - str.begin()); rge = ifind_first(str, "long"); cout << fmt % rge % (rge.begin() - str.begin()); rge = find_nth(str, "ng", 2); cout << fmt % rge % (rge.begin() - str.begin()); rge = find_head(str, 4); cout << fmt % rge % (rge.begin() - str.begin()); rge = find_tail(str, 5); cout << fmt % rge % (rge.begin() - str.begin()); rge = find_first(str, "samus"); assert(rge.empty() && !rge); } ////////////////////////////////////////// void case7() { string str = "Samus beat the monster.\n"; cout << replace_first_copy(str, "Samus", "samus"); replace_last(str, "beat", "kill"); cout << str; replace_tail(str, 9, "ridley.\n"); cout << str; cout << ierase_all_copy(str, "samus"); cout << replace_nth_copy(str, "l", 1, "L"); cout << erase_tail_copy(str, 8); } ////////////////////////////////////////// void case8() { string str = "Samus,Link.Zelda::Mario-Luigi+zelda"; deque<string> d; ifind_all(d, str, "zELDA"); assert(d.size() == 2); for (auto x : d) { cout << "["<< x << "] "; } cout << endl; list<iterator_range<string::iterator> > l; split(l, str, is_any_of(",.:-+")); for (auto x : l) { cout << "["<< x << "]"; } cout << endl; l.clear(); split(l, str, is_any_of(".:-"), token_compress_on); for (auto x : l) { cout << "["<< x << "]"; } cout << endl; } ////////////////////////////////////////// #include <boost/assign.hpp> void case9() { using namespace boost::assign; vector<string> v = list_of("Samus")("Link")("Zelda")("Mario"); cout << join(v, "+") << endl; //cout << join_if(v, "**", is_contains_a()); cout << join_if(v, "**", [](string_ref s) { return contains(s, "a"); } ); cout << endl; } ////////////////////////////////////////// void case10() { string str("Samus||samus||mario||||Link"); //typedef find_iterator<string::iterator> string_find_iterator; //string_find_iterator pos, end; //for (pos = make_find_iterator(str, first_finder("samus", is_iequal())); // pos != end; ++pos) //{ cout << "[" << *pos << "]" ; } auto pos = make_find_iterator(str, first_finder("samus", is_iequal())); decltype(pos) end; for(; pos != end; ++pos) { cout << "[" << *pos << "]" ; } cout << endl; typedef split_iterator<string::iterator> string_split_iterator; string_split_iterator p, endp; for (p = make_split_iterator(str, first_finder("||", is_iequal())); p != endp; ++p) { cout << "[" << *p << "]" ; } cout << endl; } ////////////////////////////////////////// int main() { case1(); case2(); case3(); case4(); case5(); case6(); case7(); case8(); case9(); case10(); } <commit_msg>string_algo.cpp<commit_after>// Copyright (c) 2015 // Author: Chrono Law #include <std.hpp> using namespace std; #include <boost/utility/string_ref.hpp> #include <boost/algorithm/string.hpp> using namespace boost; ////////////////////////////////////////// void case1() { string str("readme.txt"); if (ends_with(str, "txt")) { cout << to_upper_copy(str) + " UPPER" << endl; assert(ends_with(str, "txt")); } replace_first(str, "readme", "followme"); cout << str << endl; vector<char> v(str.begin(), str.end()); vector<char> v2 = to_upper_copy( erase_first_copy(v, "txt")); for (auto ch : v2) { cout << ch; } } ////////////////////////////////////////// void case2() { string str("FireEmblem Heroes\n"); cout << to_upper_copy(str); cout << str; to_lower(str); cout << str; } ////////////////////////////////////////// void case3() { string str("Power Bomb"); assert(iends_with(str, "bomb")); assert(!ends_with(str, "bomb")); assert(starts_with(str, "Pow")); assert(contains(str, "er")); string str2 = to_lower_copy(str); assert(iequals(str, str2)); string str3("power suit"); assert(ilexicographical_compare(str, str3)); assert(all(str2.substr(0, 5), is_lower())); } ////////////////////////////////////////// void case4() { string str1("Samus"), str2("samus"); assert(!is_equal()(str1, str2)); assert( is_less()(str1, str2)); //cout << (to_upper_copy(str1) == to_upper_copy(str2)) << endl; //cout << is_iequal()(str1, str2) << endl; assert(!is_equal()(str1, string_ref(str2))); } ////////////////////////////////////////// #include <boost/format.hpp> struct is_zero_or_one { bool operator()(char x) { return x == '0' || x == '1';} }; auto is01 = [](char x) { return x == '0' || x == '1';}; void case5() { format fmt("|%s|\n"); string str = " samus aran "; cout << fmt % trim_copy(str); cout << fmt % trim_left_copy(str); trim_right(str); cout << fmt % str; string str2 = "2015 Happy new Year!!!"; cout << fmt % trim_left_copy_if(str2, is_digit()); cout << fmt % trim_right_copy_if(str2, is_punct()); cout << fmt % trim_copy_if(str2, is_punct() || is_digit() || is_space()); } ////////////////////////////////////////// void case6() { format fmt("|%s|. pos = %d\n"); string str = "Long long ago, there was a king."; iterator_range<string::iterator> rge; rge = find_first(str, "long"); cout << fmt % rge % (rge.begin() - str.begin()); rge = ifind_first(str, "long"); cout << fmt % rge % (rge.begin() - str.begin()); rge = find_nth(str, "ng", 2); cout << fmt % rge % (rge.begin() - str.begin()); rge = find_head(str, 4); cout << fmt % rge % (rge.begin() - str.begin()); rge = find_tail(str, 5); cout << fmt % rge % (rge.begin() - str.begin()); rge = find_first(str, "samus"); assert(rge.empty() && !rge); } ////////////////////////////////////////// void case7() { string str = "Samus beat the monster.\n"; cout << replace_first_copy(str, "Samus", "samus"); replace_last(str, "beat", "kill"); cout << str; replace_tail(str, 9, "ridley.\n"); cout << str; cout << ierase_all_copy(str, "samus"); cout << replace_nth_copy(str, "l", 1, "L"); cout << erase_tail_copy(str, 8); } ////////////////////////////////////////// void case8() { string str = "Samus,Link.Zelda::Mario-Luigi+zelda"; deque<string> d; ifind_all(d, str, "zELDA"); assert(d.size() == 2); for (auto x : d) { cout << "["<< x << "] "; } cout << endl; list<iterator_range<string::iterator> > l; split(l, str, is_any_of(",.:-+")); for (auto x : l) { cout << "["<< x << "]"; } cout << endl; l.clear(); split(l, str, is_any_of(".:-"), token_compress_on); for (auto x : l) { cout << "["<< x << "]"; } cout << endl; } ////////////////////////////////////////// #include <boost/assign.hpp> void case9() { using namespace boost::assign; vector<string> v = list_of("Samus")("Link")("Zelda")("Mario"); cout << join(v, "+") << endl; //cout << join_if(v, "**", is_contains_a()); cout << join_if(v, "**", [](string_ref s) { return contains(s, "a"); } ); cout << endl; } ////////////////////////////////////////// void case10() { string str("Samus||samus||mario||||Link"); //typedef find_iterator<string::iterator> string_find_iterator; //string_find_iterator pos, end; //for (pos = make_find_iterator(str, first_finder("samus", is_iequal())); // pos != end; ++pos) //{ cout << "[" << *pos << "]" ; } auto pos = make_find_iterator(str, first_finder("samus", is_iequal())); decltype(pos) end; for(; pos != end; ++pos) { cout << "[" << *pos << "]" ; } cout << endl; typedef split_iterator<string::iterator> string_split_iterator; string_split_iterator p, endp; for (p = make_split_iterator(str, first_finder("||", is_iequal())); p != endp; ++p) { cout << "[" << *p << "]" ; } cout << endl; } ////////////////////////////////////////// int main() { case1(); case2(); case3(); case4(); case5(); case6(); case7(); case8(); case9(); case10(); } <|endoftext|>
<commit_before>#include <imgui_utils/app_runner/imgui_runner.h> #include "imgui_internal.h" #include <map> namespace ImGuiUtils { namespace ImGuiRunner { void MyCreateDockLayout(ImGuiID fullDockSpaceId) { ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::DockBuilderRemoveNode(fullDockSpaceId); // Clear out existing layout ImGui::DockBuilderAddNode(fullDockSpaceId); // Add empty node ImGui::DockBuilderSetNodeSize(fullDockSpaceId, viewport->Size); ImGuiID dock_main_id = fullDockSpaceId; // This variable will track the document node, however we are not using it // here as we aren't docking anything into it. ImGuiID dock_id_left = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Left, 0.20f, NULL, &dock_main_id); ImGuiID dock_id_right = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Right, 0.20f, NULL, &dock_main_id); ImGuiID dock_id_bottom = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Down, 0.20f, NULL, &dock_main_id); ImGuiID dock_id_left_bottom = ImGui::DockBuilderSplitNode(dock_id_left, ImGuiDir_Down, 0.50f, NULL, &dock_id_left); ImGui::DockBuilderDockWindow("Left", dock_id_left); ImGui::DockBuilderDockWindow("LeftBottom1", dock_id_left_bottom); ImGui::DockBuilderDockWindow("LeftBottom2", dock_id_left_bottom); ImGui::DockBuilderDockWindow("LeftBottom3", dock_id_left_bottom); ImGui::DockBuilderDockWindow("Main", dock_main_id); ImGui::DockBuilderDockWindow("Right", dock_id_right); ImGui::DockBuilderDockWindow("Bottom", dock_id_bottom); ImGui::DockBuilderFinish(fullDockSpaceId); } void DummyWindow(const char* title) { static std::map<std::string, bool> openStatuses; if (openStatuses.find(title) == openStatuses.end()) openStatuses[title] = true; ImGui::SetNextWindowSize(ImVec2(300, 300), ImGuiCond_Once); bool& dummyOpen = openStatuses.at(title); int windowFlags = 0;// ImGuiWindowFlags_NoMove; if (dummyOpen) { ImGui::Begin(title, &dummyOpen, windowFlags); ImGui::Text("%s", title); static bool show_demo_window = false; ImGui::Checkbox("Demo Window", &show_demo_window); if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); if (ImGui::Button("Reset Layout")) ImGuiRunner::ResetDockLayout(); ImGui::End(); } } void DemoGui() { std::vector<std::string> titles = { "Left", "LeftBottom1", "LeftBottom2", "LeftBottom3", "Right", "Main", "Bottom" }; for (const auto & title : titles) DummyWindow((title + "").c_str()); } void ShowDemo() { ImGuiUtils::ImGuiRunner::AppWindowParams params; params.DefaultWindowType = DefaultWindowTypeOption::ProvideFullScreenDockSpace; params.InitialDockLayoutFunction = MyCreateDockLayout; params.Title = "Hello World"; ImGuiUtils::ImGuiRunner::RunGui(DemoGui, params); } } } <commit_msg>imgui_runner_demo: add missing include<commit_after>#include <imgui_utils/app_runner/imgui_runner.h> #include "imgui_internal.h" #include <map> #include <vector> #include <string> namespace ImGuiUtils { namespace ImGuiRunner { void MyCreateDockLayout(ImGuiID fullDockSpaceId) { ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::DockBuilderRemoveNode(fullDockSpaceId); // Clear out existing layout ImGui::DockBuilderAddNode(fullDockSpaceId); // Add empty node ImGui::DockBuilderSetNodeSize(fullDockSpaceId, viewport->Size); ImGuiID dock_main_id = fullDockSpaceId; // This variable will track the document node, however we are not using it // here as we aren't docking anything into it. ImGuiID dock_id_left = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Left, 0.20f, NULL, &dock_main_id); ImGuiID dock_id_right = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Right, 0.20f, NULL, &dock_main_id); ImGuiID dock_id_bottom = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Down, 0.20f, NULL, &dock_main_id); ImGuiID dock_id_left_bottom = ImGui::DockBuilderSplitNode(dock_id_left, ImGuiDir_Down, 0.50f, NULL, &dock_id_left); ImGui::DockBuilderDockWindow("Left", dock_id_left); ImGui::DockBuilderDockWindow("LeftBottom1", dock_id_left_bottom); ImGui::DockBuilderDockWindow("LeftBottom2", dock_id_left_bottom); ImGui::DockBuilderDockWindow("LeftBottom3", dock_id_left_bottom); ImGui::DockBuilderDockWindow("Main", dock_main_id); ImGui::DockBuilderDockWindow("Right", dock_id_right); ImGui::DockBuilderDockWindow("Bottom", dock_id_bottom); ImGui::DockBuilderFinish(fullDockSpaceId); } void DummyWindow(const char* title) { static std::map<std::string, bool> openStatuses; if (openStatuses.find(title) == openStatuses.end()) openStatuses[title] = true; ImGui::SetNextWindowSize(ImVec2(300, 300), ImGuiCond_Once); bool& dummyOpen = openStatuses.at(title); int windowFlags = 0;// ImGuiWindowFlags_NoMove; if (dummyOpen) { ImGui::Begin(title, &dummyOpen, windowFlags); ImGui::Text("%s", title); static bool show_demo_window = false; ImGui::Checkbox("Demo Window", &show_demo_window); if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); if (ImGui::Button("Reset Layout")) ImGuiRunner::ResetDockLayout(); ImGui::End(); } } void DemoGui() { std::vector<std::string> titles = { "Left", "LeftBottom1", "LeftBottom2", "LeftBottom3", "Right", "Main", "Bottom" }; for (const auto & title : titles) DummyWindow((title + "").c_str()); } void ShowDemo() { ImGuiUtils::ImGuiRunner::AppWindowParams params; params.DefaultWindowType = DefaultWindowTypeOption::ProvideFullScreenDockSpace; params.InitialDockLayoutFunction = MyCreateDockLayout; params.Title = "Hello World"; ImGuiUtils::ImGuiRunner::RunGui(DemoGui, params); } } } <|endoftext|>
<commit_before>#include <osgVolume/VolumeScene> #include <osgDB/ObjectWrapper> #include <osgDB/InputStream> #include <osgDB/OutputStream> REGISTER_OBJECT_WRAPPER( osgVolume_VolumeScene, new osgVolume::VolumeScene, osgVolume::VolumeScene, "osg::Object osg::Node osg::Group osgVolume::VolumeScene" ) { } <commit_msg>add an include to osg/geometry<commit_after>#include <osg/Geometry> #include <osgVolume/VolumeScene> #include <osgDB/ObjectWrapper> #include <osgDB/InputStream> #include <osgDB/OutputStream> REGISTER_OBJECT_WRAPPER( osgVolume_VolumeScene, new osgVolume::VolumeScene, osgVolume::VolumeScene, "osg::Object osg::Node osg::Group osgVolume::VolumeScene" ) { } <|endoftext|>
<commit_before>/* Copyright 2017 Istio Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/istio/control/tcp/attributes_builder.h" #include "google/protobuf/text_format.h" #include "google/protobuf/util/message_differencer.h" #include "gtest/gtest.h" #include "include/istio/utils/attribute_names.h" #include "include/istio/utils/attributes_builder.h" #include "src/istio/control/tcp/mock_check_data.h" #include "src/istio/control/tcp/mock_report_data.h" #include "src/istio/utils/utils.h" using ::google::protobuf::TextFormat; using ::google::protobuf::util::MessageDifferencer; using ::testing::_; using ::testing::Invoke; using ::testing::Return; namespace istio { namespace control { namespace tcp { namespace { const char kCheckAttributes[] = R"( attributes { key: "context.protocol" value { string_value: "tcp" } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "source.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "origin.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "connection.mtls" value { bool_value: true } } attributes { key: "connection.requested_server_name" value { string_value: "www.google.com" } } attributes { key: "source.namespace" value { string_value: "ns_ns" } } attributes { key: "source.principal" value { string_value: "cluster.local/sa/test_user/ns/ns_ns/" } } attributes { key: "source.user" value { string_value: "cluster.local/sa/test_user/ns/ns_ns/" } } attributes { key: "destination.principal" value { string_value: "destination_user" } } attributes { key: "connection.id" value { string_value: "1234-5" } } )"; const char kFirstReportAttributes[] = R"( attributes { key: "connection.event" value { string_value: "open" } } attributes { key: "connection.received.bytes" value { int64_value: 0 } } attributes { key: "connection.received.bytes_total" value { int64_value: 0 } } attributes { key: "connection.sent.bytes" value { int64_value: 0 } } attributes { key: "connection.sent.bytes_total" value { int64_value: 0 } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "destination.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "destination.port" value { int64_value: 8080 } } attributes { key: "destination.uid" value { string_value: "pod1.ns2" } } attributes { key: "connection.filter_state" value { string_value: "www.google.com" } } )"; const char kReportAttributes[] = R"( attributes { key: "connection.event" value { string_value: "close" } } attributes { key: "check.error_code" value { int64_value: 3 } } attributes { key: "check.error_message" value { string_value: "INVALID_ARGUMENT:Invalid argument" } } attributes { key: "connection.duration" value { duration_value { nanos: 4 } } } attributes { key: "connection.received.bytes" value { int64_value: 144 } } attributes { key: "connection.received.bytes_total" value { int64_value: 345 } } attributes { key: "connection.sent.bytes" value { int64_value: 274 } } attributes { key: "connection.sent.bytes_total" value { int64_value: 678 } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "destination.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "destination.port" value { int64_value: 8080 } } attributes { key: "destination.uid" value { string_value: "pod1.ns2" } } attributes { key: "connection.filter_state" value { string_value: "aeiou" } } )"; const char kDeltaOneReportAttributes[] = R"( attributes { key: "connection.event" value { string_value: "continue" } } attributes { key: "connection.received.bytes" value { int64_value: 100 } } attributes { key: "connection.sent.bytes" value { int64_value: 200 } } attributes { key: "connection.received.bytes_total" value { int64_value: 100 } } attributes { key: "connection.sent.bytes_total" value { int64_value: 200 } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "destination.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "destination.port" value { int64_value: 8080 } } attributes { key: "destination.uid" value { string_value: "pod1.ns2" } } attributes { key: "connection.filter_state" value { string_value: "aeiou" } } )"; const char kDeltaTwoReportAttributes[] = R"( attributes { key: "connection.event" value { string_value: "continue" } } attributes { key: "connection.received.bytes" value { int64_value: 101 } } attributes { key: "connection.sent.bytes" value { int64_value: 204 } } attributes { key: "connection.received.bytes_total" value { int64_value: 201 } } attributes { key: "connection.sent.bytes_total" value { int64_value: 404 } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "destination.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "destination.port" value { int64_value: 8080 } } attributes { key: "destination.uid" value { string_value: "pod1.ns2" } } attributes { key: "connection.filter_state" value { string_value: "aeiou" } } )"; void ClearContextTime(RequestContext* request) { // Override timestamp with - utils::AttributesBuilder builder(request->attributes); std::chrono::time_point<std::chrono::system_clock> time0; builder.AddTimestamp(utils::AttributeName::kContextTime, time0); } TEST(AttributesBuilderTest, TestCheckAttributes) { ::testing::NiceMock<MockCheckData> mock_data; EXPECT_CALL(mock_data, GetSourceIpPort(_, _)) .WillOnce(Invoke([](std::string* ip, int* port) -> bool { *ip = "1.2.3.4"; *port = 8080; return true; })); EXPECT_CALL(mock_data, IsMutualTLS()).WillOnce(Invoke([]() -> bool { return true; })); EXPECT_CALL(mock_data, GetPrincipal(_, _)) .WillRepeatedly(Invoke([](bool peer, std::string* user) -> bool { if (peer) { *user = "cluster.local/sa/test_user/ns/ns_ns/"; } else { *user = "destination_user"; } return true; })); EXPECT_CALL(mock_data, GetConnectionId()).WillOnce(Return("1234-5")); EXPECT_CALL(mock_data, GetRequestedServerName(_)) .WillOnce(Invoke([](std::string* name) -> bool { *name = "www.google.com"; return true; })); RequestContext request; AttributesBuilder builder(&request); builder.ExtractCheckAttributes(&mock_data); ClearContextTime(&request); std::string out_str; TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; ::istio::mixer::v1::Attributes expected_attributes; ASSERT_TRUE( TextFormat::ParseFromString(kCheckAttributes, &expected_attributes)); EXPECT_TRUE( MessageDifferencer::Equals(*request.attributes, expected_attributes)); } TEST(AttributesBuilderTest, TestReportAttributes) { ::testing::NiceMock<MockReportData> mock_data; EXPECT_CALL(mock_data, GetDestinationIpPort(_, _)) .Times(4) .WillRepeatedly(Invoke([](std::string* ip, int* port) -> bool { *ip = "1.2.3.4"; *port = 8080; return true; })); EXPECT_CALL(mock_data, GetDestinationUID(_)) .Times(4) .WillRepeatedly(Invoke([](std::string* uid) -> bool { *uid = "pod1.ns2"; return true; })); EXPECT_CALL(mock_data, GetDynamicFilterState(_)) .Times(4) .WillRepeatedly(Invoke([](std::string* filter_state) -> bool { *filter_state = "aeiou"; return true; })); EXPECT_CALL(mock_data, GetReportInfo(_)) .Times(4) .WillOnce(Invoke([](ReportData::ReportInfo* info) { info->received_bytes = 0; info->send_bytes = 0; info->duration = std::chrono::nanoseconds(1); })) .WillOnce(Invoke([](ReportData::ReportInfo* info) { info->received_bytes = 100; info->send_bytes = 200; info->duration = std::chrono::nanoseconds(2); })) .WillOnce(Invoke([](ReportData::ReportInfo* info) { info->received_bytes = 201; info->send_bytes = 404; info->duration = std::chrono::nanoseconds(3); })) .WillOnce(Invoke([](ReportData::ReportInfo* info) { info->received_bytes = 345; info->send_bytes = 678; info->duration = std::chrono::nanoseconds(4); })); RequestContext request; request.check_status = ::google::protobuf::util::Status( ::google::protobuf::util::error::INVALID_ARGUMENT, "Invalid argument"); AttributesBuilder builder(&request); ReportData::ReportInfo last_report_info{0ULL, 0ULL, std::chrono::nanoseconds::zero()}; // Verify first open report builder.ExtractReportAttributes(&mock_data, ReportData::ConnectionEvent::OPEN, &last_report_info); ClearContextTime(&request); std::string out_str; TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; ::istio::mixer::v1::Attributes expected_open_attributes; ASSERT_TRUE(TextFormat::ParseFromString(kFirstReportAttributes, &expected_open_attributes)); EXPECT_TRUE(MessageDifferencer::Equals(*request.attributes, expected_open_attributes)); EXPECT_EQ(0, last_report_info.received_bytes); EXPECT_EQ(0, last_report_info.send_bytes); // Verify delta one report builder.ExtractReportAttributes( &mock_data, ReportData::ConnectionEvent::CONTINUE, &last_report_info); ClearContextTime(&request); TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; ::istio::mixer::v1::Attributes expected_delta_attributes; ASSERT_TRUE(TextFormat::ParseFromString(kDeltaOneReportAttributes, &expected_delta_attributes)); EXPECT_TRUE(MessageDifferencer::Equals(*request.attributes, expected_delta_attributes)); EXPECT_EQ(100, last_report_info.received_bytes); EXPECT_EQ(200, last_report_info.send_bytes); // Verify delta two report builder.ExtractReportAttributes( &mock_data, ReportData::ConnectionEvent::CONTINUE, &last_report_info); ClearContextTime(&request); out_str.clear(); TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; expected_delta_attributes.Clear(); ASSERT_TRUE(TextFormat::ParseFromString(kDeltaTwoReportAttributes, &expected_delta_attributes)); EXPECT_TRUE(MessageDifferencer::Equals(*request.attributes, expected_delta_attributes)); EXPECT_EQ(201, last_report_info.received_bytes); EXPECT_EQ(404, last_report_info.send_bytes); // Verify final report builder.ExtractReportAttributes( &mock_data, ReportData::ConnectionEvent::CLOSE, &last_report_info); ClearContextTime(&request); out_str.clear(); TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; ::istio::mixer::v1::Attributes expected_final_attributes; ASSERT_TRUE(TextFormat::ParseFromString(kReportAttributes, &expected_final_attributes)); EXPECT_TRUE(MessageDifferencer::Equals(*request.attributes, expected_final_attributes)); } } // namespace } // namespace tcp } // namespace control } // namespace istio <commit_msg>typos<commit_after>/* Copyright 2017 Istio Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/istio/control/tcp/attributes_builder.h" #include "google/protobuf/text_format.h" #include "google/protobuf/util/message_differencer.h" #include "gtest/gtest.h" #include "include/istio/utils/attribute_names.h" #include "include/istio/utils/attributes_builder.h" #include "src/istio/control/tcp/mock_check_data.h" #include "src/istio/control/tcp/mock_report_data.h" #include "src/istio/utils/utils.h" using ::google::protobuf::TextFormat; using ::google::protobuf::util::MessageDifferencer; using ::testing::_; using ::testing::Invoke; using ::testing::Return; namespace istio { namespace control { namespace tcp { namespace { const char kCheckAttributes[] = R"( attributes { key: "context.protocol" value { string_value: "tcp" } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "source.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "origin.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "connection.mtls" value { bool_value: true } } attributes { key: "connection.requested_server_name" value { string_value: "www.google.com" } } attributes { key: "source.namespace" value { string_value: "ns_ns" } } attributes { key: "source.principal" value { string_value: "cluster.local/sa/test_user/ns/ns_ns/" } } attributes { key: "source.user" value { string_value: "cluster.local/sa/test_user/ns/ns_ns/" } } attributes { key: "destination.principal" value { string_value: "destination_user" } } attributes { key: "connection.id" value { string_value: "1234-5" } } )"; const char kFirstReportAttributes[] = R"( attributes { key: "connection.event" value { string_value: "open" } } attributes { key: "connection.received.bytes" value { int64_value: 0 } } attributes { key: "connection.received.bytes_total" value { int64_value: 0 } } attributes { key: "connection.sent.bytes" value { int64_value: 0 } } attributes { key: "connection.sent.bytes_total" value { int64_value: 0 } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "destination.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "destination.port" value { int64_value: 8080 } } attributes { key: "destination.uid" value { string_value: "pod1.ns2" } } attributes { key: "connection.filter_state" value { bytes_value: "aeiou" } } )"; const char kReportAttributes[] = R"( attributes { key: "connection.event" value { string_value: "close" } } attributes { key: "check.error_code" value { int64_value: 3 } } attributes { key: "check.error_message" value { string_value: "INVALID_ARGUMENT:Invalid argument" } } attributes { key: "connection.duration" value { duration_value { nanos: 4 } } } attributes { key: "connection.received.bytes" value { int64_value: 144 } } attributes { key: "connection.received.bytes_total" value { int64_value: 345 } } attributes { key: "connection.sent.bytes" value { int64_value: 274 } } attributes { key: "connection.sent.bytes_total" value { int64_value: 678 } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "destination.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "destination.port" value { int64_value: 8080 } } attributes { key: "destination.uid" value { string_value: "pod1.ns2" } } attributes { key: "connection.filter_state" value { bytes_value: "aeiou" } } )"; const char kDeltaOneReportAttributes[] = R"( attributes { key: "connection.event" value { string_value: "continue" } } attributes { key: "connection.received.bytes" value { int64_value: 100 } } attributes { key: "connection.sent.bytes" value { int64_value: 200 } } attributes { key: "connection.received.bytes_total" value { int64_value: 100 } } attributes { key: "connection.sent.bytes_total" value { int64_value: 200 } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "destination.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "destination.port" value { int64_value: 8080 } } attributes { key: "destination.uid" value { string_value: "pod1.ns2" } } attributes { key: "connection.filter_state" value { bytes_value: "aeiou" } } )"; const char kDeltaTwoReportAttributes[] = R"( attributes { key: "connection.event" value { string_value: "continue" } } attributes { key: "connection.received.bytes" value { int64_value: 101 } } attributes { key: "connection.sent.bytes" value { int64_value: 204 } } attributes { key: "connection.received.bytes_total" value { int64_value: 201 } } attributes { key: "connection.sent.bytes_total" value { int64_value: 404 } } attributes { key: "context.time" value { timestamp_value { } } } attributes { key: "destination.ip" value { bytes_value: "1.2.3.4" } } attributes { key: "destination.port" value { int64_value: 8080 } } attributes { key: "destination.uid" value { string_value: "pod1.ns2" } } attributes { key: "connection.filter_state" value { bytes_value: "aeiou" } } )"; void ClearContextTime(RequestContext* request) { // Override timestamp with - utils::AttributesBuilder builder(request->attributes); std::chrono::time_point<std::chrono::system_clock> time0; builder.AddTimestamp(utils::AttributeName::kContextTime, time0); } TEST(AttributesBuilderTest, TestCheckAttributes) { ::testing::NiceMock<MockCheckData> mock_data; EXPECT_CALL(mock_data, GetSourceIpPort(_, _)) .WillOnce(Invoke([](std::string* ip, int* port) -> bool { *ip = "1.2.3.4"; *port = 8080; return true; })); EXPECT_CALL(mock_data, IsMutualTLS()).WillOnce(Invoke([]() -> bool { return true; })); EXPECT_CALL(mock_data, GetPrincipal(_, _)) .WillRepeatedly(Invoke([](bool peer, std::string* user) -> bool { if (peer) { *user = "cluster.local/sa/test_user/ns/ns_ns/"; } else { *user = "destination_user"; } return true; })); EXPECT_CALL(mock_data, GetConnectionId()).WillOnce(Return("1234-5")); EXPECT_CALL(mock_data, GetRequestedServerName(_)) .WillOnce(Invoke([](std::string* name) -> bool { *name = "www.google.com"; return true; })); RequestContext request; AttributesBuilder builder(&request); builder.ExtractCheckAttributes(&mock_data); ClearContextTime(&request); std::string out_str; TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; ::istio::mixer::v1::Attributes expected_attributes; ASSERT_TRUE( TextFormat::ParseFromString(kCheckAttributes, &expected_attributes)); EXPECT_TRUE( MessageDifferencer::Equals(*request.attributes, expected_attributes)); } TEST(AttributesBuilderTest, TestReportAttributes) { ::testing::NiceMock<MockReportData> mock_data; EXPECT_CALL(mock_data, GetDestinationIpPort(_, _)) .Times(4) .WillRepeatedly(Invoke([](std::string* ip, int* port) -> bool { *ip = "1.2.3.4"; *port = 8080; return true; })); EXPECT_CALL(mock_data, GetDestinationUID(_)) .Times(4) .WillRepeatedly(Invoke([](std::string* uid) -> bool { *uid = "pod1.ns2"; return true; })); EXPECT_CALL(mock_data, GetDynamicFilterState(_)) .Times(4) .WillRepeatedly(Invoke([](std::string* filter_state) -> bool { *filter_state = "aeiou"; return true; })); EXPECT_CALL(mock_data, GetReportInfo(_)) .Times(4) .WillOnce(Invoke([](ReportData::ReportInfo* info) { info->received_bytes = 0; info->send_bytes = 0; info->duration = std::chrono::nanoseconds(1); })) .WillOnce(Invoke([](ReportData::ReportInfo* info) { info->received_bytes = 100; info->send_bytes = 200; info->duration = std::chrono::nanoseconds(2); })) .WillOnce(Invoke([](ReportData::ReportInfo* info) { info->received_bytes = 201; info->send_bytes = 404; info->duration = std::chrono::nanoseconds(3); })) .WillOnce(Invoke([](ReportData::ReportInfo* info) { info->received_bytes = 345; info->send_bytes = 678; info->duration = std::chrono::nanoseconds(4); })); RequestContext request; request.check_status = ::google::protobuf::util::Status( ::google::protobuf::util::error::INVALID_ARGUMENT, "Invalid argument"); AttributesBuilder builder(&request); ReportData::ReportInfo last_report_info{0ULL, 0ULL, std::chrono::nanoseconds::zero()}; // Verify first open report builder.ExtractReportAttributes(&mock_data, ReportData::ConnectionEvent::OPEN, &last_report_info); ClearContextTime(&request); std::string out_str; TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; ::istio::mixer::v1::Attributes expected_open_attributes; ASSERT_TRUE(TextFormat::ParseFromString(kFirstReportAttributes, &expected_open_attributes)); EXPECT_TRUE(MessageDifferencer::Equals(*request.attributes, expected_open_attributes)); EXPECT_EQ(0, last_report_info.received_bytes); EXPECT_EQ(0, last_report_info.send_bytes); // Verify delta one report builder.ExtractReportAttributes( &mock_data, ReportData::ConnectionEvent::CONTINUE, &last_report_info); ClearContextTime(&request); TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; ::istio::mixer::v1::Attributes expected_delta_attributes; ASSERT_TRUE(TextFormat::ParseFromString(kDeltaOneReportAttributes, &expected_delta_attributes)); EXPECT_TRUE(MessageDifferencer::Equals(*request.attributes, expected_delta_attributes)); EXPECT_EQ(100, last_report_info.received_bytes); EXPECT_EQ(200, last_report_info.send_bytes); // Verify delta two report builder.ExtractReportAttributes( &mock_data, ReportData::ConnectionEvent::CONTINUE, &last_report_info); ClearContextTime(&request); out_str.clear(); TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; expected_delta_attributes.Clear(); ASSERT_TRUE(TextFormat::ParseFromString(kDeltaTwoReportAttributes, &expected_delta_attributes)); EXPECT_TRUE(MessageDifferencer::Equals(*request.attributes, expected_delta_attributes)); EXPECT_EQ(201, last_report_info.received_bytes); EXPECT_EQ(404, last_report_info.send_bytes); // Verify final report builder.ExtractReportAttributes( &mock_data, ReportData::ConnectionEvent::CLOSE, &last_report_info); ClearContextTime(&request); out_str.clear(); TextFormat::PrintToString(*request.attributes, &out_str); GOOGLE_LOG(INFO) << "===" << out_str << "==="; ::istio::mixer::v1::Attributes expected_final_attributes; ASSERT_TRUE(TextFormat::ParseFromString(kReportAttributes, &expected_final_attributes)); EXPECT_TRUE(MessageDifferencer::Equals(*request.attributes, expected_final_attributes)); } } // namespace } // namespace tcp } // namespace control } // namespace istio <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Petar Perisin. ** Contact: [email protected] ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "gerritpushdialog.h" #include "ui_gerritpushdialog.h" #include "branchcombobox.h" #include "../gitplugin.h" #include "../gitclient.h" #include <QDateTime> #include <QDir> #include <QPushButton> #include <QRegExpValidator> using namespace Git::Internal; namespace Gerrit { namespace Internal { class PushItemDelegate : public IconItemDelegate { public: PushItemDelegate(LogChangeWidget *widget) : IconItemDelegate(widget, QLatin1String(":/git/images/arrowup.png")) { } protected: bool hasIcon(int row) const { return row >= currentRow(); } }; QString GerritPushDialog::determineRemoteBranch() { const QString earliestCommit = m_ui->commitView->earliestCommit(); QString output; QString error; QStringList args; args << QLatin1String("-r") << QLatin1String("--contains") << earliestCommit + QLatin1Char('^'); if (!m_client->synchronousBranchCmd(m_workingDir, args, &output, &error)) return QString(); const QString head = QLatin1String("/HEAD"); QStringList refs = output.split(QLatin1Char('\n')); QString localBranch = m_ui->localBranchComboBox->currentText(); if (localBranch == QLatin1String("HEAD")) localBranch.clear(); const QString remoteTrackingBranch = m_client->synchronousTrackingBranch(m_workingDir, localBranch); QString remoteBranch; foreach (const QString &reference, refs) { const QString ref = reference.trimmed(); if (ref.contains(head) || ref.isEmpty()) continue; if (remoteBranch.isEmpty()) remoteBranch = ref; // Prefer remote tracking branch if it exists and contains the latest remote commit if (ref == remoteTrackingBranch) return ref; } return remoteBranch; } void GerritPushDialog::initRemoteBranches() { QString output; QStringList args; const QString head = QLatin1String("/HEAD"); QString remotesPrefix(QLatin1String("refs/remotes/")); args << QLatin1String("--format=%(refname)\t%(committerdate:raw)") << remotesPrefix; if (!m_client->synchronousForEachRefCmd(m_workingDir, args, &output)) return; const QStringList refs = output.split(QLatin1String("\n")); foreach (const QString &reference, refs) { QStringList entries = reference.split(QLatin1Char('\t')); if (entries.count() < 2 || entries.first().endsWith(head)) continue; const QString ref = entries.at(0).mid(remotesPrefix.size()); int refBranchIndex = ref.indexOf(QLatin1Char('/')); int timeT = entries.at(1).left(entries.at(1).indexOf(QLatin1Char(' '))).toInt(); BranchDate bd(ref.mid(refBranchIndex + 1), QDateTime::fromTime_t(timeT).date()); m_remoteBranches.insertMulti(ref.left(refBranchIndex), bd); } const QString remoteBranch = determineRemoteBranch(); if (!remoteBranch.isEmpty()) m_suggestedRemoteBranch = remoteBranch.mid(remoteBranch.indexOf(QLatin1Char('/')) + 1); QStringList remotes = m_remoteBranches.keys(); remotes.removeDuplicates(); m_ui->remoteComboBox->addItems(remotes); if (!m_suggestedRemoteBranch.isEmpty()) { int index = m_ui->remoteComboBox->findText(m_suggestedRemoteBranch); if (index != -1) m_ui->remoteComboBox->setCurrentIndex(index); } } GerritPushDialog::GerritPushDialog(const QString &workingDir, const QString &reviewerList, QWidget *parent) : QDialog(parent), m_workingDir(workingDir), m_ui(new Ui::GerritPushDialog), m_valid(false) { m_client = GitPlugin::instance()->gitClient(); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); m_ui->setupUi(this); m_ui->repositoryLabel->setText(tr("<b>Local repository:</b> %1").arg( QDir::toNativeSeparators(workingDir))); PushItemDelegate *delegate = new PushItemDelegate(m_ui->commitView); delegate->setParent(this); initRemoteBranches(); const int remoteCount = m_ui->remoteComboBox->count(); if (remoteCount < 1) { return; } else if (remoteCount == 1) { m_ui->remoteLabel->hide(); m_ui->remoteComboBox->hide(); } else { connect(m_ui->remoteComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setRemoteBranches())); } m_ui->localBranchComboBox->init(workingDir); connect(m_ui->localBranchComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCommits(int))); connect(m_ui->targetBranchComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setChangeRange())); setRemoteBranches(); m_ui->reviewersLineEdit->setText(reviewerList); m_ui->topicLineEdit->setValidator(new QRegExpValidator(QRegExp(QLatin1String("^\\S+$")), this)); updateCommits(m_ui->localBranchComboBox->currentIndex()); m_valid = true; } GerritPushDialog::~GerritPushDialog() { delete m_ui; } QString GerritPushDialog::selectedCommit() const { return m_ui->commitView->commit(); } QString GerritPushDialog::calculateChangeRange(const QString &branch) { QString remote = selectedRemoteName(); remote += QLatin1Char('/'); remote += selectedRemoteBranchName(); QStringList args(remote + QLatin1String("..") + branch); args << QLatin1String("--count"); QString number; if (!m_client->synchronousRevListCmd(m_workingDir, args, &number)) reject(); number.chop(1); return number; } void GerritPushDialog::setChangeRange() { if (m_ui->targetBranchComboBox->itemData(m_ui->targetBranchComboBox->currentIndex()) == 1) { setRemoteBranches(true); return; } QString remote = selectedRemoteName(); remote += QLatin1Char('/'); remote += selectedRemoteBranchName(); const QString branch = m_ui->localBranchComboBox->currentText(); m_ui->infoLabel->setText(tr("Number of commits between %1 and %2: %3") .arg(branch) .arg(remote) .arg(calculateChangeRange(branch))); } bool GerritPushDialog::valid() const { return m_valid; } void GerritPushDialog::setRemoteBranches(bool includeOld) { bool blocked = m_ui->targetBranchComboBox->blockSignals(true); m_ui->targetBranchComboBox->clear(); int i = 0; bool excluded = false; for (RemoteBranchesMap::const_iterator it = m_remoteBranches.constBegin(), end = m_remoteBranches.constEnd(); it != end; ++it) { if (it.key() == selectedRemoteName()) { const BranchDate &bd = it.value(); const bool isSuggested = bd.first == m_suggestedRemoteBranch; if (includeOld || bd.second.daysTo(QDate::currentDate()) <= 60 || isSuggested) { m_ui->targetBranchComboBox->addItem(bd.first); if (isSuggested) m_ui->targetBranchComboBox->setCurrentIndex(i); ++i; } else { excluded = true; } } } if (excluded) m_ui->targetBranchComboBox->addItem(tr("... Include older branches ..."), 1); setChangeRange(); m_ui->targetBranchComboBox->blockSignals(blocked); } void GerritPushDialog::updateCommits(int index) { const QString branch = m_ui->localBranchComboBox->itemText(index); const bool hasLocalCommits = m_ui->commitView->init(m_workingDir, branch, LogChangeWidget::Silent); m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(hasLocalCommits); setChangeRange(); } QString GerritPushDialog::selectedRemoteName() const { return m_ui->remoteComboBox->currentText(); } QString GerritPushDialog::selectedRemoteBranchName() const { return m_ui->targetBranchComboBox->currentText(); } QString GerritPushDialog::selectedPushType() const { return m_ui->draftCheckBox->isChecked() ? QLatin1String("drafts") : QLatin1String("for"); } QString GerritPushDialog::selectedTopic() const { return m_ui->topicLineEdit->text().trimmed(); } QString GerritPushDialog::reviewers() const { return m_ui->reviewersLineEdit->text(); } } // namespace Internal } // namespace Gerrit <commit_msg>Git: Fix target branch auto-detection in Push to Gerrit<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Petar Perisin. ** Contact: [email protected] ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "gerritpushdialog.h" #include "ui_gerritpushdialog.h" #include "branchcombobox.h" #include "../gitplugin.h" #include "../gitclient.h" #include <QDateTime> #include <QDir> #include <QPushButton> #include <QRegExpValidator> using namespace Git::Internal; namespace Gerrit { namespace Internal { class PushItemDelegate : public IconItemDelegate { public: PushItemDelegate(LogChangeWidget *widget) : IconItemDelegate(widget, QLatin1String(":/git/images/arrowup.png")) { } protected: bool hasIcon(int row) const { return row >= currentRow(); } }; QString GerritPushDialog::determineRemoteBranch() { const QString earliestCommit = m_ui->commitView->earliestCommit(); QString output; QString error; QStringList args; args << QLatin1String("-r") << QLatin1String("--contains") << earliestCommit + QLatin1Char('^'); if (!m_client->synchronousBranchCmd(m_workingDir, args, &output, &error)) return QString(); const QString head = QLatin1String("/HEAD"); QStringList refs = output.split(QLatin1Char('\n')); QString localBranch = m_ui->localBranchComboBox->currentText(); if (localBranch == QLatin1String("HEAD")) localBranch.clear(); const QString remoteTrackingBranch = m_client->synchronousTrackingBranch(m_workingDir, localBranch); QString remoteBranch; foreach (const QString &reference, refs) { const QString ref = reference.trimmed(); if (ref.contains(head) || ref.isEmpty()) continue; if (remoteBranch.isEmpty()) remoteBranch = ref; // Prefer remote tracking branch if it exists and contains the latest remote commit if (ref == remoteTrackingBranch) return ref; } return remoteBranch; } void GerritPushDialog::initRemoteBranches() { QString output; QStringList args; const QString head = QLatin1String("/HEAD"); QString remotesPrefix(QLatin1String("refs/remotes/")); args << QLatin1String("--format=%(refname)\t%(committerdate:raw)") << remotesPrefix; if (!m_client->synchronousForEachRefCmd(m_workingDir, args, &output)) return; const QStringList refs = output.split(QLatin1String("\n")); foreach (const QString &reference, refs) { QStringList entries = reference.split(QLatin1Char('\t')); if (entries.count() < 2 || entries.first().endsWith(head)) continue; const QString ref = entries.at(0).mid(remotesPrefix.size()); int refBranchIndex = ref.indexOf(QLatin1Char('/')); int timeT = entries.at(1).left(entries.at(1).indexOf(QLatin1Char(' '))).toInt(); BranchDate bd(ref.mid(refBranchIndex + 1), QDateTime::fromTime_t(timeT).date()); m_remoteBranches.insertMulti(ref.left(refBranchIndex), bd); } QStringList remotes = m_remoteBranches.keys(); remotes.removeDuplicates(); m_ui->remoteComboBox->addItems(remotes); const int remoteCount = m_ui->remoteComboBox->count(); if (remoteCount < 1) { return; } else if (remoteCount == 1) { m_ui->remoteLabel->hide(); m_ui->remoteComboBox->hide(); } else { connect(m_ui->remoteComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setRemoteBranches())); } } GerritPushDialog::GerritPushDialog(const QString &workingDir, const QString &reviewerList, QWidget *parent) : QDialog(parent), m_workingDir(workingDir), m_ui(new Ui::GerritPushDialog), m_valid(false) { m_client = GitPlugin::instance()->gitClient(); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); m_ui->setupUi(this); m_ui->repositoryLabel->setText(tr("<b>Local repository:</b> %1").arg( QDir::toNativeSeparators(workingDir))); PushItemDelegate *delegate = new PushItemDelegate(m_ui->commitView); delegate->setParent(this); initRemoteBranches(); if (m_ui->remoteComboBox->count() < 1) return; m_ui->localBranchComboBox->init(workingDir); connect(m_ui->localBranchComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCommits(int))); connect(m_ui->targetBranchComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setChangeRange())); updateCommits(m_ui->localBranchComboBox->currentIndex()); setRemoteBranches(); m_ui->reviewersLineEdit->setText(reviewerList); m_ui->topicLineEdit->setValidator(new QRegExpValidator(QRegExp(QLatin1String("^\\S+$")), this)); m_valid = true; } GerritPushDialog::~GerritPushDialog() { delete m_ui; } QString GerritPushDialog::selectedCommit() const { return m_ui->commitView->commit(); } QString GerritPushDialog::calculateChangeRange(const QString &branch) { QString remote = selectedRemoteName(); remote += QLatin1Char('/'); remote += selectedRemoteBranchName(); QStringList args(remote + QLatin1String("..") + branch); args << QLatin1String("--count"); QString number; if (!m_client->synchronousRevListCmd(m_workingDir, args, &number)) reject(); number.chop(1); return number; } void GerritPushDialog::setChangeRange() { if (m_ui->targetBranchComboBox->itemData(m_ui->targetBranchComboBox->currentIndex()) == 1) { setRemoteBranches(true); return; } QString remote = selectedRemoteName(); remote += QLatin1Char('/'); remote += selectedRemoteBranchName(); const QString branch = m_ui->localBranchComboBox->currentText(); m_ui->infoLabel->setText(tr("Number of commits between %1 and %2: %3") .arg(branch) .arg(remote) .arg(calculateChangeRange(branch))); } bool GerritPushDialog::valid() const { return m_valid; } void GerritPushDialog::setRemoteBranches(bool includeOld) { bool blocked = m_ui->targetBranchComboBox->blockSignals(true); m_ui->targetBranchComboBox->clear(); int i = 0; bool excluded = false; for (RemoteBranchesMap::const_iterator it = m_remoteBranches.constBegin(), end = m_remoteBranches.constEnd(); it != end; ++it) { if (it.key() == selectedRemoteName()) { const BranchDate &bd = it.value(); const bool isSuggested = bd.first == m_suggestedRemoteBranch; if (includeOld || bd.second.daysTo(QDate::currentDate()) <= 60 || isSuggested) { m_ui->targetBranchComboBox->addItem(bd.first); if (isSuggested) m_ui->targetBranchComboBox->setCurrentIndex(i); ++i; } else { excluded = true; } } } if (excluded) m_ui->targetBranchComboBox->addItem(tr("... Include older branches ..."), 1); setChangeRange(); m_ui->targetBranchComboBox->blockSignals(blocked); } void GerritPushDialog::updateCommits(int index) { const QString branch = m_ui->localBranchComboBox->itemText(index); const bool hasLocalCommits = m_ui->commitView->init(m_workingDir, branch, LogChangeWidget::Silent); const QString remoteBranch = determineRemoteBranch(); if (!remoteBranch.isEmpty()) { const int slash = remoteBranch.indexOf(QLatin1Char('/')); m_suggestedRemoteBranch = remoteBranch.mid(slash + 1); const QString remote = remoteBranch.left(slash); const int index = m_ui->remoteComboBox->findText(remote); if (index != -1 && index != m_ui->remoteComboBox->currentIndex()) m_ui->remoteComboBox->setCurrentIndex(index); else setRemoteBranches(); } m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(hasLocalCommits); } QString GerritPushDialog::selectedRemoteName() const { return m_ui->remoteComboBox->currentText(); } QString GerritPushDialog::selectedRemoteBranchName() const { return m_ui->targetBranchComboBox->currentText(); } QString GerritPushDialog::selectedPushType() const { return m_ui->draftCheckBox->isChecked() ? QLatin1String("drafts") : QLatin1String("for"); } QString GerritPushDialog::selectedTopic() const { return m_ui->topicLineEdit->text().trimmed(); } QString GerritPushDialog::reviewers() const { return m_ui->reviewersLineEdit->text(); } } // namespace Internal } // namespace Gerrit <|endoftext|>
<commit_before>/************************************************************************** ** ** Copyright (C) 2011 - 2013 Research In Motion ** ** Contact: Research In Motion ([email protected]) ** Contact: KDAB ([email protected]) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "blackberryconfiguration.h" #include "blackberryqtversion.h" #include "qnxutils.h" #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/kitmanager.h> #include <projectexplorer/kitinformation.h> #include <projectexplorer/toolchainmanager.h> #include <qtsupport/baseqtversion.h> #include <qtsupport/qtversionmanager.h> #include <qtsupport/qtkitinformation.h> #include <qt4projectmanager/qmakekitinformation.h> #include <debugger/debuggerkitinformation.h> #include <QFileInfo> #include <QDir> #include <QMessageBox> using namespace ProjectExplorer; using namespace QtSupport; using namespace Utils; namespace Qnx { namespace Internal { BlackBerryConfiguration::BlackBerryConfiguration(const FileName &ndkEnvFile, bool isAutoDetected, const QString &displayName) { Q_ASSERT(!QFileInfo(ndkEnvFile.toString()).isDir()); m_ndkEnvFile = ndkEnvFile; m_isAutoDetected = isAutoDetected; QString ndkPath = ndkEnvFile.parentDir().toString(); m_displayName = displayName.isEmpty() ? ndkPath.split(QDir::separator()).last() : displayName; m_qnxEnv = QnxUtils::parseEnvironmentFile(m_ndkEnvFile.toString()); QString ndkTarget = m_qnxEnv.value(QLatin1String("QNX_TARGET")); QString sep = QString::fromLatin1("%1qnx6").arg(QDir::separator()); m_targetName = ndkTarget.split(sep).first().split(QDir::separator()).last(); if (QDir(ndkTarget).exists()) m_sysRoot = FileName::fromString(ndkTarget); QString qnxHost = m_qnxEnv.value(QLatin1String("QNX_HOST")); FileName qmake4Path = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/qmake"))); FileName qmake5Path = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/qt5/qmake"))); FileName gccPath = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/qcc"))); FileName deviceGdbPath = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/ntoarm-gdb"))); FileName simulatorGdbPath = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/ntox86-gdb"))); if (qmake4Path.toFileInfo().exists()) m_qmake4BinaryFile = qmake4Path; if (qmake5Path.toFileInfo().exists()) m_qmake5BinaryFile = qmake5Path; if (gccPath.toFileInfo().exists()) m_gccCompiler = gccPath; if (deviceGdbPath.toFileInfo().exists()) m_deviceDebuger = deviceGdbPath; if (simulatorGdbPath.toFileInfo().exists()) m_simulatorDebuger = simulatorGdbPath; } QString BlackBerryConfiguration::ndkPath() const { return m_ndkEnvFile.parentDir().toString(); } QString BlackBerryConfiguration::displayName() const { return m_displayName; } QString BlackBerryConfiguration::targetName() const { return m_targetName; } bool BlackBerryConfiguration::isAutoDetected() const { return m_isAutoDetected; } bool BlackBerryConfiguration::isActive() const { BaseQtVersion *qt4Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake4BinaryFile); BaseQtVersion *qt5Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake5BinaryFile); return (qt4Version || qt5Version); } bool BlackBerryConfiguration::isValid() const { return !((m_qmake4BinaryFile.isEmpty() && m_qmake5BinaryFile.isEmpty()) || m_gccCompiler.isEmpty() || m_deviceDebuger.isEmpty() || m_simulatorDebuger.isEmpty()); } FileName BlackBerryConfiguration::ndkEnvFile() const { return m_ndkEnvFile; } FileName BlackBerryConfiguration::qmake4BinaryFile() const { return m_qmake4BinaryFile; } FileName BlackBerryConfiguration::qmake5BinaryFile() const { return m_qmake5BinaryFile; } FileName BlackBerryConfiguration::gccCompiler() const { return m_gccCompiler; } FileName BlackBerryConfiguration::deviceDebuger() const { return m_deviceDebuger; } FileName BlackBerryConfiguration::simulatorDebuger() const { return m_simulatorDebuger; } FileName BlackBerryConfiguration::sysRoot() const { return m_sysRoot; } QMultiMap<QString, QString> BlackBerryConfiguration::qnxEnv() const { return m_qnxEnv; } void BlackBerryConfiguration::setupConfigurationPerQtVersion(const FileName &qmakePath, GccToolChain *tc) { if (qmakePath.isEmpty() || !tc) return; BaseQtVersion *qtVersion = createQtVersion(qmakePath); Kit *deviceKit = createKit(ArmLeV7, qtVersion, tc); Kit *simulatorKit = createKit(X86, qtVersion, tc); if (qtVersion && tc && deviceKit && simulatorKit) { if (!qtVersion->qtAbis().isEmpty()) tc->setTargetAbi(qtVersion->qtAbis().first()); // register QtVersionManager::addVersion(qtVersion); ToolChainManager::registerToolChain(tc); KitManager::registerKit(deviceKit); KitManager::registerKit(simulatorKit); } } BaseQtVersion *BlackBerryConfiguration::createQtVersion(const FileName &qmakePath) { if (qmakePath.isEmpty()) return 0; QString cpuDir = m_qnxEnv.value(QLatin1String("CPUVARDIR")); BaseQtVersion *version = QtVersionManager::qtVersionForQMakeBinary(qmakePath); if (version) { if (!m_isAutoDetected) QMessageBox::warning(0, tr("Qt Version Already Known"), tr("This Qt version was already registered."), QMessageBox::Ok); return version; } version = new BlackBerryQtVersion(QnxUtils::cpudirToArch(cpuDir), qmakePath, m_isAutoDetected, QString(), m_ndkEnvFile.toString()); if (!version) { if (!m_isAutoDetected) QMessageBox::warning(0, tr("Invalid Qt Version"), tr("Unable to add BlackBerry Qt version."), QMessageBox::Ok); return 0; } version->setDisplayName(QString::fromLatin1("Qt %1 BlackBerry 10 (%2)").arg(version->qtVersionString(), m_targetName)); return version; } GccToolChain *BlackBerryConfiguration::createGccToolChain() { if ((m_qmake4BinaryFile.isEmpty() && m_qmake5BinaryFile.isEmpty()) || m_gccCompiler.isEmpty()) return 0; foreach (ToolChain *tc, ToolChainManager::toolChains()) { if (tc->compilerCommand() == m_gccCompiler) { if (!m_isAutoDetected) QMessageBox::warning(0, tr("Compiler Already Known"), tr("This compiler was already registered."), QMessageBox::Ok); return dynamic_cast<GccToolChain *>(tc); } } GccToolChain* tc = new GccToolChain(QLatin1String(ProjectExplorer::Constants::GCC_TOOLCHAIN_ID), m_isAutoDetected ? ToolChain::AutoDetection : ToolChain::ManualDetection); tc->setDisplayName(QString::fromLatin1("GCC BlackBerry 10 (%1)").arg(m_targetName)); tc->setCompilerCommand(m_gccCompiler); return tc; } Kit *BlackBerryConfiguration::createKit(QnxArchitecture arch, BaseQtVersion *qtVersion, GccToolChain *tc) { if (!qtVersion || !tc || m_targetName.isEmpty()) return 0; // Check if an identical kit already exists foreach (Kit *kit, KitManager::kits()) { if (QtKitInformation::qtVersion(kit) == qtVersion && ToolChainKitInformation::toolChain(kit) == tc && DeviceTypeKitInformation::deviceTypeId(kit) == Constants::QNX_BB_OS_TYPE && SysRootKitInformation::sysRoot(kit) == m_sysRoot) { if ((arch == X86 && Qt4ProjectManager::QmakeKitInformation::mkspec(kit).toString() == QString::fromLatin1("blackberry-x86-qcc") && Debugger::DebuggerKitInformation::debuggerCommand(kit) == m_simulatorDebuger) || (arch == ArmLeV7 && Debugger::DebuggerKitInformation::debuggerCommand(kit) == m_deviceDebuger)) { if (!m_isAutoDetected) QMessageBox::warning(0, tr("Kit Already Known"), tr("This kit was already registered."), QMessageBox::Ok); setSticky(kit); return kit; } } } Kit *kit = new Kit; QtKitInformation::setQtVersion(kit, qtVersion); ToolChainKitInformation::setToolChain(kit, tc); if (arch == X86) { Debugger::DebuggerKitInformation::setDebugger(kit, Debugger::GdbEngineType, m_simulatorDebuger); Qt4ProjectManager::QmakeKitInformation::setMkspec(kit, FileName::fromString(QString::fromLatin1("blackberry-x86-qcc"))); // TODO: Check if the name already exists(?) kit->setDisplayName(tr("BlackBerry 10 (%1 - %2) - Simulator").arg(qtVersion->qtVersionString(), m_targetName)); } else { Debugger::DebuggerKitInformation::setDebugger(kit, Debugger::GdbEngineType, m_deviceDebuger); kit->setDisplayName(tr("BlackBerry 10 (%1 - %2)").arg(qtVersion->qtVersionString(), m_targetName)); } kit->setAutoDetected(m_isAutoDetected); kit->setIconPath(FileName::fromString(QLatin1String(Constants::QNX_BB_CATEGORY_ICON))); setSticky(kit); DeviceTypeKitInformation::setDeviceTypeId(kit, Constants::QNX_BB_OS_TYPE); SysRootKitInformation::setSysRoot(kit, m_sysRoot); return kit; } void BlackBerryConfiguration::setSticky(Kit *kit) { kit->setSticky(QtKitInformation::id(), true); kit->setSticky(ToolChainKitInformation::id(), true); kit->setSticky(DeviceTypeKitInformation::id(), true); kit->setSticky(SysRootKitInformation::id(), true); kit->setSticky(Debugger::DebuggerKitInformation::id(), true); kit->setSticky(Qt4ProjectManager::QmakeKitInformation::id(), true); } bool BlackBerryConfiguration::activate() { if (!isValid()) { if (m_isAutoDetected) return false; QString errorMessage = tr("The following errors occurred while activating Target: %1").arg(m_targetName); if (m_qmake4BinaryFile.isEmpty() && m_qmake5BinaryFile.isEmpty()) errorMessage += QLatin1Char('\n') + tr("- No Qt version found."); if (m_gccCompiler.isEmpty()) errorMessage += QLatin1Char('\n') + tr("- No GCC compiler found."); if (m_deviceDebuger.isEmpty()) errorMessage += QLatin1Char('\n') + tr("- No GDB debugger found for BB10 Device."); if (!m_simulatorDebuger.isEmpty()) errorMessage += QLatin1Char('\n') + tr("- No GDB debugger found for BB10 Simulator."); QMessageBox::warning(0, tr("Cannot Set up BB10 Configuration"), errorMessage, QMessageBox::Ok); return false; } if (isActive() && !m_isAutoDetected) return true; GccToolChain *tc = createGccToolChain(); if (!m_qmake4BinaryFile.isEmpty()) setupConfigurationPerQtVersion(m_qmake4BinaryFile, tc); if (!m_qmake5BinaryFile.isEmpty()) setupConfigurationPerQtVersion(m_qmake5BinaryFile, tc); return true; } void BlackBerryConfiguration::deactivate() { BaseQtVersion *qt4Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake4BinaryFile); BaseQtVersion *qt5Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake5BinaryFile); if (qt4Version || qt5Version) { foreach (Kit *kit, KitManager::kits()) { if (qt4Version && qt4Version == QtKitInformation::qtVersion(kit)) KitManager::deregisterKit(kit); else if (qt5Version && qt5Version == QtKitInformation::qtVersion(kit)) KitManager::deregisterKit(kit); } if (qt4Version) QtVersionManager::removeVersion(qt4Version); if (qt5Version) QtVersionManager::removeVersion(qt5Version); } foreach (ToolChain *tc, ToolChainManager::toolChains()) if (tc->compilerCommand() == m_gccCompiler) ToolChainManager::deregisterToolChain(tc); } } // namespace Internal } // namespace Qnx <commit_msg>Qnx: auto-detected BlackBerry kits have mutable Device field<commit_after>/************************************************************************** ** ** Copyright (C) 2011 - 2013 Research In Motion ** ** Contact: Research In Motion ([email protected]) ** Contact: KDAB ([email protected]) ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "blackberryconfiguration.h" #include "blackberryqtversion.h" #include "qnxutils.h" #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/kitmanager.h> #include <projectexplorer/kitinformation.h> #include <projectexplorer/toolchainmanager.h> #include <qtsupport/baseqtversion.h> #include <qtsupport/qtversionmanager.h> #include <qtsupport/qtkitinformation.h> #include <qt4projectmanager/qmakekitinformation.h> #include <debugger/debuggerkitinformation.h> #include <QFileInfo> #include <QDir> #include <QMessageBox> using namespace ProjectExplorer; using namespace QtSupport; using namespace Utils; namespace Qnx { namespace Internal { BlackBerryConfiguration::BlackBerryConfiguration(const FileName &ndkEnvFile, bool isAutoDetected, const QString &displayName) { Q_ASSERT(!QFileInfo(ndkEnvFile.toString()).isDir()); m_ndkEnvFile = ndkEnvFile; m_isAutoDetected = isAutoDetected; QString ndkPath = ndkEnvFile.parentDir().toString(); m_displayName = displayName.isEmpty() ? ndkPath.split(QDir::separator()).last() : displayName; m_qnxEnv = QnxUtils::parseEnvironmentFile(m_ndkEnvFile.toString()); QString ndkTarget = m_qnxEnv.value(QLatin1String("QNX_TARGET")); QString sep = QString::fromLatin1("%1qnx6").arg(QDir::separator()); m_targetName = ndkTarget.split(sep).first().split(QDir::separator()).last(); if (QDir(ndkTarget).exists()) m_sysRoot = FileName::fromString(ndkTarget); QString qnxHost = m_qnxEnv.value(QLatin1String("QNX_HOST")); FileName qmake4Path = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/qmake"))); FileName qmake5Path = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/qt5/qmake"))); FileName gccPath = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/qcc"))); FileName deviceGdbPath = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/ntoarm-gdb"))); FileName simulatorGdbPath = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/ntox86-gdb"))); if (qmake4Path.toFileInfo().exists()) m_qmake4BinaryFile = qmake4Path; if (qmake5Path.toFileInfo().exists()) m_qmake5BinaryFile = qmake5Path; if (gccPath.toFileInfo().exists()) m_gccCompiler = gccPath; if (deviceGdbPath.toFileInfo().exists()) m_deviceDebuger = deviceGdbPath; if (simulatorGdbPath.toFileInfo().exists()) m_simulatorDebuger = simulatorGdbPath; } QString BlackBerryConfiguration::ndkPath() const { return m_ndkEnvFile.parentDir().toString(); } QString BlackBerryConfiguration::displayName() const { return m_displayName; } QString BlackBerryConfiguration::targetName() const { return m_targetName; } bool BlackBerryConfiguration::isAutoDetected() const { return m_isAutoDetected; } bool BlackBerryConfiguration::isActive() const { BaseQtVersion *qt4Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake4BinaryFile); BaseQtVersion *qt5Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake5BinaryFile); return (qt4Version || qt5Version); } bool BlackBerryConfiguration::isValid() const { return !((m_qmake4BinaryFile.isEmpty() && m_qmake5BinaryFile.isEmpty()) || m_gccCompiler.isEmpty() || m_deviceDebuger.isEmpty() || m_simulatorDebuger.isEmpty()); } FileName BlackBerryConfiguration::ndkEnvFile() const { return m_ndkEnvFile; } FileName BlackBerryConfiguration::qmake4BinaryFile() const { return m_qmake4BinaryFile; } FileName BlackBerryConfiguration::qmake5BinaryFile() const { return m_qmake5BinaryFile; } FileName BlackBerryConfiguration::gccCompiler() const { return m_gccCompiler; } FileName BlackBerryConfiguration::deviceDebuger() const { return m_deviceDebuger; } FileName BlackBerryConfiguration::simulatorDebuger() const { return m_simulatorDebuger; } FileName BlackBerryConfiguration::sysRoot() const { return m_sysRoot; } QMultiMap<QString, QString> BlackBerryConfiguration::qnxEnv() const { return m_qnxEnv; } void BlackBerryConfiguration::setupConfigurationPerQtVersion(const FileName &qmakePath, GccToolChain *tc) { if (qmakePath.isEmpty() || !tc) return; BaseQtVersion *qtVersion = createQtVersion(qmakePath); Kit *deviceKit = createKit(ArmLeV7, qtVersion, tc); Kit *simulatorKit = createKit(X86, qtVersion, tc); if (qtVersion && tc && deviceKit && simulatorKit) { if (!qtVersion->qtAbis().isEmpty()) tc->setTargetAbi(qtVersion->qtAbis().first()); // register QtVersionManager::addVersion(qtVersion); ToolChainManager::registerToolChain(tc); KitManager::registerKit(deviceKit); KitManager::registerKit(simulatorKit); } } BaseQtVersion *BlackBerryConfiguration::createQtVersion(const FileName &qmakePath) { if (qmakePath.isEmpty()) return 0; QString cpuDir = m_qnxEnv.value(QLatin1String("CPUVARDIR")); BaseQtVersion *version = QtVersionManager::qtVersionForQMakeBinary(qmakePath); if (version) { if (!m_isAutoDetected) QMessageBox::warning(0, tr("Qt Version Already Known"), tr("This Qt version was already registered."), QMessageBox::Ok); return version; } version = new BlackBerryQtVersion(QnxUtils::cpudirToArch(cpuDir), qmakePath, m_isAutoDetected, QString(), m_ndkEnvFile.toString()); if (!version) { if (!m_isAutoDetected) QMessageBox::warning(0, tr("Invalid Qt Version"), tr("Unable to add BlackBerry Qt version."), QMessageBox::Ok); return 0; } version->setDisplayName(QString::fromLatin1("Qt %1 BlackBerry 10 (%2)").arg(version->qtVersionString(), m_targetName)); return version; } GccToolChain *BlackBerryConfiguration::createGccToolChain() { if ((m_qmake4BinaryFile.isEmpty() && m_qmake5BinaryFile.isEmpty()) || m_gccCompiler.isEmpty()) return 0; foreach (ToolChain *tc, ToolChainManager::toolChains()) { if (tc->compilerCommand() == m_gccCompiler) { if (!m_isAutoDetected) QMessageBox::warning(0, tr("Compiler Already Known"), tr("This compiler was already registered."), QMessageBox::Ok); return dynamic_cast<GccToolChain *>(tc); } } GccToolChain* tc = new GccToolChain(QLatin1String(ProjectExplorer::Constants::GCC_TOOLCHAIN_ID), m_isAutoDetected ? ToolChain::AutoDetection : ToolChain::ManualDetection); tc->setDisplayName(QString::fromLatin1("GCC BlackBerry 10 (%1)").arg(m_targetName)); tc->setCompilerCommand(m_gccCompiler); return tc; } Kit *BlackBerryConfiguration::createKit(QnxArchitecture arch, BaseQtVersion *qtVersion, GccToolChain *tc) { if (!qtVersion || !tc || m_targetName.isEmpty()) return 0; // Check if an identical kit already exists foreach (Kit *kit, KitManager::kits()) { if (QtKitInformation::qtVersion(kit) == qtVersion && ToolChainKitInformation::toolChain(kit) == tc && DeviceTypeKitInformation::deviceTypeId(kit) == Constants::QNX_BB_OS_TYPE && SysRootKitInformation::sysRoot(kit) == m_sysRoot) { if ((arch == X86 && Qt4ProjectManager::QmakeKitInformation::mkspec(kit).toString() == QString::fromLatin1("blackberry-x86-qcc") && Debugger::DebuggerKitInformation::debuggerCommand(kit) == m_simulatorDebuger) || (arch == ArmLeV7 && Debugger::DebuggerKitInformation::debuggerCommand(kit) == m_deviceDebuger)) { if (!m_isAutoDetected) QMessageBox::warning(0, tr("Kit Already Known"), tr("This kit was already registered."), QMessageBox::Ok); setSticky(kit); return kit; } } } Kit *kit = new Kit; QtKitInformation::setQtVersion(kit, qtVersion); ToolChainKitInformation::setToolChain(kit, tc); if (arch == X86) { Debugger::DebuggerKitInformation::setDebugger(kit, Debugger::GdbEngineType, m_simulatorDebuger); Qt4ProjectManager::QmakeKitInformation::setMkspec(kit, FileName::fromString(QString::fromLatin1("blackberry-x86-qcc"))); // TODO: Check if the name already exists(?) kit->setDisplayName(tr("BlackBerry 10 (%1 - %2) - Simulator").arg(qtVersion->qtVersionString(), m_targetName)); } else { Debugger::DebuggerKitInformation::setDebugger(kit, Debugger::GdbEngineType, m_deviceDebuger); kit->setDisplayName(tr("BlackBerry 10 (%1 - %2)").arg(qtVersion->qtVersionString(), m_targetName)); } kit->setAutoDetected(m_isAutoDetected); kit->setIconPath(FileName::fromString(QLatin1String(Constants::QNX_BB_CATEGORY_ICON))); kit->setMutable(DeviceKitInformation::id(), true); setSticky(kit); DeviceTypeKitInformation::setDeviceTypeId(kit, Constants::QNX_BB_OS_TYPE); SysRootKitInformation::setSysRoot(kit, m_sysRoot); return kit; } void BlackBerryConfiguration::setSticky(Kit *kit) { kit->setSticky(QtKitInformation::id(), true); kit->setSticky(ToolChainKitInformation::id(), true); kit->setSticky(DeviceTypeKitInformation::id(), true); kit->setSticky(SysRootKitInformation::id(), true); kit->setSticky(Debugger::DebuggerKitInformation::id(), true); kit->setSticky(Qt4ProjectManager::QmakeKitInformation::id(), true); } bool BlackBerryConfiguration::activate() { if (!isValid()) { if (m_isAutoDetected) return false; QString errorMessage = tr("The following errors occurred while activating Target: %1").arg(m_targetName); if (m_qmake4BinaryFile.isEmpty() && m_qmake5BinaryFile.isEmpty()) errorMessage += QLatin1Char('\n') + tr("- No Qt version found."); if (m_gccCompiler.isEmpty()) errorMessage += QLatin1Char('\n') + tr("- No GCC compiler found."); if (m_deviceDebuger.isEmpty()) errorMessage += QLatin1Char('\n') + tr("- No GDB debugger found for BB10 Device."); if (!m_simulatorDebuger.isEmpty()) errorMessage += QLatin1Char('\n') + tr("- No GDB debugger found for BB10 Simulator."); QMessageBox::warning(0, tr("Cannot Set up BB10 Configuration"), errorMessage, QMessageBox::Ok); return false; } if (isActive() && !m_isAutoDetected) return true; GccToolChain *tc = createGccToolChain(); if (!m_qmake4BinaryFile.isEmpty()) setupConfigurationPerQtVersion(m_qmake4BinaryFile, tc); if (!m_qmake5BinaryFile.isEmpty()) setupConfigurationPerQtVersion(m_qmake5BinaryFile, tc); return true; } void BlackBerryConfiguration::deactivate() { BaseQtVersion *qt4Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake4BinaryFile); BaseQtVersion *qt5Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake5BinaryFile); if (qt4Version || qt5Version) { foreach (Kit *kit, KitManager::kits()) { if (qt4Version && qt4Version == QtKitInformation::qtVersion(kit)) KitManager::deregisterKit(kit); else if (qt5Version && qt5Version == QtKitInformation::qtVersion(kit)) KitManager::deregisterKit(kit); } if (qt4Version) QtVersionManager::removeVersion(qt4Version); if (qt5Version) QtVersionManager::removeVersion(qt5Version); } foreach (ToolChain *tc, ToolChainManager::toolChains()) if (tc->compilerCommand() == m_gccCompiler) ToolChainManager::deregisterToolChain(tc); } } // namespace Internal } // namespace Qnx <|endoftext|>
<commit_before>#include "TiltedTimeWindow.h" namespace Analytics { int TiltedTimeWindow::GranularityBucketCount[TTW_NUM_GRANULARITIES] = { 4, 24, 31, 12, 1 }; int TiltedTimeWindow::GranularityBucketOffset[TTW_NUM_GRANULARITIES] = { 0, 4, 28, 59, 71 }; char TiltedTimeWindow::GranularityChar[TTW_NUM_GRANULARITIES] = {'Q','H','D','M','Y' }; //-------------------------------------------------------------------------- // Public methods. TiltedTimeWindow::TiltedTimeWindow() { this->oldestBucketFilled = -1; this->lastUpdate = 0; for (int b = 0; b < TTW_NUM_BUCKETS; b++) this->buckets[b] = -1; for (int g = 0; g < TTW_NUM_GRANULARITIES; g++) this->capacityUsed[g] = 0; } void TiltedTimeWindow::appendQuarter(SupportCount supportCount, uint32_t updateID) { this->lastUpdate = updateID; store(GRANULARITY_QUARTER, supportCount); } void TiltedTimeWindow::dropTail(int start) { // Find the granularity to which it belongs and reset every // granularity along the way. Granularity g; for (g = (Granularity) (TTW_NUM_GRANULARITIES - 1); g >= 0; g = (Granularity) ((int) g - 1)) { if (start >= this->GranularityBucketOffset[g]) break; else this->reset(g); } // Now decide what to do with the granularity in which this tail // was started to be pruned. Reset the granularity starting at // the starting position of the tail pruning; this will // automatically reset the entire granularity when this is the // first bucket of the granularity. this->reset(g, start); } QVector<SupportCount> TiltedTimeWindow::getBuckets(int numBuckets) const { Q_ASSERT(numBuckets <= TTW_NUM_BUCKETS); QVector<SupportCount> v; for (int i = 0; i < numBuckets; i++) v.append(this->buckets[i]); return v; } //-------------------------------------------------------------------------- // Private methods. /** * Reset a granularity. Defaults to resetting the entire granularity, * but allows for a partial reset. * * @param granularity * The granularity that should be reset. * @param startBucket * When performing a partial reset, */ void TiltedTimeWindow::reset(Granularity granularity, int startBucket) { int offset = GranularityBucketOffset[granularity]; int count = GranularityBucketCount[granularity]; // Reset this granularity's buckets. memset(this->buckets + offset + startBucket, -1, (count - startBucket ) * sizeof(int)); // Update this granularity's used capacity.. this->capacityUsed[granularity] = startBucket; // Update oldestBucketFilled. if (this->oldestBucketFilled > offset + startBucket - 1) this->oldestBucketFilled = offset + startBucket - 1; } /** * Shift the support counts from one granularity to the next. * * @param granularity * The granularity that should be shifted. */ void TiltedTimeWindow::shift(Granularity granularity) { // If the next granularity does not exist, reset this granularity. if (granularity + 1 > TTW_NUM_GRANULARITIES - 1) this->reset(granularity); int offset = GranularityBucketOffset[granularity]; int count = GranularityBucketCount[granularity]; // Calculate the sum of this granularity's buckets. SupportCount sum = 0; for (int bucket = 0; bucket < count; bucket++) sum += buckets[offset + bucket]; // Reset this granularity. this->reset(granularity); // Store the sum of the buckets in the next granularity. this->store((Granularity) (granularity + 1), sum); } /** * Store a next support count in a granularity. * * @param granularity * The granularity to which this support count should be appended. * @param supportCount * The supportCount that should be appended. */ void TiltedTimeWindow::store(Granularity granularity, SupportCount supportCount) { int offset = GranularityBucketOffset[granularity]; int count = GranularityBucketCount[granularity]; int capacityUsed = this->capacityUsed[granularity]; // If the current granularity's maximum capacity has been reached, // then shift it to the next (less granular) granularity. if (capacityUsed == count) { this->shift(granularity); capacityUsed = this->capacityUsed[granularity]; } // Store the value (in the first bucket of this granularity, which // means we'll have to move the data in previously filled in buckets // in this granularity) and update this granularity's capacity. if (capacityUsed > 0) memmove(buckets + offset + 1, buckets + offset, capacityUsed * sizeof(int)); buckets[offset + 0] = supportCount; this->capacityUsed[granularity]++; // Update oldestbucketFilled. if (this->oldestBucketFilled < offset + this->capacityUsed[granularity] - 1) this->oldestBucketFilled = offset + this->capacityUsed[granularity] - 1; } #ifdef DEBUG QDebug operator<<(QDebug dbg, const TiltedTimeWindow & ttw) { int capacityUsed, offset; QVector<SupportCount> buckets = ttw.getBuckets(); dbg.nospace() << "{"; Granularity g; for (g = (Granularity) 0; g < TTW_NUM_GRANULARITIES; g = (Granularity) ((int) g + 1)) { capacityUsed = ttw.getCapacityUsed(g); if (capacityUsed == 0) break; dbg.nospace() << TiltedTimeWindow::GranularityChar[g] << "={"; // Print the contents of this granularity. offset = TiltedTimeWindow::GranularityBucketOffset[g]; for (int b = 0; b < capacityUsed; b++) { if (b > 0) dbg.nospace() << ", "; dbg.nospace() << buckets[offset + b]; } dbg.nospace() << "}"; if (g < TTW_NUM_GRANULARITIES - 1 && ttw.getCapacityUsed((Granularity) (g + 1)) > 0) dbg.nospace() << ", "; } dbg.nospace() << "}"; return dbg.nospace(); } #endif } <commit_msg>In TiltedTimeWindow's QDebug output operator, show the last time it was updated.<commit_after>#include "TiltedTimeWindow.h" namespace Analytics { int TiltedTimeWindow::GranularityBucketCount[TTW_NUM_GRANULARITIES] = { 4, 24, 31, 12, 1 }; int TiltedTimeWindow::GranularityBucketOffset[TTW_NUM_GRANULARITIES] = { 0, 4, 28, 59, 71 }; char TiltedTimeWindow::GranularityChar[TTW_NUM_GRANULARITIES] = {'Q','H','D','M','Y' }; //-------------------------------------------------------------------------- // Public methods. TiltedTimeWindow::TiltedTimeWindow() { this->oldestBucketFilled = -1; this->lastUpdate = 0; for (int b = 0; b < TTW_NUM_BUCKETS; b++) this->buckets[b] = -1; for (int g = 0; g < TTW_NUM_GRANULARITIES; g++) this->capacityUsed[g] = 0; } void TiltedTimeWindow::appendQuarter(SupportCount supportCount, uint32_t updateID) { this->lastUpdate = updateID; store(GRANULARITY_QUARTER, supportCount); } void TiltedTimeWindow::dropTail(int start) { // Find the granularity to which it belongs and reset every // granularity along the way. Granularity g; for (g = (Granularity) (TTW_NUM_GRANULARITIES - 1); g >= 0; g = (Granularity) ((int) g - 1)) { if (start >= this->GranularityBucketOffset[g]) break; else this->reset(g); } // Now decide what to do with the granularity in which this tail // was started to be pruned. Reset the granularity starting at // the starting position of the tail pruning; this will // automatically reset the entire granularity when this is the // first bucket of the granularity. this->reset(g, start); } QVector<SupportCount> TiltedTimeWindow::getBuckets(int numBuckets) const { Q_ASSERT(numBuckets <= TTW_NUM_BUCKETS); QVector<SupportCount> v; for (int i = 0; i < numBuckets; i++) v.append(this->buckets[i]); return v; } //-------------------------------------------------------------------------- // Private methods. /** * Reset a granularity. Defaults to resetting the entire granularity, * but allows for a partial reset. * * @param granularity * The granularity that should be reset. * @param startBucket * When performing a partial reset, */ void TiltedTimeWindow::reset(Granularity granularity, int startBucket) { int offset = GranularityBucketOffset[granularity]; int count = GranularityBucketCount[granularity]; // Reset this granularity's buckets. memset(this->buckets + offset + startBucket, -1, (count - startBucket ) * sizeof(int)); // Update this granularity's used capacity.. this->capacityUsed[granularity] = startBucket; // Update oldestBucketFilled. if (this->oldestBucketFilled > offset + startBucket - 1) this->oldestBucketFilled = offset + startBucket - 1; } /** * Shift the support counts from one granularity to the next. * * @param granularity * The granularity that should be shifted. */ void TiltedTimeWindow::shift(Granularity granularity) { // If the next granularity does not exist, reset this granularity. if (granularity + 1 > TTW_NUM_GRANULARITIES - 1) this->reset(granularity); int offset = GranularityBucketOffset[granularity]; int count = GranularityBucketCount[granularity]; // Calculate the sum of this granularity's buckets. SupportCount sum = 0; for (int bucket = 0; bucket < count; bucket++) sum += buckets[offset + bucket]; // Reset this granularity. this->reset(granularity); // Store the sum of the buckets in the next granularity. this->store((Granularity) (granularity + 1), sum); } /** * Store a next support count in a granularity. * * @param granularity * The granularity to which this support count should be appended. * @param supportCount * The supportCount that should be appended. */ void TiltedTimeWindow::store(Granularity granularity, SupportCount supportCount) { int offset = GranularityBucketOffset[granularity]; int count = GranularityBucketCount[granularity]; int capacityUsed = this->capacityUsed[granularity]; // If the current granularity's maximum capacity has been reached, // then shift it to the next (less granular) granularity. if (capacityUsed == count) { this->shift(granularity); capacityUsed = this->capacityUsed[granularity]; } // Store the value (in the first bucket of this granularity, which // means we'll have to move the data in previously filled in buckets // in this granularity) and update this granularity's capacity. if (capacityUsed > 0) memmove(buckets + offset + 1, buckets + offset, capacityUsed * sizeof(int)); buckets[offset + 0] = supportCount; this->capacityUsed[granularity]++; // Update oldestbucketFilled. if (this->oldestBucketFilled < offset + this->capacityUsed[granularity] - 1) this->oldestBucketFilled = offset + this->capacityUsed[granularity] - 1; } #ifdef DEBUG QDebug operator<<(QDebug dbg, const TiltedTimeWindow & ttw) { int capacityUsed, offset; QVector<SupportCount> buckets = ttw.getBuckets(); dbg.nospace() << "{"; Granularity g; for (g = (Granularity) 0; g < TTW_NUM_GRANULARITIES; g = (Granularity) ((int) g + 1)) { capacityUsed = ttw.getCapacityUsed(g); if (capacityUsed == 0) break; dbg.nospace() << TiltedTimeWindow::GranularityChar[g] << "={"; // Print the contents of this granularity. offset = TiltedTimeWindow::GranularityBucketOffset[g]; for (int b = 0; b < capacityUsed; b++) { if (b > 0) dbg.nospace() << ", "; dbg.nospace() << buckets[offset + b]; } dbg.nospace() << "}"; if (g < TTW_NUM_GRANULARITIES - 1 && ttw.getCapacityUsed((Granularity) (g + 1)) > 0) dbg.nospace() << ", "; } dbg.nospace() << "} (lastUpdate=" << ttw.getLastUpdate() << ")"; return dbg.nospace(); } #endif } <|endoftext|>
<commit_before>/*Copyright 2014 George Karagoulis 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 "enginecontrol.h" #include "ui_enginecontrol.h" #include "gkchess_board.h" #include "gkchess_uci_client.h" USING_NAMESPACE_GKCHESS; NAMESPACE_GKCHESS1(UI); EngineControl::EngineControl(QWidget *parent) :QWidget(parent), ui(new Ui::EngineControl) { ui->setupUi(this); setEnabled(false); } void EngineControl::Initialize(UCI_Client *cli, Board *b) { if(cli && b) { m_uci = cli; m_board = b; connect(cli, SIGNAL(MessageReceived(QByteArray)), this, SLOT(_msg_rx(QByteArray))); connect(cli, SIGNAL(NotifyEngineCrashed()), this, SLOT(_engine_crashed())); setEnabled(true); } } void EngineControl::Uninitialize() { if(IsInitialized()) { disconnect(m_uci, SIGNAL(NotifyEngineCrashed()), this, SLOT(_engine_crashed())); disconnect(m_uci, SIGNAL(MessageReceived(QByteArray)), this, SLOT(_msg_rx(QByteArray))); m_uci = 0; m_board = 0; setEnabled(false); } } EngineControl::~EngineControl() { delete ui; } void EngineControl::Go() { if(IsInitialized()) { m_uci->SetPosition(m_board->ToFEN()); UCI_Client::GoParams p; p.MoveTime = ui->spin_thinkTime->value(); p.Nodes = ui->spin_nodes->value(); p.Depth = ui->spin_depth->value(); p.Mate = ui->spin_mate->value(); m_uci->Go(p); } } void EngineControl::Stop() { if(IsInitialized()) { m_uci->Stop(); } } void EngineControl::_msg_rx(const QByteArray &line) { ui->tb_engineLog->append(line); } void EngineControl::_engine_crashed() { ui->tb_engineLog->append("*** ENGINE CRASHED ***"); } END_NAMESPACE_GKCHESS1; <commit_msg>Added an assertion<commit_after>/*Copyright 2014 George Karagoulis 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 "enginecontrol.h" #include "ui_enginecontrol.h" #include "gkchess_board.h" #include "gkchess_uci_client.h" USING_NAMESPACE_GKCHESS; NAMESPACE_GKCHESS1(UI); EngineControl::EngineControl(QWidget *parent) :QWidget(parent), ui(new Ui::EngineControl) { ui->setupUi(this); setEnabled(false); } void EngineControl::Initialize(UCI_Client *cli, Board *b) { if(cli && b) { m_uci = cli; m_board = b; connect(cli, SIGNAL(MessageReceived(QByteArray)), this, SLOT(_msg_rx(QByteArray))); connect(cli, SIGNAL(NotifyEngineCrashed()), this, SLOT(_engine_crashed())); setEnabled(true); } GASSERT(cli && b); } void EngineControl::Uninitialize() { if(IsInitialized()) { disconnect(m_uci, SIGNAL(NotifyEngineCrashed()), this, SLOT(_engine_crashed())); disconnect(m_uci, SIGNAL(MessageReceived(QByteArray)), this, SLOT(_msg_rx(QByteArray))); m_uci = 0; m_board = 0; setEnabled(false); } } EngineControl::~EngineControl() { delete ui; } void EngineControl::Go() { if(IsInitialized()) { m_uci->SetPosition(m_board->ToFEN()); UCI_Client::GoParams p; p.MoveTime = ui->spin_thinkTime->value(); p.Nodes = ui->spin_nodes->value(); p.Depth = ui->spin_depth->value(); p.Mate = ui->spin_mate->value(); m_uci->Go(p); } } void EngineControl::Stop() { if(IsInitialized()) { m_uci->Stop(); } } void EngineControl::_msg_rx(const QByteArray &line) { ui->tb_engineLog->append(line); } void EngineControl::_engine_crashed() { ui->tb_engineLog->append("*** ENGINE CRASHED ***"); } END_NAMESPACE_GKCHESS1; <|endoftext|>
<commit_before>/*Copyright 2014 George Karagoulis 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 "enginecontrol.h" #include "ui_enginecontrol.h" #include "gkchess_manage_engines.h" #include "gkchess_board.h" #include "gkchess_uci_client.h" #include "gkchess_enginesettings.h" #include "gkchess_uiglobals.h" USING_NAMESPACE_GKCHESS; USING_NAMESPACE_GUTIL1(Qt); USING_NAMESPACE_GUTIL; #define NO_ENGINE_TEXT "(none)" NAMESPACE_GKCHESS1(UI); EngineControl::EngineControl(Board &b, EngineSettings *settings, GUtil::Qt::Settings *appSettings, QWidget *parent) :QWidget(parent), m_board(b), m_settings(settings), m_appSettings(appSettings), m_suppressUpdate(false), ui(new Ui::EngineControl) { ui->setupUi(this); _engines_updated(); if(settings->GetEngineList().size() > 0) _engine_selection_changed(ui->cmb_engine->currentText()); connect(m_settings, SIGNAL(NotifyEnginesUpdated()), this, SLOT(_engines_updated())); connect(ui->cmb_engine, SIGNAL(activated(int)), this, SLOT(_engine_selection_activated(int))); connect(ui->cmb_engine, SIGNAL(currentIndexChanged(QString)), this, SLOT(_engine_selection_changed(QString))); } EngineControl::~EngineControl() { delete ui; } void EngineControl::_engines_updated() { m_engineList = m_settings->GetEngineList(); m_engineList.sort(); // Remove engines from the combo box first QStringList combo_list; for(int i = ui->cmb_engine->count() - 1; i >= 0; --i){ QString engine_name = ui->cmb_engine->itemText(i); if(m_engineList.contains(engine_name)) combo_list.append(engine_name); else ui->cmb_engine->removeItem(i); } // Then add new ones if(0 < m_engineList.size()){ int i = 0; for(const String &k : m_engineList){ int indx = combo_list.indexOf(k); if(-1 == indx) ui->cmb_engine->insertItem(i, k, i); ++i; } ui->wdg_control->setEnabled(true); } else{ ui->cmb_engine->addItem(tr(NO_ENGINE_TEXT), -1); ui->wdg_control->setEnabled(false); } const QString last_engine = m_appSettings->Value(GKCHESS_SETTING_LAST_ENGINE_USED).toString(); int indx = 0; if(!last_engine.isEmpty()){ indx = ui->cmb_engine->findText(last_engine); if(-1 == indx) indx = 0; } ui->cmb_engine->setCurrentIndex(indx); } void EngineControl::Go() { // Since this engine is for analysis only, every position should be from a new game m_engineMan->GetEngine().NewGame(); m_engineMan->GetEngine().WaitForReady(); m_engineMan->GetEngine().SetPosition(m_board.ToFEN()); IEngine::ThinkParams p; p.SearchTime = ui->spin_thinkTime->value(); p.Nodes = ui->spin_nodes->value(); p.Depth = ui->spin_depth->value(); p.Mate = ui->spin_mate->value(); m_engineMan->GetEngine().StartThinking(p); } void EngineControl::Stop() { m_engineMan->GetEngine().StopThinking(); } void EngineControl::_msg_tx(const QByteArray &line) { ui->tb_engineLog->setTextColor(::Qt::blue); ui->tb_engineLog->append(line); } void EngineControl::_msg_rx(const QByteArray &line) { ui->tb_engineLog->setTextColor(::Qt::black); ui->tb_engineLog->append(line); } void EngineControl::_best_move_received(const GenericMove &, const GenericMove &) { ui->btn_gostop->setChecked(false); } void EngineControl::_engine_crashed() { ui->tb_engineLog->setTextColor(::Qt::red); ui->tb_engineLog->append(tr("*** ENGINE CRASHED ***")); ui->btn_gostop->setChecked(false); } void EngineControl::_go_stop_pressed() { bool checked = ui->btn_gostop->isChecked(); if(checked) Go(); else Stop(); _update_go_stop_text(checked); } void EngineControl::_update_go_stop_text(bool checked) { if(checked) ui->btn_gostop->setText(tr("Stop")); else ui->btn_gostop->setText(tr("Go")); } void EngineControl::_engine_selection_activated(int indx) { if(0 == indx && ui->cmb_engine->currentText() == NO_ENGINE_TEXT){ // Open the engine settings manager ManageEngines mng(m_settings, m_appSettings, this); mng.exec(); } } void EngineControl::_engine_selection_changed(const QString &engine_name) { if(engine_name.isEmpty()) return; if(!m_engineMan || m_engineMan->GetEngineName() != engine_name){ m_engineMan = new EngineManager(ui->cmb_engine->currentText(), m_settings); connect(&m_engineMan->GetEngine(), SIGNAL(MessageSent(QByteArray)), this, SLOT(_msg_tx(QByteArray))); connect(&m_engineMan->GetEngine(), SIGNAL(MessageReceived(QByteArray)), this, SLOT(_msg_rx(QByteArray))); connect(&m_engineMan->GetEngine(), SIGNAL(NotifyEngineCrashed()), this, SLOT(_engine_crashed())); connect(&m_engineMan->GetEngine(), SIGNAL(BestMove(const GenericMove &, const GenericMove &)), this, SLOT(_best_move_received(const GenericMove &, const GenericMove &))); // Whenever we switch engines, remember the last one we used m_appSettings->SetValue(GKCHESS_SETTING_LAST_ENGINE_USED, engine_name); } else{ m_engineMan->ApplySettings(); } ui->wdg_control->setEnabled(true); } END_NAMESPACE_GKCHESS1; <commit_msg>Cleaned up an invalid memory access<commit_after>/*Copyright 2014 George Karagoulis 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 "enginecontrol.h" #include "ui_enginecontrol.h" #include "gkchess_manage_engines.h" #include "gkchess_board.h" #include "gkchess_uci_client.h" #include "gkchess_enginesettings.h" #include "gkchess_uiglobals.h" USING_NAMESPACE_GKCHESS; USING_NAMESPACE_GUTIL1(Qt); USING_NAMESPACE_GUTIL; #define NO_ENGINE_TEXT "(none)" NAMESPACE_GKCHESS1(UI); EngineControl::EngineControl(Board &b, EngineSettings *settings, GUtil::Qt::Settings *appSettings, QWidget *parent) :QWidget(parent), m_board(b), m_settings(settings), m_appSettings(appSettings), m_suppressUpdate(false), ui(new Ui::EngineControl) { ui->setupUi(this); _engines_updated(); if(settings->GetEngineList().size() > 0) _engine_selection_changed(ui->cmb_engine->currentText()); connect(m_settings, SIGNAL(NotifyEnginesUpdated()), this, SLOT(_engines_updated())); connect(ui->cmb_engine, SIGNAL(activated(int)), this, SLOT(_engine_selection_activated(int))); connect(ui->cmb_engine, SIGNAL(currentIndexChanged(QString)), this, SLOT(_engine_selection_changed(QString))); } EngineControl::~EngineControl() { m_engineMan.Clear(); delete ui; } void EngineControl::_engines_updated() { m_engineList = m_settings->GetEngineList(); m_engineList.sort(); // Remove engines from the combo box first QStringList combo_list; for(int i = ui->cmb_engine->count() - 1; i >= 0; --i){ QString engine_name = ui->cmb_engine->itemText(i); if(m_engineList.contains(engine_name)) combo_list.append(engine_name); else ui->cmb_engine->removeItem(i); } // Then add new ones if(0 < m_engineList.size()){ int i = 0; for(const String &k : m_engineList){ int indx = combo_list.indexOf(k); if(-1 == indx) ui->cmb_engine->insertItem(i, k, i); ++i; } ui->wdg_control->setEnabled(true); } else{ ui->cmb_engine->addItem(tr(NO_ENGINE_TEXT), -1); ui->wdg_control->setEnabled(false); } const QString last_engine = m_appSettings->Value(GKCHESS_SETTING_LAST_ENGINE_USED).toString(); int indx = 0; if(!last_engine.isEmpty()){ indx = ui->cmb_engine->findText(last_engine); if(-1 == indx) indx = 0; } ui->cmb_engine->setCurrentIndex(indx); } void EngineControl::Go() { // Since this engine is for analysis only, every position should be from a new game m_engineMan->GetEngine().NewGame(); m_engineMan->GetEngine().WaitForReady(); m_engineMan->GetEngine().SetPosition(m_board.ToFEN()); IEngine::ThinkParams p; p.SearchTime = ui->spin_thinkTime->value(); p.Nodes = ui->spin_nodes->value(); p.Depth = ui->spin_depth->value(); p.Mate = ui->spin_mate->value(); m_engineMan->GetEngine().StartThinking(p); } void EngineControl::Stop() { m_engineMan->GetEngine().StopThinking(); } void EngineControl::_msg_tx(const QByteArray &line) { ui->tb_engineLog->setTextColor(::Qt::blue); ui->tb_engineLog->append(line); } void EngineControl::_msg_rx(const QByteArray &line) { ui->tb_engineLog->setTextColor(::Qt::black); ui->tb_engineLog->append(line); } void EngineControl::_best_move_received(const GenericMove &, const GenericMove &) { ui->btn_gostop->setChecked(false); } void EngineControl::_engine_crashed() { ui->tb_engineLog->setTextColor(::Qt::red); ui->tb_engineLog->append(tr("*** ENGINE CRASHED ***")); ui->btn_gostop->setChecked(false); } void EngineControl::_go_stop_pressed() { bool checked = ui->btn_gostop->isChecked(); if(checked) Go(); else Stop(); _update_go_stop_text(checked); } void EngineControl::_update_go_stop_text(bool checked) { if(checked) ui->btn_gostop->setText(tr("Stop")); else ui->btn_gostop->setText(tr("Go")); } void EngineControl::_engine_selection_activated(int indx) { if(0 == indx && ui->cmb_engine->currentText() == NO_ENGINE_TEXT){ // Open the engine settings manager ManageEngines mng(m_settings, m_appSettings, this); mng.exec(); } } void EngineControl::_engine_selection_changed(const QString &engine_name) { if(engine_name.isEmpty()) return; if(!m_engineMan || m_engineMan->GetEngineName() != engine_name){ m_engineMan = new EngineManager(ui->cmb_engine->currentText(), m_settings); connect(&m_engineMan->GetEngine(), SIGNAL(MessageSent(QByteArray)), this, SLOT(_msg_tx(QByteArray))); connect(&m_engineMan->GetEngine(), SIGNAL(MessageReceived(QByteArray)), this, SLOT(_msg_rx(QByteArray))); connect(&m_engineMan->GetEngine(), SIGNAL(NotifyEngineCrashed()), this, SLOT(_engine_crashed())); connect(&m_engineMan->GetEngine(), SIGNAL(BestMove(const GenericMove &, const GenericMove &)), this, SLOT(_best_move_received(const GenericMove &, const GenericMove &))); // Whenever we switch engines, remember the last one we used m_appSettings->SetValue(GKCHESS_SETTING_LAST_ENGINE_USED, engine_name); } else{ m_engineMan->ApplySettings(); } ui->wdg_control->setEnabled(true); } END_NAMESPACE_GKCHESS1; <|endoftext|>
<commit_before><commit_msg>Cleaning up code.<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tf/transform_listener.h> #include <geometry_msgs/PoseStamped.h> #include "rviz/display_context.h" #include "rviz/properties/string_property.h" #include "rviz/default_plugin/tools/goal_tool.h" namespace rviz { GoalTool::GoalTool() { shortcut_key_ = 'g'; topic_property_ = new StringProperty( "Topic", "/move_base_simple/goal", "The topic on which to publish navigation goals.", getPropertyContainer(), SLOT( updateTopic() ), this ); } void GoalTool::onInitialize() { PoseTool::onInitialize(); setName( "2D Nav Goal" ); updateTopic(); } void GoalTool::updateTopic() { pub_ = nh_.advertise<geometry_msgs::PoseStamped>( topic_property_->getStdString(), 1 ); } void GoalTool::onPoseSet(double x, double y, double theta) { std::string fixed_frame = context_->getFixedFrame().toStdString(); tf::Quaternion quat; quat.setRPY(0.0, 0.0, theta); tf::Stamped<tf::Pose> p = tf::Stamped<tf::Pose>(tf::Pose(quat, tf::Point(x, y, 0.0)), ros::Time::now(), fixed_frame); geometry_msgs::PoseStamped goal; tf::poseStampedTFToMsg(p, goal); ROS_INFO("Setting goal: Frame:%s, Position(%.3f, %.3f, %.3f), Orientation(%.3f, %.3f, %.3f, %.3f) = Angle: %.3f\n", fixed_frame.c_str(), goal.pose.position.x, goal.pose.position.y, goal.pose.position.z, goal.pose.orientation.x, goal.pose.orientation.y, goal.pose.orientation.z, goal.pose.orientation.w, theta); pub_.publish(goal); } } // end namespace rviz #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS( rviz::GoalTool, rviz::Tool ) <commit_msg>GoalTool: changed '/move_base_simple/goal'->'goal'<commit_after>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <tf/transform_listener.h> #include <geometry_msgs/PoseStamped.h> #include "rviz/display_context.h" #include "rviz/properties/string_property.h" #include "rviz/default_plugin/tools/goal_tool.h" namespace rviz { GoalTool::GoalTool() { shortcut_key_ = 'g'; topic_property_ = new StringProperty( "Topic", "goal", "The topic on which to publish navigation goals.", getPropertyContainer(), SLOT( updateTopic() ), this ); } void GoalTool::onInitialize() { PoseTool::onInitialize(); setName( "2D Nav Goal" ); updateTopic(); } void GoalTool::updateTopic() { pub_ = nh_.advertise<geometry_msgs::PoseStamped>( topic_property_->getStdString(), 1 ); } void GoalTool::onPoseSet(double x, double y, double theta) { std::string fixed_frame = context_->getFixedFrame().toStdString(); tf::Quaternion quat; quat.setRPY(0.0, 0.0, theta); tf::Stamped<tf::Pose> p = tf::Stamped<tf::Pose>(tf::Pose(quat, tf::Point(x, y, 0.0)), ros::Time::now(), fixed_frame); geometry_msgs::PoseStamped goal; tf::poseStampedTFToMsg(p, goal); ROS_INFO("Setting goal: Frame:%s, Position(%.3f, %.3f, %.3f), Orientation(%.3f, %.3f, %.3f, %.3f) = Angle: %.3f\n", fixed_frame.c_str(), goal.pose.position.x, goal.pose.position.y, goal.pose.position.z, goal.pose.orientation.x, goal.pose.orientation.y, goal.pose.orientation.z, goal.pose.orientation.w, theta); pub_.publish(goal); } } // end namespace rviz #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS( rviz::GoalTool, rviz::Tool ) <|endoftext|>
<commit_before>//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_io_PcapSignalMgr.h" #include "jnc_io_Pcap.h" namespace jnc { namespace io { //.............................................................................. PcapSignalMgr::PcapSignalMgr() { memset(&m_prevSigAction, 0, sizeof(m_prevSigAction)); m_installCount = 0; } void PcapSignalMgr::install() { int32_t installCount = sys::atomicInc(&m_installCount); if (installCount != 1) return; struct sigaction sigAction = { 0 }; sigAction.sa_flags = SA_SIGINFO; sigAction.sa_sigaction = signalHandler; ::sigemptyset(&sigAction.sa_mask); int result = ::sigaction(Signal, &sigAction, &m_prevSigAction); ASSERT(result == 0); } void PcapSignalMgr::uninstall() { int32_t installCount = sys::atomicDec(&m_installCount); if (installCount != 0) return; int result = ::sigaction(Signal, &m_prevSigAction, NULL); ASSERT(result == 0); memset(&m_prevSigAction, 0, sizeof(m_prevSigAction)); } void PcapSignalMgr::signalHandler( int signal, siginfo_t* signalInfo, void* context ) { ASSERT(signal == Signal); Pcap* pcap = sys::getTlsPtrSlotValue<Pcap>(); if (pcap) ::pcap_breakloop(pcap->getPcap()); const struct sigaction* prevSigAction = &sl::getSimpleSingleton<PcapSignalMgr>()->m_prevSigAction; if (prevSigAction->sa_handler == SIG_IGN || prevSigAction->sa_handler == SIG_DFL) return; if (!(prevSigAction->sa_flags & SA_SIGINFO)) prevSigAction->sa_handler(signal); else if (prevSigAction->sa_sigaction) prevSigAction->sa_sigaction(signal, signalInfo, context); } //.............................................................................. } // namespace io } // namespace jnc <commit_msg>[jnc_io_pcap] fix: sigemptyset may be a macro (remove context operator ::)<commit_after>//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_io_PcapSignalMgr.h" #include "jnc_io_Pcap.h" namespace jnc { namespace io { //.............................................................................. PcapSignalMgr::PcapSignalMgr() { memset(&m_prevSigAction, 0, sizeof(m_prevSigAction)); m_installCount = 0; } void PcapSignalMgr::install() { int32_t installCount = sys::atomicInc(&m_installCount); if (installCount != 1) return; struct sigaction sigAction = { 0 }; sigAction.sa_flags = SA_SIGINFO; sigAction.sa_sigaction = signalHandler; sigemptyset(&sigAction.sa_mask); int result = ::sigaction(Signal, &sigAction, &m_prevSigAction); ASSERT(result == 0); } void PcapSignalMgr::uninstall() { int32_t installCount = sys::atomicDec(&m_installCount); if (installCount != 0) return; int result = ::sigaction(Signal, &m_prevSigAction, NULL); ASSERT(result == 0); memset(&m_prevSigAction, 0, sizeof(m_prevSigAction)); } void PcapSignalMgr::signalHandler( int signal, siginfo_t* signalInfo, void* context ) { ASSERT(signal == Signal); Pcap* pcap = sys::getTlsPtrSlotValue<Pcap>(); if (pcap) ::pcap_breakloop(pcap->getPcap()); const struct sigaction* prevSigAction = &sl::getSimpleSingleton<PcapSignalMgr>()->m_prevSigAction; if (prevSigAction->sa_handler == SIG_IGN || prevSigAction->sa_handler == SIG_DFL) return; if (!(prevSigAction->sa_flags & SA_SIGINFO)) prevSigAction->sa_handler(signal); else if (prevSigAction->sa_sigaction) prevSigAction->sa_sigaction(signal, signalInfo, context); } //.............................................................................. } // namespace io } // namespace jnc <|endoftext|>
<commit_before>/****************************************************************************** SparkFun_9DOF_Edison_Block_Example.cpp Example code for the 9DOF Edison Block 14 Jul 2015 by Mike Hord https://github.com/sparkfun/SparkFun_9DOF_Block_for_Edison_CPP_Library Demonstrates the major functionality of the SparkFun 9DOF block for Edison. ** Supports only I2C connection! ** Development environment specifics: Code developed in Intel's Eclipse IOT-DK This code requires the Intel mraa library to function; for more information see https://github.com/intel-iot-devkit/mraa This code is beerware; if you see me (or any other SparkFun employee) at the local, and you've found our code helpful, please buy us a round! Distributed as-is; no warranty is given. ******************************************************************************/ #include "mraa.hpp" #include <sys/types.h> #include <syslog.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <syslog.h> #include <string.h> #include <signal.h> #include <iostream> #include "SFE_LSM9DS0.h" using namespace std; int running = 1; void sig_handler(int signo) { if (signo == SIGINT || signo == SIGTERM || signo == SIGHUP) { printf("Closing and cleaning up\n"); running = 0; } } int main( int argc, char* argv[] ) { LSM9DS0 *imu; /* Our process ID and Session ID */ pid_t pid, sid; /* Fork off the parent process */ pid = fork(); if (pid < 0) { fprintf(stderr, "Can't fork child\n"); exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } /* Change the file mode mask */ umask(0); setlogmask (LOG_UPTO (LOG_NOTICE)); openlog (argv[0], LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1); syslog (LOG_NOTICE, "Program started by User %d", getuid ()); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { /* Log the failure */ syslog (LOG_ERR, "Can't create new SID for child process"); exit(EXIT_FAILURE); } /* Change the current working directory */ if ((chdir("/")) < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); /* Daemon-specific initialization goes here */ syslog (LOG_NOTICE, "Program started by User %d", getuid ()); signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); signal(SIGHUP, sig_handler); imu = new LSM9DS0(0x6B, 0x1D); // The begin() function sets up some basic parameters and turns the device // on; you may not need to do more than call it. It also returns the "whoami" // registers from the chip. If all is good, the return value here should be // 0x49d4. Here are the initial settings from this function: // Gyro scale: 245 deg/sec max // Xl scale: 4g max // Mag scale: 2 Gauss max // Gyro sample rate: 95Hz // Xl sample rate: 100Hz // Mag sample rate: 100Hz // These can be changed either by calling appropriate functions or by // pasing parameters to the begin() function. There are named constants in // the .h file for all scales and data rates; I won't reproduce them here. // Here's the list of fuctions to set the rates/scale: // setMagScale(mag_scale mScl) setMagODR(mag_odr mRate) // setGyroScale(gyro_scale gScl) setGyroODR(gyro_odr gRate) // setAccelScale(accel_scale aScl) setGyroODR(accel_odr aRate) // If you want to make these changes at the point of calling begin, here's // the prototype for that function showing the order to pass things: // begin(gyro_scale gScl, accel_scale aScl, mag_scale mScl, // gyro_odr gODR, accel_odr aODR, mag_odr mODR) uint16_t imuResult = imu->begin(); cout<<hex<<"Chip ID: 0x"<<imuResult<<dec<<" (should be 0x49d4)"<<endl; bool newAccelData = false; bool newMagData = false; bool newGyroData = false; bool overflow = false; // Loop and report data while (running) { // First, let's make sure we're collecting up-to-date information. The // sensors are sampling at 100Hz (for the accelerometer, magnetometer, and // temp) and 95Hz (for the gyro), and we could easily do a bunch of // crap within that ~10ms sampling period. while ((newGyroData & newAccelData & newMagData) != true) { if (newAccelData != true) { newAccelData = imu->newXData(); } if (newGyroData != true) { newGyroData = imu->newGData(); } if (newMagData != true) { newMagData = imu->newMData(); // Temp data is collected at the same // rate as magnetometer data. } } newAccelData = false; newMagData = false; newGyroData = false; // Of course, we may care if an overflow occurred; we can check that // easily enough from an internal register on the part. There are functions // to check for overflow per device. overflow = imu->xDataOverflow() | imu->gDataOverflow() | imu->mDataOverflow(); if (overflow) { syslog (LOG_INFO, "Warning: Data overflow!!!"); } // Calling these functions causes the data to be read from the IMU into // 10 16-bit signed integer public variables, as seen below. There is no // automated check on whether the data is new; you need to do that // manually as above. Also, there's no check on overflow, so you may miss // a sample and not know it. imu->readAccel(); imu->readMag(); imu->readGyro(); imu->readTemp(); // Print the unscaled 16-bit signed values. cout<<"-------------------------------------"<<endl; cout<<"Gyro x: "<<imu->gx<<endl; cout<<"Gyro y: "<<imu->gy<<endl; cout<<"Gyro z: "<<imu->gz<<endl; cout<<"Accel x: "<<imu->ax<<endl; cout<<"Accel y: "<<imu->ay<<endl; cout<<"Accel z: "<<imu->az<<endl; cout<<"Mag x: "<<imu->mx<<endl; cout<<"Mag y: "<<imu->my<<endl; cout<<"Mag z: "<<imu->mz<<endl; cout<<"Temp: "<<imu->temperature<<endl; cout<<"-------------------------------------"<<endl; // Print the "real" values in more human comprehensible units. cout<<"-------------------------------------"<<endl; cout<<"Gyro x: "<<imu->calcGyro(imu->gx)<<" deg/s"<<endl; cout<<"Gyro y: "<<imu->calcGyro(imu->gy)<<" deg/s"<<endl; cout<<"Gyro z: "<<imu->calcGyro(imu->gz)<<" deg/s"<<endl; cout<<"Accel x: "<<imu->calcAccel(imu->ax)<<" g"<<endl; cout<<"Accel y: "<<imu->calcAccel(imu->ay)<<" g"<<endl; cout<<"Accel z: "<<imu->calcAccel(imu->az)<<" g"<<endl; cout<<"Mag x: "<<imu->calcMag(imu->mx)<<" Gauss"<<endl; cout<<"Mag y: "<<imu->calcMag(imu->my)<<" Gauss"<<endl; cout<<"Mag z: "<<imu->calcMag(imu->mz)<<" Gauss"<<endl; // Temp conversion is left as an example to the reader, as it requires a // good deal of device- and system-specific calibration. The on-board // temp sensor is probably best not used if local temp data is required! cout<<"-------------------------------------"<<endl; sleep(1); } closelog(); delete imu; return MRAA_SUCCESS; } <commit_msg>Open file to write accel, gyro, magne<commit_after>/****************************************************************************** SparkFun_9DOF_Edison_Block_Example.cpp Example code for the 9DOF Edison Block 14 Jul 2015 by Mike Hord https://github.com/sparkfun/SparkFun_9DOF_Block_for_Edison_CPP_Library Demonstrates the major functionality of the SparkFun 9DOF block for Edison. ** Supports only I2C connection! ** Development environment specifics: Code developed in Intel's Eclipse IOT-DK This code requires the Intel mraa library to function; for more information see https://github.com/intel-iot-devkit/mraa This code is beerware; if you see me (or any other SparkFun employee) at the local, and you've found our code helpful, please buy us a round! Distributed as-is; no warranty is given. ******************************************************************************/ #include "mraa.hpp" #include <sys/types.h> #include <time.h> #include <syslog.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <syslog.h> #include <string.h> #include <signal.h> #include <iostream> #include "SFE_LSM9DS0.h" using namespace std; int running = 1; void sig_handler(int signo) { if (signo == SIGINT || signo == SIGTERM || signo == SIGHUP) { printf("Closing and cleaning up\n"); running = 0; } } int main( int argc, char* argv[] ) { LSM9DS0 *imu; /* Our process ID and Session ID */ pid_t pid, sid; /* Fork off the parent process */ pid = fork(); if (pid < 0) { fprintf(stderr, "Can't fork child\n"); exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } /* Change the file mode mask */ umask(0); setlogmask (LOG_UPTO (LOG_NOTICE)); openlog (argv[0], LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1); syslog (LOG_NOTICE, "Program started by User %d", getuid ()); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { /* Log the failure */ syslog (LOG_ERR, "Can't create new SID for child process"); exit(EXIT_FAILURE); } /* Change the current working directory */ /* if ((chdir("/")) < 0) { exit(EXIT_FAILURE); } */ /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); /* Daemon-specific initialization goes here */ syslog (LOG_NOTICE, "Program started by User %d", getuid ()); signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); signal(SIGHUP, sig_handler); imu = new LSM9DS0(0x6B, 0x1D); // The begin() function sets up some basic parameters and turns the device // on; you may not need to do more than call it. It also returns the "whoami" // registers from the chip. If all is good, the return value here should be // 0x49d4. Here are the initial settings from this function: // Gyro scale: 245 deg/sec max // Xl scale: 4g max // Mag scale: 2 Gauss max // Gyro sample rate: 95Hz // Xl sample rate: 100Hz // Mag sample rate: 100Hz // These can be changed either by calling appropriate functions or by // pasing parameters to the begin() function. There are named constants in // the .h file for all scales and data rates; I won't reproduce them here. // Here's the list of fuctions to set the rates/scale: // setMagScale(mag_scale mScl) setMagODR(mag_odr mRate) // setGyroScale(gyro_scale gScl) setGyroODR(gyro_odr gRate) // setAccelScale(accel_scale aScl) setGyroODR(accel_odr aRate) // If you want to make these changes at the point of calling begin, here's // the prototype for that function showing the order to pass things: // begin(gyro_scale gScl, accel_scale aScl, mag_scale mScl, // gyro_odr gODR, accel_odr aODR, mag_odr mODR) uint16_t imuResult = imu->begin(); // cout<<hex<<"Chip ID: 0x"<<imuResult<<dec<<" (should be 0x49d4)"<<endl; bool newAccelData = false; bool newMagData = false; bool newGyroData = false; bool overflow = false; time_t now; struct tm ts; char buf[80]; char path[256]; memset(path, 0, sizeof(path)); // Get current time time(&now); // Format time, "ddd yyyy-mm-dd hh:mm:ss zzz" ts = *localtime(&now); strftime(buf, sizeof(buf), "%a_%Y-%m-%d_%H:%M:%S_%Z.csv", &ts); if (argc > 1) { strcat(path, argv[1]); } strcat(path, buf); // open the file FILE* fd2 = fopen (path, "w+"); if (fd2 == NULL) { running = 0; } // Loop and report data while (running) { // First, let's make sure we're collecting up-to-date information. The // sensors are sampling at 100Hz (for the accelerometer, magnetometer, and // temp) and 95Hz (for the gyro), and we could easily do a bunch of // crap within that ~10ms sampling period. while ((newGyroData & newAccelData & newMagData) != true) { if (newAccelData != true) { newAccelData = imu->newXData(); } if (newGyroData != true) { newGyroData = imu->newGData(); } if (newMagData != true) { newMagData = imu->newMData(); // Temp data is collected at the same // rate as magnetometer data. } } newAccelData = false; newMagData = false; newGyroData = false; // Of course, we may care if an overflow occurred; we can check that // easily enough from an internal register on the part. There are functions // to check for overflow per device. overflow = imu->xDataOverflow() | imu->gDataOverflow() | imu->mDataOverflow(); if (overflow) { syslog (LOG_INFO, "Warning: Data overflow!!!"); } // Calling these functions causes the data to be read from the IMU into // 10 16-bit signed integer public variables, as seen below. There is no // automated check on whether the data is new; you need to do that // manually as above. Also, there's no check on overflow, so you may miss // a sample and not know it. imu->readAccel(); imu->readMag(); imu->readGyro(); imu->readTemp(); // Print the unscaled 16-bit signed values. /* cout<<"-------------------------------------"<<endl; cout<<"Gyro x: "<<imu->gx<<endl; cout<<"Gyro y: "<<imu->gy<<endl; cout<<"Gyro z: "<<imu->gz<<endl; cout<<"Accel x: "<<imu->ax<<endl; cout<<"Accel y: "<<imu->ay<<endl; cout<<"Accel z: "<<imu->az<<endl; cout<<"Mag x: "<<imu->mx<<endl; cout<<"Mag y: "<<imu->my<<endl; cout<<"Mag z: "<<imu->mz<<endl; cout<<"Temp: "<<imu->temperature<<endl; cout<<"-------------------------------------"<<endl; */ // Print the "real" values in more human comprehensible units. /* cout<<"-------------------------------------"<<endl; cout<<"Gyro x: "<<imu->calcGyro(imu->gx)<<" deg/s"<<endl; cout<<"Gyro y: "<<imu->calcGyro(imu->gy)<<" deg/s"<<endl; cout<<"Gyro z: "<<imu->calcGyro(imu->gz)<<" deg/s"<<endl; cout<<"Accel x: "<<imu->calcAccel(imu->ax)<<" g"<<endl; cout<<"Accel y: "<<imu->calcAccel(imu->ay)<<" g"<<endl; cout<<"Accel z: "<<imu->calcAccel(imu->az)<<" g"<<endl; cout<<"Mag x: "<<imu->calcMag(imu->mx)<<" Gauss"<<endl; cout<<"Mag y: "<<imu->calcMag(imu->my)<<" Gauss"<<endl; cout<<"Mag z: "<<imu->calcMag(imu->mz)<<" Gauss"<<endl; */ fprintf (fd2, "%f,%f,%f,%f,%f,%f,%f,%f,%f\n", imu->calcGyro(imu->gx), imu->calcGyro(imu->gy), imu->calcGyro(imu->gz), imu->calcAccel(imu->ax), imu->calcAccel(imu->ay), imu->calcAccel(imu->az), imu->calcMag(imu->mx), imu->calcMag(imu->my), imu->calcMag(imu->mz)); // Temp conversion is left as an example to the reader, as it requires a // good deal of device- and system-specific calibration. The on-board // temp sensor is probably best not used if local temp data is required! // cout<<"-------------------------------------"<<endl; sleep(1); } if (fd2 != NULL) { fclose(fd2); } delete imu; return MRAA_SUCCESS; } <|endoftext|>