text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. 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. namespace iox { namespace concurrent { template <class ValueType, uint32_t CapacityValue> SoFi<ValueType, CapacityValue>::SoFi() noexcept { } template <class ValueType, uint32_t CapacityValue> uint64_t SoFi<ValueType, CapacityValue>::capacity() const noexcept { return m_size - INTERNAL_SIZE_ADD_ON; } template <class ValueType, uint32_t CapacityValue> uint64_t SoFi<ValueType, CapacityValue>::size() const noexcept { uint64_t readPosition; uint64_t writePosition; do { readPosition = m_readPosition.load(std::memory_order_relaxed); writePosition = m_writePosition.load(std::memory_order_relaxed); } while (m_writePosition.load(std::memory_order_relaxed) != writePosition || m_readPosition.load(std::memory_order_relaxed) != readPosition); return writePosition - readPosition; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::resize(const uint32_t newSize) noexcept { uint64_t newInternalSize = newSize + INTERNAL_SIZE_ADD_ON; if (empty() && (newInternalSize <= INTERNAL_SOFI_SIZE)) { m_size = newInternalSize; m_readPosition.store(0u, std::memory_order_release); m_writePosition.store(0u, std::memory_order_release); return true; } return false; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::empty() const noexcept { uint64_t currentReadPosition; bool isEmpty; do { /// @todo read before write since the writer increments the aba counter!!! /// @todo write doc with example!!! currentReadPosition = m_readPosition.load(std::memory_order_acquire); uint64_t currentWritePosition = m_writePosition.load(std::memory_order_acquire); isEmpty = (currentWritePosition == currentReadPosition); // we need compare without exchange } while (!(currentReadPosition == m_readPosition.load(std::memory_order_acquire))); return isEmpty; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::pop(ValueType& valueOut) noexcept { return popIf(valueOut, [](ValueType) { return true; }); } template <class ValueType, uint32_t CapacityValue> template <typename Verificator_T> inline bool SoFi<ValueType, CapacityValue>::popIf(ValueType& valueOut, const Verificator_T& verificator) noexcept { uint64_t currentReadPosition = m_readPosition.load(std::memory_order_acquire); uint64_t nextReadPosition; bool popWasSuccessful{true}; do { if (currentReadPosition == m_writePosition.load(std::memory_order_acquire)) { nextReadPosition = currentReadPosition; popWasSuccessful = false; } else { // we use memcpy here, since the copy assignment is not thread safe in general (we might have an overflow in // the push thread and invalidates the object while the copy is running and therefore works on an // invalid object); memcpy is also not thread safe, but we discard the object anyway and read it // again if its overwritten in between; this is only relevant for types larger than pointer size // assign the user data std::memcpy(&valueOut, &m_data[static_cast<int32_t>(currentReadPosition) % m_size], sizeof(ValueType)); /// @brief first we need to peak valueOut if it is fitting the condition and then we have to verify /// if valueOut is not am invalid object, this could be the case if the read position has /// changed if (m_readPosition.load(std::memory_order_relaxed) == currentReadPosition && verificator(valueOut) == false) { popWasSuccessful = false; } else { nextReadPosition = currentReadPosition + 1U; popWasSuccessful = true; } } // compare and swap // if(m_readPosition == currentReadPosition) // m_readPosition = l_next_aba_read_pos // else // currentReadPosition = m_readPosition // Assign m_aba_read_p to next readable location } while (!m_readPosition.compare_exchange_weak( currentReadPosition, nextReadPosition, std::memory_order_acq_rel, std::memory_order_acquire)); return popWasSuccessful; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::push(const ValueType& valueOut, ValueType& f_paramOut_r) noexcept { constexpr bool OVERFLOW{false}; uint64_t currentWritePosition = m_writePosition.load(std::memory_order_relaxed); uint64_t nextWritePosition = currentWritePosition + 1U; m_data[static_cast<int32_t>(currentWritePosition) % m_size] = valueOut; m_writePosition.store(nextWritePosition, std::memory_order_release); uint64_t currentReadPosition = m_readPosition.load(std::memory_order_acquire); // check if there is a free position for the next push if (nextWritePosition < currentReadPosition + m_size) { return !OVERFLOW; } // this is an overflow situation, which means that the next push has no free position, therefore the oldest value // needs to be passed back to the caller uint64_t nextReadPosition = currentReadPosition + 1U; // we need to update the read position // a) it works, then we need to pass the overflow value back // b) it doesn't work, which means that the pop thread already took the value in the meantime an no further action // is required // memory order success is memory_order_acq_rel // - this is to prevent the reordering of m_writePosition.store(...) after the increment of the m_readPosition // - in case of an overflow, this might result in the pop thread getting one element less than the capacity of // the SoFi if the push thread is suspended in between this two statements // - it's still possible to get more elements than the capacity, but this is an inherent issue with concurrent // queues and cannot be prevented since there can always be a push during a pop operation // - another issue might be that two consecutive pushes (not concurrent) happen on different CPU cores without // synchronization, then the memory also needs to be synchronized for the overflow case // memory order failure is memory_order_relaxed since there is no further synchronization needed if there is no // overflow if (m_readPosition.compare_exchange_strong( currentReadPosition, nextReadPosition, std::memory_order_acq_rel, std::memory_order_relaxed)) { std::memcpy(&f_paramOut_r, &m_data[static_cast<int32_t>(currentReadPosition) % m_size], sizeof(ValueType)); return OVERFLOW; } return !OVERFLOW; } } // namespace concurrent } // namespace iox <commit_msg>iox-#119 fixing xcode OVERLFOW macro usage in sofi<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. 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. namespace iox { namespace concurrent { template <class ValueType, uint32_t CapacityValue> SoFi<ValueType, CapacityValue>::SoFi() noexcept { } template <class ValueType, uint32_t CapacityValue> uint64_t SoFi<ValueType, CapacityValue>::capacity() const noexcept { return m_size - INTERNAL_SIZE_ADD_ON; } template <class ValueType, uint32_t CapacityValue> uint64_t SoFi<ValueType, CapacityValue>::size() const noexcept { uint64_t readPosition; uint64_t writePosition; do { readPosition = m_readPosition.load(std::memory_order_relaxed); writePosition = m_writePosition.load(std::memory_order_relaxed); } while (m_writePosition.load(std::memory_order_relaxed) != writePosition || m_readPosition.load(std::memory_order_relaxed) != readPosition); return writePosition - readPosition; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::resize(const uint32_t newSize) noexcept { uint64_t newInternalSize = newSize + INTERNAL_SIZE_ADD_ON; if (empty() && (newInternalSize <= INTERNAL_SOFI_SIZE)) { m_size = newInternalSize; m_readPosition.store(0u, std::memory_order_release); m_writePosition.store(0u, std::memory_order_release); return true; } return false; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::empty() const noexcept { uint64_t currentReadPosition; bool isEmpty; do { /// @todo read before write since the writer increments the aba counter!!! /// @todo write doc with example!!! currentReadPosition = m_readPosition.load(std::memory_order_acquire); uint64_t currentWritePosition = m_writePosition.load(std::memory_order_acquire); isEmpty = (currentWritePosition == currentReadPosition); // we need compare without exchange } while (!(currentReadPosition == m_readPosition.load(std::memory_order_acquire))); return isEmpty; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::pop(ValueType& valueOut) noexcept { return popIf(valueOut, [](ValueType) { return true; }); } template <class ValueType, uint32_t CapacityValue> template <typename Verificator_T> inline bool SoFi<ValueType, CapacityValue>::popIf(ValueType& valueOut, const Verificator_T& verificator) noexcept { uint64_t currentReadPosition = m_readPosition.load(std::memory_order_acquire); uint64_t nextReadPosition; bool popWasSuccessful{true}; do { if (currentReadPosition == m_writePosition.load(std::memory_order_acquire)) { nextReadPosition = currentReadPosition; popWasSuccessful = false; } else { // we use memcpy here, since the copy assignment is not thread safe in general (we might have an overflow in // the push thread and invalidates the object while the copy is running and therefore works on an // invalid object); memcpy is also not thread safe, but we discard the object anyway and read it // again if its overwritten in between; this is only relevant for types larger than pointer size // assign the user data std::memcpy(&valueOut, &m_data[static_cast<int32_t>(currentReadPosition) % m_size], sizeof(ValueType)); /// @brief first we need to peak valueOut if it is fitting the condition and then we have to verify /// if valueOut is not am invalid object, this could be the case if the read position has /// changed if (m_readPosition.load(std::memory_order_relaxed) == currentReadPosition && verificator(valueOut) == false) { popWasSuccessful = false; } else { nextReadPosition = currentReadPosition + 1U; popWasSuccessful = true; } } // compare and swap // if(m_readPosition == currentReadPosition) // m_readPosition = l_next_aba_read_pos // else // currentReadPosition = m_readPosition // Assign m_aba_read_p to next readable location } while (!m_readPosition.compare_exchange_weak( currentReadPosition, nextReadPosition, std::memory_order_acq_rel, std::memory_order_acquire)); return popWasSuccessful; } template <class ValueType, uint32_t CapacityValue> bool SoFi<ValueType, CapacityValue>::push(const ValueType& valueOut, ValueType& f_paramOut_r) noexcept { constexpr bool SOFI_OVERFLOW{false}; uint64_t currentWritePosition = m_writePosition.load(std::memory_order_relaxed); uint64_t nextWritePosition = currentWritePosition + 1U; m_data[static_cast<int32_t>(currentWritePosition) % m_size] = valueOut; m_writePosition.store(nextWritePosition, std::memory_order_release); uint64_t currentReadPosition = m_readPosition.load(std::memory_order_acquire); // check if there is a free position for the next push if (nextWritePosition < currentReadPosition + m_size) { return !SOFI_OVERFLOW; } // this is an overflow situation, which means that the next push has no free position, therefore the oldest value // needs to be passed back to the caller uint64_t nextReadPosition = currentReadPosition + 1U; // we need to update the read position // a) it works, then we need to pass the overflow value back // b) it doesn't work, which means that the pop thread already took the value in the meantime an no further action // is required // memory order success is memory_order_acq_rel // - this is to prevent the reordering of m_writePosition.store(...) after the increment of the m_readPosition // - in case of an overflow, this might result in the pop thread getting one element less than the capacity of // the SoFi if the push thread is suspended in between this two statements // - it's still possible to get more elements than the capacity, but this is an inherent issue with concurrent // queues and cannot be prevented since there can always be a push during a pop operation // - another issue might be that two consecutive pushes (not concurrent) happen on different CPU cores without // synchronization, then the memory also needs to be synchronized for the overflow case // memory order failure is memory_order_relaxed since there is no further synchronization needed if there is no // overflow if (m_readPosition.compare_exchange_strong( currentReadPosition, nextReadPosition, std::memory_order_acq_rel, std::memory_order_relaxed)) { std::memcpy(&f_paramOut_r, &m_data[static_cast<int32_t>(currentReadPosition) % m_size], sizeof(ValueType)); return SOFI_OVERFLOW; } return !SOFI_OVERFLOW; } } // namespace concurrent } // namespace iox <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow 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. ==============================================================================*/ #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #include "tensorflow/core/kernels/cwise_ops_gpu_common.cu.h" namespace tensorflow { namespace functor { #if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED) DEFINE_BINARY2(zeta, float, double); #endif DEFINE_BINARY2(polygamma, float, double); } // namespace functor } // namespace tensorflow #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM <commit_msg>Only define functor for Polygamma on GPUs if MLIR generated kernels are disabled.<commit_after>/* Copyright 2015 The TensorFlow 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. ==============================================================================*/ #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM #include "tensorflow/core/kernels/cwise_ops_gpu_common.cu.h" namespace tensorflow { namespace functor { #if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED) DEFINE_BINARY2(zeta, float, double); DEFINE_BINARY2(polygamma, float, double); #endif } // namespace functor } // namespace tensorflow #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM <|endoftext|>
<commit_before>// Copyright 2015-2016 Zuse Institute Berlin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SCALARIS_REQUESTLIST_HPP #define SCALARIS_REQUESTLIST_HPP #include <iostream> #include <string> #include <stdexcept> #include <boost/asio.hpp> #include "json/json.h" namespace scalaris { class RequestList { Json::Value reqlist; bool _is_commit = false; public: RequestList() : reqlist(Json::arrayValue) {} void add_read(const std::string key) { Json::Value read_request = { Json::objectValue }; read_request["read"] = key; reqlist.append(read_request); } void add_write(const std::string key, const std::string value) { Json::Value write_op = { Json::objectValue }; write_op[key] = as_is(value); Json::Value write_request = { Json::objectValue }; write_request["write"] = write_op; reqlist.append(write_request); } void add_commit() { Json::Value commit_request = { Json::objectValue }; commit_request["commit"] = ""; reqlist.append(commit_request); _is_commit = true; } bool is_commit() { return _is_commit; } bool is_empty() { return _is_commit; } int size() { return reqlist.size(); } Json::Value get_json_value() const { return reqlist; } private: Json::Value as_is(const std::string& val) { Json::Value result = { Json::objectValue }; result["type"] = "as_is"; result["value"] = val; return result; } }; } #endif <commit_msg>cpp: add missing include<commit_after>// Copyright 2015-2018 Zuse Institute Berlin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SCALARIS_REQUESTLIST_HPP #define SCALARIS_REQUESTLIST_HPP #include <iostream> #include <string> #include <stdexcept> #include <sys/time.h> // clang modules #include <boost/asio.hpp> #include "json/json.h" namespace scalaris { class RequestList { Json::Value reqlist; bool _is_commit = false; public: RequestList() : reqlist(Json::arrayValue) {} void add_read(const std::string key) { Json::Value read_request = { Json::objectValue }; read_request["read"] = key; reqlist.append(read_request); } void add_write(const std::string key, const std::string value) { Json::Value write_op = { Json::objectValue }; write_op[key] = as_is(value); Json::Value write_request = { Json::objectValue }; write_request["write"] = write_op; reqlist.append(write_request); } void add_commit() { Json::Value commit_request = { Json::objectValue }; commit_request["commit"] = ""; reqlist.append(commit_request); _is_commit = true; } bool is_commit() { return _is_commit; } bool is_empty() { return _is_commit; } int size() { return reqlist.size(); } Json::Value get_json_value() const { return reqlist; } private: Json::Value as_is(const std::string& val) { Json::Value result = { Json::objectValue }; result["type"] = "as_is"; result["value"] = val; return result; } }; } #endif <|endoftext|>
<commit_before>#include "process.h" #include "timing.h" #include "database.h" #include "shop.h" #include "parse.h" #include "faction.h" #include "extern.h" #include "toggle.h" #include "guild.h" #include "being.h" #include <sys/shm.h> #include <sys/ipc.h> /////////// // procFactoryProduction procFactoryProduction::procFactoryProduction(const int &p) { trigger_pulse=p; name="procFactoryProduction"; } void procFactoryProduction::run(const TPulse &) const { TDatabase db(DB_SNEEZY); db.query("select distinct shop_nr from factoryproducing"); while(db.fetchRow()){ factoryProduction(convertTo<int>(db["shop_nr"])); } } // procSaveFactions procSaveFactions::procSaveFactions(const int &p) { trigger_pulse=p; name="procSaveFactions"; } void procSaveFactions::run(const TPulse &) const { save_factions(); } // procSaveNewFactions procSaveNewFactions::procSaveNewFactions(const int &p) { trigger_pulse=p; name="procSaveNewFactions"; } void procSaveNewFactions::run(const TPulse &) const { save_guilds(); } // procDoComponents procDoComponents::procDoComponents(const int &p) { trigger_pulse=p; name="procDoComponents"; } void procDoComponents::run(const TPulse &) const { do_components(-1); } // procPerformViolence procPerformViolence::procPerformViolence(const int &p) { trigger_pulse=p; name="procPerformViolence"; } void procPerformViolence::run(const TPulse &pl) const { perform_violence(pl.pulse); } /////// bool TBaseProcess::should_run(int p) const { if(!(p % trigger_pulse)) return true; else return false; } void TScheduler::add(TProcess *p) { procs.push_back(p); } void TScheduler::add(TObjProcess *p) { obj_procs.push_back(p); } void TScheduler::add(TCharProcess *p) { char_procs.push_back(p); } TScheduler::TScheduler(){ pulse.init(0); placeholder=read_object(42, VIRTUAL); // don't think we can recover from this mud_assert(placeholder!=NULL, "couldn't load placeholder object"); mud_assert(real_roomp(0) != NULL, "couldn't load room 0"); *(real_roomp(0)) += *placeholder; objIter=find(object_list.begin(), object_list.end(), placeholder); tmp_ch=NULL; } void TScheduler::runObj(int pulseNum) { int count; TObj *obj; // we want to go through 1/12th of the object list every pulse // obviously the object count will change, so this is approximate. count=(int)((float)objCount/11.5); while(count--){ // remove placeholder from object list and increment iterator object_list.erase(objIter++); // set object to be processed obj=(*objIter); // move to front of list if we reach the end // otherwise just stick the placeholder in if(++objIter == object_list.end()){ object_list.push_front(placeholder); objIter=object_list.begin(); } else { object_list.insert(objIter, placeholder); --objIter; } for(std::vector<TObjProcess *>::iterator iter=obj_procs.begin(); iter!=obj_procs.end();++iter){ if((*iter)->should_run(pulse.pulse)){ if((*iter)->run(pulse, obj)){ delete obj; break; } } } } } void TScheduler::runChar(int pulseNum) { TBeing *temp; int count; // we've already finished going through the character list, so start over if(!tmp_ch) tmp_ch=character_list; count=max((int)((float)mobCount/11.5), 1); for (; tmp_ch; tmp_ch = temp) { temp = tmp_ch->next; // just for safety if (tmp_ch->roomp == NULL || tmp_ch->getName().empty()) { vlogf(LOG_BUG, "Error: character_list contains a bogus item, removing."); tmp_ch = temp; temp = temp->next; } if(!count--) break; if (tmp_ch->getPosition() == POSITION_DEAD) { assert(tmp_ch); // I suppose this guy exists if we have already dereferenced it // even if shortDescr is NULL. vlogf(LOG_BUG, format("Error: dead creature (%s at %d) in character_list, removing.") % tmp_ch->getName() % tmp_ch->in_room); delete tmp_ch; continue; } if ((tmp_ch->getPosition() < POSITION_STUNNED) && (tmp_ch->getHit() > 0)) { vlogf(LOG_BUG, format("Error: creature (%s) with hit > 0 found with position < stunned") % tmp_ch->getName()); vlogf(LOG_BUG, "Setting player to POSITION_STANDING"); tmp_ch->setPosition(POSITION_STANDING); } for(TCharProcess *char_proc : char_procs) { if(char_proc->should_run(pulse.pulse)){ if(char_proc->run(pulse, tmp_ch)){ delete tmp_ch; break; } } } temp = tmp_ch->next; // just for safety } } void TScheduler::run(int pulseNum) { pulse.init(pulseNum); // run general processes for(TProcess* proc : procs) { if(proc->should_run(pulse.pulse)){ proc->run(pulse); } } pulse.init12(pulseNum); // run object processes runObj(pulseNum); // run character processes runChar(pulseNum); pulse.init(pulseNum); } procSeedRandom::procSeedRandom(const int &p) { trigger_pulse=p; name="procSeedRandom"; } void procSeedRandom::run(const TPulse &) const { srand(time(0)); vlogf(LOG_SILENT, "procSeedRandom: Generated new seed."); } <commit_msg>Fixed crash: objprocs' deleting objects invalidating iterators<commit_after>#include "process.h" #include "timing.h" #include "database.h" #include "shop.h" #include "parse.h" #include "faction.h" #include "extern.h" #include "toggle.h" #include "guild.h" #include "being.h" #include <sys/shm.h> #include <sys/ipc.h> /////////// // procFactoryProduction procFactoryProduction::procFactoryProduction(const int &p) { trigger_pulse=p; name="procFactoryProduction"; } void procFactoryProduction::run(const TPulse &) const { TDatabase db(DB_SNEEZY); db.query("select distinct shop_nr from factoryproducing"); while(db.fetchRow()){ factoryProduction(convertTo<int>(db["shop_nr"])); } } // procSaveFactions procSaveFactions::procSaveFactions(const int &p) { trigger_pulse=p; name="procSaveFactions"; } void procSaveFactions::run(const TPulse &) const { save_factions(); } // procSaveNewFactions procSaveNewFactions::procSaveNewFactions(const int &p) { trigger_pulse=p; name="procSaveNewFactions"; } void procSaveNewFactions::run(const TPulse &) const { save_guilds(); } // procDoComponents procDoComponents::procDoComponents(const int &p) { trigger_pulse=p; name="procDoComponents"; } void procDoComponents::run(const TPulse &) const { do_components(-1); } // procPerformViolence procPerformViolence::procPerformViolence(const int &p) { trigger_pulse=p; name="procPerformViolence"; } void procPerformViolence::run(const TPulse &pl) const { perform_violence(pl.pulse); } /////// bool TBaseProcess::should_run(int p) const { if(!(p % trigger_pulse)) return true; else return false; } void TScheduler::add(TProcess *p) { procs.push_back(p); } void TScheduler::add(TObjProcess *p) { obj_procs.push_back(p); } void TScheduler::add(TCharProcess *p) { char_procs.push_back(p); } TScheduler::TScheduler(){ pulse.init(0); placeholder=read_object(42, VIRTUAL); // don't think we can recover from this mud_assert(placeholder!=NULL, "couldn't load placeholder object"); mud_assert(real_roomp(0) != NULL, "couldn't load room 0"); *(real_roomp(0)) += *placeholder; objIter=find(object_list.begin(), object_list.end(), placeholder); tmp_ch=NULL; } void TScheduler::runObj(int pulseNum) { int count; TObj *obj; // we want to go through 1/12th of the object list every pulse // obviously the object count will change, so this is approximate. count=(int)((float)objCount/11.5); while(count--){ // remove placeholder from object list and increment iterator object_list.erase(objIter++); // set object to be processed obj=(*objIter); // move to front of list if we reach the end // otherwise just stick the placeholder in if(++objIter == object_list.end()){ object_list.push_front(placeholder); objIter=object_list.begin(); } else { object_list.insert(objIter, placeholder); --objIter; } bool invalidated = false; for(std::vector<TObjProcess *>::iterator iter=obj_procs.begin(); iter!=obj_procs.end();++iter){ if((*iter)->should_run(pulse.pulse)){ if((*iter)->run(pulse, obj)){ delete obj; invalidated = true; break; } } } if (invalidated) { auto newObjIter = find(object_list.begin(), object_list.end(), placeholder); if (objIter != newObjIter) objIter = newObjIter; } } } void TScheduler::runChar(int pulseNum) { TBeing *temp; int count; // we've already finished going through the character list, so start over if(!tmp_ch) tmp_ch=character_list; count=max((int)((float)mobCount/11.5), 1); for (; tmp_ch; tmp_ch = temp) { temp = tmp_ch->next; // just for safety if (tmp_ch->roomp == NULL || tmp_ch->getName().empty()) { vlogf(LOG_BUG, "Error: character_list contains a bogus item, removing."); tmp_ch = temp; temp = temp->next; } if(!count--) break; if (tmp_ch->getPosition() == POSITION_DEAD) { assert(tmp_ch); // I suppose this guy exists if we have already dereferenced it // even if shortDescr is NULL. vlogf(LOG_BUG, format("Error: dead creature (%s at %d) in character_list, removing.") % tmp_ch->getName() % tmp_ch->in_room); delete tmp_ch; continue; } if ((tmp_ch->getPosition() < POSITION_STUNNED) && (tmp_ch->getHit() > 0)) { vlogf(LOG_BUG, format("Error: creature (%s) with hit > 0 found with position < stunned") % tmp_ch->getName()); vlogf(LOG_BUG, "Setting player to POSITION_STANDING"); tmp_ch->setPosition(POSITION_STANDING); } for(TCharProcess *char_proc : char_procs) { if(char_proc->should_run(pulse.pulse)){ if(char_proc->run(pulse, tmp_ch)){ delete tmp_ch; break; } } } temp = tmp_ch->next; // just for safety } } void TScheduler::run(int pulseNum) { pulse.init(pulseNum); // run general processes for(TProcess* proc : procs) { if(proc->should_run(pulse.pulse)){ proc->run(pulse); } } pulse.init12(pulseNum); // run object processes runObj(pulseNum); // run character processes runChar(pulseNum); pulse.init(pulseNum); } procSeedRandom::procSeedRandom(const int &p) { trigger_pulse=p; name="procSeedRandom"; } void procSeedRandom::run(const TPulse &) const { srand(time(0)); vlogf(LOG_SILENT, "procSeedRandom: Generated new seed."); } <|endoftext|>
<commit_before>#include <cassert> #include "ch_frb_io_internals.hpp" using namespace std; using namespace ch_frb_io; inline bool array_contains(const int *arr, int len, int x) { for (int i = 0; i < len; i++) if (arr[i] == x) return true; return false; } inline double intval(int beam_id, int ifreq, int it) { return 0.823*beam_id + 1.319*ifreq + 0.2139*it; } // weights are between 0.2 and 1 inline double wtval(int beam_id, int ifreq, int it) { return 0.6 + 0.4 * sin(1.328*beam_id + 2.382*ifreq + 0.883*it); } // ------------------------------------------------------------------------------------------------- struct unit_test_instance { static constexpr int maxbeams = 8; int nbeams = 0; int nupfreq = 0; int nfreq_coarse_per_packet = 0; int nt_per_packet = 0; int nt_per_chunk = 0; int nt_tot = 0; int fpga_counts_per_sample = 0; uint64_t initial_fpga_count = 0; float wt_cutoff = 0.0; vector<int> recv_beam_ids; vector<int> send_beam_ids; vector<int> send_freq_ids; int send_stride; // not protected by lock pthread_t consumer_threads[maxbeams]; shared_ptr<ch_frb_io::intensity_network_stream> istream; pthread_mutex_t lock; unit_test_instance(std::mt19937 &rng); ~unit_test_instance(); }; unit_test_instance::unit_test_instance(std::mt19937 &rng) { const int nfreq_coarse = ch_frb_io::constants::nfreq_coarse; this->nbeams = randint(rng, 1, maxbeams+1); this->nupfreq = randint(rng, 1, 17); this->nfreq_coarse_per_packet = 1 << randint(rng,0,5); int n3 = nbeams * nfreq_coarse_per_packet * nupfreq; int nt_max = min(512, (8192+n3-1)/n3); // FIXME increase nt_tot this->nt_per_packet = randint(rng, nt_max/2, nt_max+1); this->nt_per_chunk = nt_per_packet * randint(rng,1,5); this->nt_tot = nt_per_chunk * randint(rng,1,5); this->fpga_counts_per_sample = randint(rng, 1, 1025); this->initial_fpga_count = fpga_counts_per_sample * randint(rng, 0, 4097); this->wt_cutoff = uniform_rand(rng, 0.3, 0.7); // Clunky way of generating random beam_ids this->recv_beam_ids.resize(nbeams); for (int i = 0; i < nbeams; i++) { do { recv_beam_ids[i] = randint(rng, 0, ch_frb_io::constants::max_allowed_beam_id); } while (array_contains(&recv_beam_ids[0], i, recv_beam_ids[i])); } // To slightly strengthen the test, we permute the receiver beams relative to sender this->send_beam_ids = recv_beam_ids; std::shuffle(send_beam_ids.begin(), send_beam_ids.end(), rng); // Randomly permute frequencies, just to strengthen the test this->send_freq_ids.resize(nfreq_coarse); for (int i = 0; i < nfreq_coarse; i++) send_freq_ids[i] = i; std::shuffle(send_freq_ids.begin(), send_freq_ids.end(), rng); this->send_stride = randint(rng, nt_per_chunk, 2*nt_per_chunk+1); // Will be needed shortly for synchronization xpthread_mutex_init(&this->lock); } unit_test_instance::~unit_test_instance() { pthread_mutex_destroy(&lock); } // ------------------------------------------------------------------------------------------------- struct consumer_thread_context { shared_ptr<ch_frb_io::intensity_beam_assembler> assembler; shared_ptr<unit_test_instance> tp; pthread_mutex_t lock; pthread_cond_t cond_running; bool is_running = false; consumer_thread_context(const shared_ptr<ch_frb_io::intensity_beam_assembler> &assembler_, const shared_ptr<unit_test_instance> &tp_) : assembler(assembler_), tp(tp_) { xpthread_mutex_init(&lock); xpthread_cond_init(&cond_running); } }; static void *consumer_thread_main(void *opaque_arg) { consumer_thread_context *context = reinterpret_cast<consumer_thread_context *> (opaque_arg); shared_ptr<ch_frb_io::intensity_beam_assembler> assembler = context->assembler; shared_ptr<unit_test_instance> tp = context->tp; pthread_mutex_lock(&context->lock); context->is_running = true; pthread_cond_broadcast(&context->cond_running); pthread_mutex_unlock(&context->lock); // actual logic of the consumer thread goes here cerr << "consumer_thread: artificially exiting\n"; return NULL; } static void spawn_consumer_thread(const shared_ptr<ch_frb_io::intensity_beam_assembler> &assembler, const shared_ptr<unit_test_instance> &tp, int ibeam) { consumer_thread_context context(assembler, tp); int err = pthread_create(&tp->consumer_threads[ibeam], NULL, consumer_thread_main, &context); if (err) throw runtime_error(string("pthread_create() failed to create consumer thread: ") + strerror(errno)); pthread_mutex_lock(&context.lock); while (!context.is_running) pthread_cond_wait(&context.cond_running, &context.lock); pthread_mutex_unlock(&context.lock); } static void spawn_all_receive_threads(const shared_ptr<unit_test_instance> &tp) { vector<shared_ptr<ch_frb_io::intensity_beam_assembler> > assemblers; for (int ibeam = 0; ibeam < tp->nbeams; ibeam++) { auto assembler = ch_frb_io::intensity_beam_assembler::make(tp->recv_beam_ids[ibeam]); spawn_consumer_thread(assembler, tp, ibeam); assemblers.push_back(assembler); } tp->istream = intensity_network_stream::make(assemblers, ch_frb_io::constants::default_udp_port); } // ------------------------------------------------------------------------------------------------- static void send_data(const shared_ptr<unit_test_instance> &tp) { const int nbeams = tp->nbeams; const int nupfreq = tp->nupfreq; const int nfreq_coarse = ch_frb_io::constants::nfreq_coarse; const int nt_chunk = tp->nt_per_chunk; const int nchunks = tp->nt_tot / tp->nt_per_chunk; const int stride = tp->send_stride; const int s2 = nupfreq * stride; const int s3 = nfreq_coarse * s2; string dstname = "127.0.0.1:" + to_string(ch_frb_io::constants::default_udp_port); // spawns network thread auto ostream = intensity_network_ostream::make(dstname, tp->send_beam_ids, tp->send_freq_ids, tp->nupfreq, tp->nt_per_chunk, tp->nfreq_coarse_per_packet, tp->nt_per_packet, tp->fpga_counts_per_sample, tp->wt_cutoff, 0.0); vector<float> intensity(nbeams * s3, 0.0); vector<float> weights(nbeams * s3, 0.0); for (int ichunk = 0; ichunk < nchunks; ichunk++) { int it0 = ichunk * nt_chunk; // start of chunk for (int ibeam = 0; ibeam < nbeams; ibeam++) { int beam_id = tp->send_beam_ids[ibeam]; for (int ifreq_coarse = 0; ifreq_coarse < nfreq_coarse; ifreq_coarse++) { int coarse_freq_id = tp->send_freq_ids[ifreq_coarse]; for (int iupfreq = 0; iupfreq < nupfreq; iupfreq++) { int ifreq_logical = coarse_freq_id * nupfreq + iupfreq; int row_start = beam_id*s3 + ifreq_coarse*s2 + iupfreq*stride; float *i_row = &intensity[row_start]; float *w_row = &weights[row_start]; for (int it = 0; it < nt_chunk; it++) { i_row[it] = intval(beam_id, ifreq_logical, it+it0); w_row[it] = wtval(beam_id, ifreq_logical, it+it0); } } } } uint64_t fpga_count = tp->initial_fpga_count + ichunk * nt_chunk * tp->fpga_counts_per_sample; ostream->send_chunk(&intensity[0], &weights[0], stride, fpga_count, true); } // joins network thread ostream->end_stream(true); } // ------------------------------------------------------------------------------------------------- int main(int argc, char **argv) { std::random_device rd; std::mt19937 rng(rd()); for (int iouter = 0; iouter < 1; iouter++) { auto tp = make_shared<unit_test_instance> (rng); spawn_all_receive_threads(tp); tp->istream->start_stream(); send_data(tp); tp->istream->end_stream(true); // join_threads=true for (int ibeam = 0; ibeam < tp->nbeams; ibeam++) { int err = pthread_join(tp->consumer_threads[ibeam], NULL); if (err) throw runtime_error("pthread_join() failed"); } } return 0; } <commit_msg>fix nt_per_packet logic in unit test<commit_after>#include <cassert> #include "ch_frb_io_internals.hpp" using namespace std; using namespace ch_frb_io; inline bool array_contains(const int *arr, int len, int x) { for (int i = 0; i < len; i++) if (arr[i] == x) return true; return false; } inline double intval(int beam_id, int ifreq, int it) { return 0.823*beam_id + 1.319*ifreq + 0.2139*it; } // weights are between 0.2 and 1 inline double wtval(int beam_id, int ifreq, int it) { return 0.6 + 0.4 * sin(1.328*beam_id + 2.382*ifreq + 0.883*it); } // ------------------------------------------------------------------------------------------------- struct unit_test_instance { static constexpr int maxbeams = 8; int nbeams = 0; int nupfreq = 0; int nfreq_coarse_per_packet = 0; int nt_per_packet = 0; int nt_per_chunk = 0; int nt_tot = 0; int fpga_counts_per_sample = 0; uint64_t initial_fpga_count = 0; float wt_cutoff = 0.0; vector<int> recv_beam_ids; vector<int> send_beam_ids; vector<int> send_freq_ids; int send_stride; // not protected by lock pthread_t consumer_threads[maxbeams]; shared_ptr<ch_frb_io::intensity_network_stream> istream; pthread_mutex_t lock; unit_test_instance(std::mt19937 &rng); ~unit_test_instance(); }; unit_test_instance::unit_test_instance(std::mt19937 &rng) { const int nfreq_coarse = ch_frb_io::constants::nfreq_coarse; this->nbeams = randint(rng, 1, maxbeams+1); this->nupfreq = randint(rng, 1, 17); this->nfreq_coarse_per_packet = 1 << randint(rng,0,5); // nt_max = max possible nt_per_packet (before max packet size is exceeded) int header_nbytes = 24 + 2*nbeams + 2*nfreq_coarse_per_packet + 8*nbeams*nfreq_coarse_per_packet; int nbytes_per_nt = nbeams * nfreq_coarse_per_packet * nupfreq; int nt_max = (ch_frb_io::constants::max_output_udp_packet_size - header_nbytes) / nbytes_per_nt; assert(nt_max >= 3); this->nt_per_packet = randint(rng, nt_max/2+1, nt_max+1); // FIXME increase nt_tot this->nt_per_chunk = nt_per_packet * randint(rng,1,5); this->nt_tot = nt_per_chunk * randint(rng,1,5); this->fpga_counts_per_sample = randint(rng, 1, 1025); this->initial_fpga_count = fpga_counts_per_sample * randint(rng, 0, 4097); this->wt_cutoff = uniform_rand(rng, 0.3, 0.7); // Clunky way of generating random beam_ids this->recv_beam_ids.resize(nbeams); for (int i = 0; i < nbeams; i++) { do { recv_beam_ids[i] = randint(rng, 0, ch_frb_io::constants::max_allowed_beam_id); } while (array_contains(&recv_beam_ids[0], i, recv_beam_ids[i])); } // To slightly strengthen the test, we permute the receiver beams relative to sender this->send_beam_ids = recv_beam_ids; std::shuffle(send_beam_ids.begin(), send_beam_ids.end(), rng); // Randomly permute frequencies, just to strengthen the test this->send_freq_ids.resize(nfreq_coarse); for (int i = 0; i < nfreq_coarse; i++) send_freq_ids[i] = i; std::shuffle(send_freq_ids.begin(), send_freq_ids.end(), rng); this->send_stride = randint(rng, nt_per_chunk, 2*nt_per_chunk+1); // Will be needed shortly for synchronization xpthread_mutex_init(&this->lock); } unit_test_instance::~unit_test_instance() { pthread_mutex_destroy(&lock); } // ------------------------------------------------------------------------------------------------- struct consumer_thread_context { shared_ptr<ch_frb_io::intensity_beam_assembler> assembler; shared_ptr<unit_test_instance> tp; pthread_mutex_t lock; pthread_cond_t cond_running; bool is_running = false; consumer_thread_context(const shared_ptr<ch_frb_io::intensity_beam_assembler> &assembler_, const shared_ptr<unit_test_instance> &tp_) : assembler(assembler_), tp(tp_) { xpthread_mutex_init(&lock); xpthread_cond_init(&cond_running); } }; static void *consumer_thread_main(void *opaque_arg) { consumer_thread_context *context = reinterpret_cast<consumer_thread_context *> (opaque_arg); shared_ptr<ch_frb_io::intensity_beam_assembler> assembler = context->assembler; shared_ptr<unit_test_instance> tp = context->tp; pthread_mutex_lock(&context->lock); context->is_running = true; pthread_cond_broadcast(&context->cond_running); pthread_mutex_unlock(&context->lock); // actual logic of the consumer thread goes here cerr << "consumer_thread: artificially exiting\n"; return NULL; } static void spawn_consumer_thread(const shared_ptr<ch_frb_io::intensity_beam_assembler> &assembler, const shared_ptr<unit_test_instance> &tp, int ibeam) { consumer_thread_context context(assembler, tp); int err = pthread_create(&tp->consumer_threads[ibeam], NULL, consumer_thread_main, &context); if (err) throw runtime_error(string("pthread_create() failed to create consumer thread: ") + strerror(errno)); pthread_mutex_lock(&context.lock); while (!context.is_running) pthread_cond_wait(&context.cond_running, &context.lock); pthread_mutex_unlock(&context.lock); } static void spawn_all_receive_threads(const shared_ptr<unit_test_instance> &tp) { vector<shared_ptr<ch_frb_io::intensity_beam_assembler> > assemblers; for (int ibeam = 0; ibeam < tp->nbeams; ibeam++) { auto assembler = ch_frb_io::intensity_beam_assembler::make(tp->recv_beam_ids[ibeam]); spawn_consumer_thread(assembler, tp, ibeam); assemblers.push_back(assembler); } tp->istream = intensity_network_stream::make(assemblers, ch_frb_io::constants::default_udp_port); } // ------------------------------------------------------------------------------------------------- static void send_data(const shared_ptr<unit_test_instance> &tp) { const int nbeams = tp->nbeams; const int nupfreq = tp->nupfreq; const int nfreq_coarse = ch_frb_io::constants::nfreq_coarse; const int nt_chunk = tp->nt_per_chunk; const int nchunks = tp->nt_tot / tp->nt_per_chunk; const int stride = tp->send_stride; const int s2 = nupfreq * stride; const int s3 = nfreq_coarse * s2; string dstname = "127.0.0.1:" + to_string(ch_frb_io::constants::default_udp_port); // spawns network thread auto ostream = intensity_network_ostream::make(dstname, tp->send_beam_ids, tp->send_freq_ids, tp->nupfreq, tp->nt_per_chunk, tp->nfreq_coarse_per_packet, tp->nt_per_packet, tp->fpga_counts_per_sample, tp->wt_cutoff, 0.0); vector<float> intensity(nbeams * s3, 0.0); vector<float> weights(nbeams * s3, 0.0); for (int ichunk = 0; ichunk < nchunks; ichunk++) { int it0 = ichunk * nt_chunk; // start of chunk for (int ibeam = 0; ibeam < nbeams; ibeam++) { int beam_id = tp->send_beam_ids[ibeam]; for (int ifreq_coarse = 0; ifreq_coarse < nfreq_coarse; ifreq_coarse++) { int coarse_freq_id = tp->send_freq_ids[ifreq_coarse]; for (int iupfreq = 0; iupfreq < nupfreq; iupfreq++) { int ifreq_logical = coarse_freq_id * nupfreq + iupfreq; int row_start = beam_id*s3 + ifreq_coarse*s2 + iupfreq*stride; float *i_row = &intensity[row_start]; float *w_row = &weights[row_start]; for (int it = 0; it < nt_chunk; it++) { i_row[it] = intval(beam_id, ifreq_logical, it+it0); w_row[it] = wtval(beam_id, ifreq_logical, it+it0); } } } } uint64_t fpga_count = tp->initial_fpga_count + ichunk * nt_chunk * tp->fpga_counts_per_sample; ostream->send_chunk(&intensity[0], &weights[0], stride, fpga_count, true); } // joins network thread ostream->end_stream(true); } // ------------------------------------------------------------------------------------------------- int main(int argc, char **argv) { std::random_device rd; std::mt19937 rng(rd()); for (int iouter = 0; iouter < 1; iouter++) { auto tp = make_shared<unit_test_instance> (rng); spawn_all_receive_threads(tp); tp->istream->start_stream(); send_data(tp); tp->istream->end_stream(true); // join_threads=true for (int ibeam = 0; ibeam < tp->nbeams; ibeam++) { int err = pthread_join(tp->consumer_threads[ibeam], NULL); if (err) throw runtime_error("pthread_join() failed"); } } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "bilininteg.hpp" #include "pfespace.hpp" #include <algorithm> namespace mfem { DGDiffusionBR2Integrator::DGDiffusionBR2Integrator(FiniteElementSpace *fes, double e) : eta(e) { // Precompute local mass matrix inverses needed for the lifting operators // First compute offsets and total size needed (e.g. for mixed meshes or // p-refinement) int nel = fes->GetNE(); Minv_offsets.SetSize(nel+1); ipiv_offsets.SetSize(nel+1); ipiv_offsets[0] = 0; Minv_offsets[0] = 0; for (int i=0; i<nel; ++i) { int dof = fes->GetFE(i)->GetDof(); ipiv_offsets[i+1] = ipiv_offsets[i] + dof; Minv_offsets[i+1] = Minv_offsets[i] + dof*dof; } #ifdef MFEM_USE_MPI // When running in parallel, we also need to compute the local mass matrices // of face neighbor elements ParFiniteElementSpace *pfes = dynamic_cast<ParFiniteElementSpace *>(fes); if (pfes != NULL) { ParMesh *pmesh = pfes->GetParMesh(); pfes->ExchangeFaceNbrData(); int nel_nbr = pmesh->GetNFaceNeighborElements(); Minv_offsets.SetSize(nel+nel_nbr+1); ipiv_offsets.SetSize(nel+nel_nbr+1); for (int i=0; i<nel_nbr; ++i) { int dof = pfes->GetFaceNbrFE(i)->GetDof(); ipiv_offsets[nel+i+1] = ipiv_offsets[nel+i] + dof; Minv_offsets[nel+i+1] = Minv_offsets[nel+i] + dof*dof; } nel += nel_nbr; } #endif // The final "offset" is the total size of all the blocks Minv.SetSize(Minv_offsets[nel]); ipiv.SetSize(ipiv_offsets[nel]); // Assemble the local mass matrices and compute LU factorization MassIntegrator mi; for (int i=0; i<nel; ++i) { const FiniteElement *fe = NULL; ElementTransformation *tr = NULL; IsoparametricTransformation iso_tr; if (i < fes->GetNE()) { fe = fes->GetFE(i); tr = fes->GetElementTransformation(i); } else { #ifdef MFEM_USE_MPI int inbr = i - fes->GetNE(); fe = pfes->GetFaceNbrFE(inbr); pfes->GetParMesh()->GetFaceNbrElementTransformation(inbr, &iso_tr); tr = &iso_tr; #endif } int dof = fe->GetDof(); double *Minv_el = &Minv[Minv_offsets[i]]; int *ipiv_el = &ipiv[ipiv_offsets[i]]; DenseMatrix Me(Minv_el, dof, dof); mi.AssembleElementMatrix(*fe, *tr, Me); LUFactors lu(Minv_el, ipiv_el); lu.Factor(dof); } } void DGDiffusionBR2Integrator::AssembleFaceMatrix( const FiniteElement &el1, const FiniteElement &el2, FaceElementTransformations &Trans, DenseMatrix &elmat) { int ndof1 = el1.GetDof(); shape1.SetSize(ndof1); R11.SetSize(ndof1, ndof1); R11 = 0.0; LUFactors M1inv(&Minv[Minv_offsets[Trans.Elem1No]], &ipiv[ipiv_offsets[Trans.Elem1No]]); LUFactors M2inv; double factor = Geometries.NumBdr(Trans.Elem1->GetGeometryType()); int ndof2; if (Trans.Elem2No >= 0) { ndof2 = el2.GetDof(); shape2.SetSize(ndof2); R12.SetSize(ndof1, ndof2); R21.SetSize(ndof2, ndof1); R22.SetSize(ndof2, ndof2); M2inv.data = &Minv[Minv_offsets[Trans.Elem2->ElementNo]]; M2inv.ipiv = &ipiv[ipiv_offsets[Trans.Elem2->ElementNo]]; R12 = 0.0; R21 = 0.0; R22 = 0.0; factor = std::max(factor, double(Geometries.NumBdr(Trans.Elem2->GetGeometryType()))); } else { ndof2 = 0; } int ndofs = ndof1 + ndof2; Re.SetSize(ndofs, ndofs); MinvRe.SetSize(ndofs, ndofs); elmat.SetSize(ndofs); elmat = 0.0; const IntegrationRule *ir = IntRule; if (ir == NULL) { int order; if (ndof2) { order = 2*std::max(el1.GetOrder(), el2.GetOrder()); } else { order = 2*el1.GetOrder(); } ir = &IntRules.Get(Trans.FaceGeom, order); } for (int p = 0; p < ir->GetNPoints(); p++) { const IntegrationPoint &ip = ir->IntPoint(p); IntegrationPoint eip1, eip2; Trans.Loc1.Transform(ip, eip1); el1.CalcShape(eip1, shape1); if (ndof2) { Trans.Loc2.Transform(ip, eip2); el2.CalcShape(eip2, shape2); } double w = factor*sqrt(eta)*ip.weight*Trans.Face->Weight(); if (ndof2) { w /= 2; } // Create matrices corresponding to term <[u]{v}> for (int i = 0; i < ndof1; i++) { const double wsi = w*shape1(i); for (int j = 0; j < ndof1; j++) { R11(i, j) += wsi*shape1(j); } } if (ndof2) { for (int i = 0; i < ndof2; i++) { const double wsi = w*shape2(i); for (int j = 0; j < ndof1; j++) { R21(i, j) += wsi*shape1(j); R12(j, i) -= wsi*shape1(j); } for (int j = 0; j < ndof2; j++) { R22(i, j) -= wsi*shape2(j); } } } } MinvR11 = R11; M1inv.Solve(ndof1, ndof1, MinvR11.Data()); for (int i = 0; i < ndof1; i++) { for (int j = 0; j < ndof1; j++) { Re(i, j) = R11(i, j); MinvRe(i, j) = MinvR11(i, j); } } if (ndof2) { MinvR12 = R12; MinvR21 = R21; MinvR22 = R22; M1inv.Solve(ndof1, ndof2, MinvR12.Data()); M2inv.Solve(ndof2, ndof1, MinvR21.Data()); M2inv.Solve(ndof2, ndof2, MinvR22.Data()); for (int i = 0; i < ndof2; i++) { for (int j = 0; j < ndof1; j++) { Re(ndof1 + i, j) = R21(i, j); MinvRe(ndof1 + i, j) = MinvR21(i, j); Re(j, ndof1 + i) = R12(j, i); MinvRe(j, ndof1 + i) = MinvR12(j, i); } for (int j = 0; j < ndof2; j++) { Re(ndof1 + i, ndof1 + j) = R22(i, j); MinvRe(ndof1 + i, ndof1 + j) = MinvR22(i, j); } } } // Compute the matrix associated with (r_e([u]), r_e([u])). // The matrix for r_e([u]) is `MinvRe`, and so we need to form the product // `MinvRe^T M MinvRe`. Cancelling Minv and M, we obtain `Re^T M MinvRe`. MultAtB(Re, MinvRe, elmat); } } <commit_msg>Update BR2 integrator with latest master changes<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "bilininteg.hpp" #include "pfespace.hpp" #include <algorithm> namespace mfem { DGDiffusionBR2Integrator::DGDiffusionBR2Integrator(FiniteElementSpace *fes, double e) : eta(e) { // Precompute local mass matrix inverses needed for the lifting operators // First compute offsets and total size needed (e.g. for mixed meshes or // p-refinement) int nel = fes->GetNE(); Minv_offsets.SetSize(nel+1); ipiv_offsets.SetSize(nel+1); ipiv_offsets[0] = 0; Minv_offsets[0] = 0; for (int i=0; i<nel; ++i) { int dof = fes->GetFE(i)->GetDof(); ipiv_offsets[i+1] = ipiv_offsets[i] + dof; Minv_offsets[i+1] = Minv_offsets[i] + dof*dof; } #ifdef MFEM_USE_MPI // When running in parallel, we also need to compute the local mass matrices // of face neighbor elements ParFiniteElementSpace *pfes = dynamic_cast<ParFiniteElementSpace *>(fes); if (pfes != NULL) { ParMesh *pmesh = pfes->GetParMesh(); pfes->ExchangeFaceNbrData(); int nel_nbr = pmesh->GetNFaceNeighborElements(); Minv_offsets.SetSize(nel+nel_nbr+1); ipiv_offsets.SetSize(nel+nel_nbr+1); for (int i=0; i<nel_nbr; ++i) { int dof = pfes->GetFaceNbrFE(i)->GetDof(); ipiv_offsets[nel+i+1] = ipiv_offsets[nel+i] + dof; Minv_offsets[nel+i+1] = Minv_offsets[nel+i] + dof*dof; } nel += nel_nbr; } #endif // The final "offset" is the total size of all the blocks Minv.SetSize(Minv_offsets[nel]); ipiv.SetSize(ipiv_offsets[nel]); // Assemble the local mass matrices and compute LU factorization MassIntegrator mi; for (int i=0; i<nel; ++i) { const FiniteElement *fe = NULL; ElementTransformation *tr = NULL; if (i < fes->GetNE()) { fe = fes->GetFE(i); tr = fes->GetElementTransformation(i); } else { #ifdef MFEM_USE_MPI int inbr = i - fes->GetNE(); fe = pfes->GetFaceNbrFE(inbr); tr = pfes->GetParMesh()->GetFaceNbrElementTransformation(inbr); #endif } int dof = fe->GetDof(); double *Minv_el = &Minv[Minv_offsets[i]]; int *ipiv_el = &ipiv[ipiv_offsets[i]]; DenseMatrix Me(Minv_el, dof, dof); mi.AssembleElementMatrix(*fe, *tr, Me); LUFactors lu(Minv_el, ipiv_el); lu.Factor(dof); } } void DGDiffusionBR2Integrator::AssembleFaceMatrix( const FiniteElement &el1, const FiniteElement &el2, FaceElementTransformations &Trans, DenseMatrix &elmat) { int ndof1 = el1.GetDof(); shape1.SetSize(ndof1); R11.SetSize(ndof1, ndof1); R11 = 0.0; LUFactors M1inv(&Minv[Minv_offsets[Trans.Elem1No]], &ipiv[ipiv_offsets[Trans.Elem1No]]); LUFactors M2inv; double factor = Geometries.NumBdr(Trans.Elem1->GetGeometryType()); int ndof2; if (Trans.Elem2No >= 0) { ndof2 = el2.GetDof(); shape2.SetSize(ndof2); R12.SetSize(ndof1, ndof2); R21.SetSize(ndof2, ndof1); R22.SetSize(ndof2, ndof2); M2inv.data = &Minv[Minv_offsets[Trans.Elem2No]]; M2inv.ipiv = &ipiv[ipiv_offsets[Trans.Elem2No]]; R12 = 0.0; R21 = 0.0; R22 = 0.0; factor = std::max(factor, double(Geometries.NumBdr(Trans.Elem2->GetGeometryType()))); } else { ndof2 = 0; } int ndofs = ndof1 + ndof2; Re.SetSize(ndofs, ndofs); MinvRe.SetSize(ndofs, ndofs); elmat.SetSize(ndofs); elmat = 0.0; const IntegrationRule *ir = IntRule; if (ir == NULL) { int order; if (ndof2) { order = 2*std::max(el1.GetOrder(), el2.GetOrder()); } else { order = 2*el1.GetOrder(); } ir = &IntRules.Get(Trans.FaceGeom, order); } for (int p = 0; p < ir->GetNPoints(); p++) { const IntegrationPoint &ip = ir->IntPoint(p); IntegrationPoint eip1, eip2; Trans.Loc1.Transform(ip, eip1); el1.CalcShape(eip1, shape1); if (ndof2) { Trans.Loc2.Transform(ip, eip2); el2.CalcShape(eip2, shape2); } double w = factor*sqrt(eta)*ip.weight*Trans.Face->Weight(); if (ndof2) { w /= 2; } // Create matrices corresponding to term <[u]{v}> for (int i = 0; i < ndof1; i++) { const double wsi = w*shape1(i); for (int j = 0; j < ndof1; j++) { R11(i, j) += wsi*shape1(j); } } if (ndof2) { for (int i = 0; i < ndof2; i++) { const double wsi = w*shape2(i); for (int j = 0; j < ndof1; j++) { R21(i, j) += wsi*shape1(j); R12(j, i) -= wsi*shape1(j); } for (int j = 0; j < ndof2; j++) { R22(i, j) -= wsi*shape2(j); } } } } MinvR11 = R11; M1inv.Solve(ndof1, ndof1, MinvR11.Data()); for (int i = 0; i < ndof1; i++) { for (int j = 0; j < ndof1; j++) { Re(i, j) = R11(i, j); MinvRe(i, j) = MinvR11(i, j); } } if (ndof2) { MinvR12 = R12; MinvR21 = R21; MinvR22 = R22; M1inv.Solve(ndof1, ndof2, MinvR12.Data()); M2inv.Solve(ndof2, ndof1, MinvR21.Data()); M2inv.Solve(ndof2, ndof2, MinvR22.Data()); for (int i = 0; i < ndof2; i++) { for (int j = 0; j < ndof1; j++) { Re(ndof1 + i, j) = R21(i, j); MinvRe(ndof1 + i, j) = MinvR21(i, j); Re(j, ndof1 + i) = R12(j, i); MinvRe(j, ndof1 + i) = MinvR12(j, i); } for (int j = 0; j < ndof2; j++) { Re(ndof1 + i, ndof1 + j) = R22(i, j); MinvRe(ndof1 + i, ndof1 + j) = MinvR22(i, j); } } } // Compute the matrix associated with (r_e([u]), r_e([u])). // The matrix for r_e([u]) is `MinvRe`, and so we need to form the product // `MinvRe^T M MinvRe`. Cancelling Minv and M, we obtain `Re^T M MinvRe`. MultAtB(Re, MinvRe, elmat); } } <|endoftext|>
<commit_before>#include "argument.h" #include "config.h" #include "util.h" #include "menu.h" #include "util/debug.h" #include "game.h" using std::vector; using std::string; using std::endl; namespace Mugen{ static void splitString(const string & subject, char split, string & left, string & right){ size_t find = subject.find(split); if (find != string::npos){ left = subject.substr(0, find); right = subject.substr(find + 1); } } /* static void setMugenMotif(){ / * FIXME: parse the motif properly * / std::string motif; try { *Mugen::Configuration::get("motif") >> motif; } catch (const std::ios_base::failure & ex){ motif.clear(); } if (!motif.empty()){ Mugen::Data::getInstance().setMotif(Filesystem::AbsolutePath(motif)); } else { / * FIXME: search for a system.def file * / Mugen::Data::getInstance().setMotif(Storage::instance().find(Filesystem::RelativePath("mugen/data/system.def"))); / * TokenReader reader; Token * head = reader.readToken(path.path()); const Token * motif = head->findToken("menu/option/mugen/motif"); if (motif != NULL){ string path; motif->view() >> path; Mugen::Data::getInstance().setMotif(Filesystem::RelativePath(path)); } * / } } */ class MugenArgument: public Argument { public: vector<string> keywords() const { vector<string> out; out.push_back("mugen"); out.push_back("--mugen"); return out; } string description() const { return " : Go directly to the mugen menu"; } class Run: public ArgumentAction { public: virtual void act(){ Util::loadMotif(); Mugen::run(); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run())); return current; } }; static bool parseMugenInstant(string input, string * player1, string * player2, string * stage){ size_t comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected three arguments separated by a comma, only 1 was given: " << input << endl; return false; } *player1 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected three arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player2 = input.substr(0, comma); input.erase(0, comma + 1); *stage = input; return true; } /* TODO: refactor this (and the above method) */ static bool parseMugenInstant(string input, string * player1, string * player2, string * player3, string * player4, string * stage){ size_t comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected five arguments separated by a comma, only 1 was given: " << input << endl; return false; } *player1 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected five arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player2 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected five arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player3 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected five arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player4 = input.substr(0, comma); input.erase(0, comma + 1); *stage = input; return true; } struct MugenInstant{ enum Kind{ None, Training, Watch, Arcade, Script, Team }; MugenInstant(): enabled(false), kind(None){ } bool enabled; string player1; string player2; string player3; string player4; string player1Script; string player2Script; string stage; Kind kind; }; class MugenTrainingArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:training"); return out; } string description() const { return " <player 1 name>,<player 2 name>,<stage> : Start training game with the specified players and stage"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen training mode player1 '" << data.player1 << "' player2 '" << data.player2 << "' stage '" << data.stage << "'" << endl; Mugen::Game::startTraining(data.player1, data.player2, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.stage); data.kind = MugenInstant::Training; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:training kfm,ken,falls" << endl; } return current; } }; class MugenScriptArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:script"); return out; } string description() const { return " <player 1 name>:<player 1 script>,<player 2 name>:<player 2 script>,<stage> : Start a scripted mugen game where each player reads its input from the specified scripts"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen scripted mode player1 '" << data.player1 << "' with script '" << data.player1Script << "' player2 '" << data.player2 << "' with script '" << data.player2Script << "' stage '" << data.stage << "'" << endl; Mugen::Game::startScript(data.player1, data.player1Script, data.player2, data.player2Script, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.stage); string player, script; splitString(data.player1, ':', player, script); data.player1 = player; data.player1Script = script; splitString(data.player2, ':', player, script); data.player2 = player; data.player2Script = script; data.kind = MugenInstant::Script; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:script kfm:kfm-script.txt,ken:ken-script.txt,falls" << endl; } return current; } }; class MugenWatchArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:watch"); return out; } string description() const { return " <player 1 name>,<player 2 name>,<stage> : Start watch game with the specified players and stage"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen watch mode player1 '" << data.player1 << "' player2 '" << data.player2 << "' stage '" << data.stage << "'" << endl; Mugen::Game::startWatch(data.player1, data.player2, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.stage); data.kind = MugenInstant::Watch; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:watch kfm,ken,falls" << endl; } return current; } }; class MugenTeamArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:team"); return out; } string description() const { return " <player 1 name>,<player 2 name>,<player 3 name>,<player 4 name>,<stage> : Start watch game with the specified players and stage"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen watch mode player1 '" << data.player1 << "' player2 '" << data.player2 << "' player3 '" << data.player3 << "' player 4 '" << data.player4 << "' stage '" << data.stage << "'" << endl; Mugen::Game::startTeam(data.player1, data.player2, data.player3, data.player4, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.player3, &data.player4, &data.stage); data.kind = MugenInstant::Team; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:team kfm,ken,kfm,kfm,falls" << endl; } return current; } }; class MugenArcadeArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:arcade"); return out; } string description() const { return " <player 1 name>,<player 2 name>,<stage> : Start an arcade mugen game between two players"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen arcade mode player1 '" << data.player1 << "' player2 '" << data.player2 << "' stage '" << data.stage << "'" << endl; Mugen::Game::startArcade(data.player1, data.player2, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.stage); data.kind = MugenInstant::Arcade; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:arcade kfm,ken,falls" << endl; } return current; } }; class MugenServerArgument: public Argument { public: vector<string> keywords() const { vector<string> out; out.push_back("mugen:server"); return out; } string description() const { return " : Start a server on port 8473"; } class Run: public ArgumentAction { public: void act(){ Game::startNetworkVersus("kfm", "kfm", "kfm", true, "localhost", 8473); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run())); return current; } }; class MugenClientArgument: public Argument { public: vector<string> keywords() const { vector<string> out; out.push_back("mugen:client"); return out; } string description() const { return " [host] : Join a server on port 8473"; } class Run: public ArgumentAction { public: Run(const string & host): host(host){ } string host; void act(){ Game::startNetworkVersus("kfm", "kfm", "kfm", false, host, 8473); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ string host = "127.0.0.1"; current++; if (current != end){ host = *current; } actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(host))); return current; } }; std::vector< ::Util::ReferenceCount<Argument> > arguments(){ vector< ::Util::ReferenceCount<Argument> > all; all.push_back(::Util::ReferenceCount<Argument>(new MugenArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenTrainingArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenScriptArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenWatchArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenTeamArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenArcadeArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenServerArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenClientArgument())); return all; } } <commit_msg>[mugen] Added port to client/server arguments.<commit_after>#include "argument.h" #include "config.h" #include "util.h" #include "menu.h" #include "util/debug.h" #include "game.h" using std::vector; using std::string; using std::endl; namespace Mugen{ static void splitString(const string & subject, char split, string & left, string & right){ size_t find = subject.find(split); if (find != string::npos){ left = subject.substr(0, find); right = subject.substr(find + 1); } } /* static void setMugenMotif(){ / * FIXME: parse the motif properly * / std::string motif; try { *Mugen::Configuration::get("motif") >> motif; } catch (const std::ios_base::failure & ex){ motif.clear(); } if (!motif.empty()){ Mugen::Data::getInstance().setMotif(Filesystem::AbsolutePath(motif)); } else { / * FIXME: search for a system.def file * / Mugen::Data::getInstance().setMotif(Storage::instance().find(Filesystem::RelativePath("mugen/data/system.def"))); / * TokenReader reader; Token * head = reader.readToken(path.path()); const Token * motif = head->findToken("menu/option/mugen/motif"); if (motif != NULL){ string path; motif->view() >> path; Mugen::Data::getInstance().setMotif(Filesystem::RelativePath(path)); } * / } } */ class MugenArgument: public Argument { public: vector<string> keywords() const { vector<string> out; out.push_back("mugen"); out.push_back("--mugen"); return out; } string description() const { return " : Go directly to the mugen menu"; } class Run: public ArgumentAction { public: virtual void act(){ Util::loadMotif(); Mugen::run(); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run())); return current; } }; static bool parseMugenInstant(string input, string * player1, string * player2, string * stage){ size_t comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected three arguments separated by a comma, only 1 was given: " << input << endl; return false; } *player1 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected three arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player2 = input.substr(0, comma); input.erase(0, comma + 1); *stage = input; return true; } /* TODO: refactor this (and the above method) */ static bool parseMugenInstant(string input, string * player1, string * player2, string * player3, string * player4, string * stage){ size_t comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected five arguments separated by a comma, only 1 was given: " << input << endl; return false; } *player1 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected five arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player2 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected five arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player3 = input.substr(0, comma); input.erase(0, comma + 1); comma = input.find(','); if (comma == string::npos){ Global::debug(0) << "Expected five arguments separated by a comma, only 2 were given: " << input << endl; return false; } *player4 = input.substr(0, comma); input.erase(0, comma + 1); *stage = input; return true; } struct MugenInstant{ enum Kind{ None, Training, Watch, Arcade, Script, Team }; MugenInstant(): enabled(false), kind(None){ } bool enabled; string player1; string player2; string player3; string player4; string player1Script; string player2Script; string stage; Kind kind; }; class MugenTrainingArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:training"); return out; } string description() const { return " <player 1 name>,<player 2 name>,<stage> : Start training game with the specified players and stage"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen training mode player1 '" << data.player1 << "' player2 '" << data.player2 << "' stage '" << data.stage << "'" << endl; Mugen::Game::startTraining(data.player1, data.player2, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.stage); data.kind = MugenInstant::Training; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:training kfm,ken,falls" << endl; } return current; } }; class MugenScriptArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:script"); return out; } string description() const { return " <player 1 name>:<player 1 script>,<player 2 name>:<player 2 script>,<stage> : Start a scripted mugen game where each player reads its input from the specified scripts"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen scripted mode player1 '" << data.player1 << "' with script '" << data.player1Script << "' player2 '" << data.player2 << "' with script '" << data.player2Script << "' stage '" << data.stage << "'" << endl; Mugen::Game::startScript(data.player1, data.player1Script, data.player2, data.player2Script, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.stage); string player, script; splitString(data.player1, ':', player, script); data.player1 = player; data.player1Script = script; splitString(data.player2, ':', player, script); data.player2 = player; data.player2Script = script; data.kind = MugenInstant::Script; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:script kfm:kfm-script.txt,ken:ken-script.txt,falls" << endl; } return current; } }; class MugenWatchArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:watch"); return out; } string description() const { return " <player 1 name>,<player 2 name>,<stage> : Start watch game with the specified players and stage"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen watch mode player1 '" << data.player1 << "' player2 '" << data.player2 << "' stage '" << data.stage << "'" << endl; Mugen::Game::startWatch(data.player1, data.player2, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.stage); data.kind = MugenInstant::Watch; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:watch kfm,ken,falls" << endl; } return current; } }; class MugenTeamArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:team"); return out; } string description() const { return " <player 1 name>,<player 2 name>,<player 3 name>,<player 4 name>,<stage> : Start watch game with the specified players and stage"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen watch mode player1 '" << data.player1 << "' player2 '" << data.player2 << "' player3 '" << data.player3 << "' player 4 '" << data.player4 << "' stage '" << data.stage << "'" << endl; Mugen::Game::startTeam(data.player1, data.player2, data.player3, data.player4, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.player3, &data.player4, &data.stage); data.kind = MugenInstant::Team; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:team kfm,ken,kfm,kfm,falls" << endl; } return current; } }; class MugenArcadeArgument: public Argument { public: MugenInstant data; vector<string> keywords() const { vector<string> out; out.push_back("mugen:arcade"); return out; } string description() const { return " <player 1 name>,<player 2 name>,<stage> : Start an arcade mugen game between two players"; } class Run: public ArgumentAction { public: Run(MugenInstant data): data(data){ } MugenInstant data; void act(){ Util::loadMotif(); Global::debug(0) << "Mugen arcade mode player1 '" << data.player1 << "' player2 '" << data.player2 << "' stage '" << data.stage << "'" << endl; Mugen::Game::startArcade(data.player1, data.player2, data.stage); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ current++; if (current != end){ data.enabled = parseMugenInstant(*current, &data.player1, &data.player2, &data.stage); data.kind = MugenInstant::Arcade; actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(data))); } else { Global::debug(0) << "Expected an argument. Example: mugen:arcade kfm,ken,falls" << endl; } return current; } }; class MugenServerArgument: public Argument { public: vector<string> keywords() const { vector<string> out; out.push_back("mugen:server"); return out; } string description() const { return " [port] : Start a server on port 8473"; } class Run: public ArgumentAction { public: Run(int port): port(port){ } int port; void act(){ Game::startNetworkVersus("kfm", "kfm", "kfm", true, "localhost", port); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ int port = 8473; current++; if (current != end){ port = atoi((*current).c_str()); } actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(port))); return current; } }; class MugenClientArgument: public Argument { public: vector<string> keywords() const { vector<string> out; out.push_back("mugen:client"); return out; } string description() const { return " [host] [port] : Join a server on port (defaults to 8473)"; } class Run: public ArgumentAction { public: Run(const string & host, int port): host(host), port(port){ } string host; int port; void act(){ Game::startNetworkVersus("kfm", "kfm", "kfm", false, host, port); } }; vector<string>::iterator parse(vector<string>::iterator current, vector<string>::iterator end, ActionRefs & actions){ string host = "127.0.0.1"; int port = 8473; current++; if (current != end){ host = *current; } current++; if (current != end){ port = atoi((*current).c_str()); } actions.push_back(::Util::ReferenceCount<ArgumentAction>(new Run(host, port))); return current; } }; std::vector< ::Util::ReferenceCount<Argument> > arguments(){ vector< ::Util::ReferenceCount<Argument> > all; all.push_back(::Util::ReferenceCount<Argument>(new MugenArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenTrainingArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenScriptArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenWatchArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenTeamArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenArcadeArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenServerArgument())); all.push_back(::Util::ReferenceCount<Argument>(new MugenClientArgument())); return all; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013, "Kira" * 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 "precompiled_headers.hpp" #include "native_command.hpp" #include "logging.hpp" #include "connection.hpp" #include "fjson.hpp" #include "login_evhttp.hpp" #include "server.hpp" #include "startup_config.hpp" #include "server_state.hpp" #include <google/profiler.h> FReturnCode NativeCommand::DebugCommand(ConnectionPtr& con, string& payload) { if (con->admin != true) return FERR_NOT_ADMIN; json_t* topnode = json_loads(payload.c_str(), 0, 0); if (!topnode) return FERR_BAD_SYNTAX; DLOG(INFO) << "Debug event with payload: " << payload; json_t* cmdnode = json_object_get(topnode, "command"); if (!json_is_string(cmdnode)) { json_decref(topnode); return FERR_BAD_SYNTAX; } string command = json_string_value(cmdnode); if (command == "isolate") { if (con->debugL) { con->sendDebugReply("Your connection is already running an isolated Lua state."); } else { string luamessage; FReturnCode isolateret = con->isolateLua(luamessage); if (isolateret == FERR_OK) { con->sendDebugReply("Your connection is now running an isolated Lua state."); } else if (isolateret == FERR_LUA) { string errmsg = "Failed to move your connection into an isolated Lua state. Lua returned the error: " + luamessage; con->sendDebugReply(errmsg); } else { con->sendDebugReply("Failed to move your connection into an isolated Lua state. An unknown error happened."); } } } else if (command == "deisolate") { if (!con->debugL) { con->sendDebugReply("Your connection is not currently running an isolated Lua state."); } else { con->deisolateLua(); con->sendDebugReply("Your connection has been returned to the global Lua state."); } } else if (command == "profile-start") { ProfilerStart("./cpu.out"); } else if (command == "profile-stop") { ProfilerStop(); } else if (command == "logger-start") { Server::loggerStart(); } else if (command == "logger-stop") { Server::loggerStop(); } else if (command == "status") { //TODO: Make this command do something. string statusmessage = "Status: "; if (con->debugL) statusmessage += "Running isolated. "; //statusmessage += "Connected from: "; con->sendDebugReply(statusmessage); } else if (command == "reload") { if (con->debugL) { string luamessage; FReturnCode reloadret = con->reloadIsolation(luamessage); if (reloadret == FERR_OK) { con->sendDebugReply("The isolated Lua state for your connection is now running the latest on disk Lua."); } else if (reloadret == FERR_LUA) { string errormsg = "It was not possible to reload the isolated Lua state for your connection because" " of a Lua error. Lua returned the error: " + luamessage + "\nYou are still running the previous version."; con->sendDebugReply(errormsg); } else { con->sendDebugReply("It was not possible to reload the isolated Lua state for your connection because of an unknown error.\n" "You are still running the previous version." ); } } else { json_t* argnode = json_object_get(topnode, "arg"); if (!json_is_string(argnode)) { json_decref(topnode); return FERR_BAD_SYNTAX; } string arg = json_string_value(argnode); if (arg == "yes") { string luamessage; FReturnCode reloadret = Server::reloadLuaState(luamessage); if (reloadret == FERR_OK) { con->sendDebugReply("The global Lua state has been reloaded."); } else if (reloadret == FERR_LUA) { string errormsg = "It was not possible to reload the global Lua state because of a Lua error. Lua returned the error: " + luamessage + "\nEveryone is still running the previous version."; con->sendDebugReply(errormsg); } else { con->sendDebugReply("It was not possible to reload the global Lua state because of an unknown error.\n" "Everyone is still running the previous version." ); } } else { con->sendDebugReply("You must confirm reloading the global Lua state by providing the argument of \"yes\"."); } } } else if (command == "halt") { Server::startShutdown(); } else if (command == "help") { con->sendDebugReply( "Possible commands are: help, status, isolate, deisolate, reload, halt\n" "help: Prints this message.\n" "status: Prints information about your connection, including if you are in an isolated Lua state.\n" "isolate: Attempts to place your connection in an isolated Lua state. Returns a detailed error message upon failure.\n" "deisolate: Removes your connection from an isolated Lua state if you are in one. Returns a detailed error message upon failure.\n" "reload: Reloads the Lua code for a state. In a global state you are required to confirm reloading. Returns a detailed error message upon failure.\n" "halt: This will immediately bring the server down after saving important data." ); } else { con->sendDebugReply("Unknown debug command. Try 'help'?"); } json_decref(topnode); return FERR_OK; } FReturnCode NativeCommand::IdentCommand(ConnectionPtr& con, string& payload) { LOG(INFO) << "Ident command with payload: " << payload; if (con->identified || con->authStarted) return FERR_ALREADY_IDENT; con->authStarted = true; if (ServerState::getConnectionCount() >= StartupConfig::getDouble("maxusers")) return FERR_SERVER_FULL; json_t* tempnode = nullptr; json_t* topnode = json_loads(payload.c_str(), 0, 0); if (!topnode) return FERR_BAD_SYNTAX; LoginRequest* request = new LoginRequest; request->connection = con; json_t* methodnode = json_object_get(topnode, "method"); if (!json_is_string(methodnode)) { json_decref(topnode); delete request; return FERR_BAD_SYNTAX; } string method = json_string_value(methodnode); if (method == "ticket") { request->method = LOGIN_METHOD_TICKET; tempnode = json_object_get(topnode, "account"); if (!json_is_string(tempnode)) goto fail; request->account = json_string_value(tempnode); tempnode = json_object_get(topnode, "ticket"); if (!json_is_string(tempnode)) goto fail; request->ticket = json_string_value(tempnode); tempnode = json_object_get(topnode, "character"); if (!json_is_string(tempnode)) goto fail; request->characterName = json_string_value(tempnode); tempnode = json_object_get(topnode, "cname"); if(!json_is_string(tempnode)) goto fail; request->clientName = json_string_value(tempnode); tempnode = json_object_get(topnode, "cversion"); if(!json_is_string(tempnode)) goto fail; request->clientVersion = json_string_value(tempnode); tempnode = nullptr; } else { json_decref(topnode); delete request; return FERR_UNKNOWN_AUTH_METHOD; } if (!LoginEvHTTPClient::addRequest(request)) { json_decref(topnode); delete request; return FERR_NO_LOGIN_SLOT; } LoginEvHTTPClient::sendWakeup(); json_decref(topnode); return FERR_OK; fail: json_decref(topnode); delete request; return FERR_BAD_SYNTAX; } void SearchFilterList(const json_t* node, list<ConnectionPtr>& conlist, string item) { unordered_set<string> items; list<ConnectionPtr> toremove; size_t size = json_array_size(node); for (size_t i = 0; i < size; ++i) { json_t* jn = json_array_get(node, i); if (json_is_string(jn)) items.insert(json_string_value(jn)); } for (list<ConnectionPtr>::iterator i = conlist.begin(); i != conlist.end(); ++i) { if (items.find((*i)->infotagMap[item]) == items.end()) toremove.push_back((*i)); } for (list<ConnectionPtr>::const_iterator i = toremove.begin(); i != toremove.end(); ++i) { conlist.remove((*i)); } } void SearchFilterListF(const json_t* node, list<ConnectionPtr>& conlist) { list<int> items; list<ConnectionPtr> tokeep; size_t size = json_array_size(node); for (size_t i = 0; i < size; ++i) { json_t* jn = json_array_get(node, i); if (json_is_string(jn)) { items.push_back((int) atoi(json_string_value(jn))); } else if (json_is_integer(jn)) { items.push_back((int) json_integer_value(jn)); } } for (list<ConnectionPtr>::const_iterator i = conlist.begin(); i != conlist.end(); ++i) { bool found = true; for (list<int>::const_iterator n = items.begin(); n != items.end(); ++n) { if ((*i)->kinkList.find((*n)) == (*i)->kinkList.end()) { found = false; break; } } if (found) tokeep.push_back((*i)); } conlist = tokeep; } FReturnCode NativeCommand::SearchCommand(intrusive_ptr< ConnectionInstance >& con, string& payload) { //DLOG(INFO) << "Starting search with payload " << payload; static string FKSstring("FKS"); static double timeout = 5.0; double time = Server::getEventTime(); if (con->timers[FKSstring] > (time - timeout)) return FERR_THROTTLE_SEARCH; else con->timers[FKSstring] = time; typedef list<ConnectionPtr> clst_t; clst_t tosearch; const conptrmap_t cons = ServerState::getConnections(); for (conptrmap_t::const_iterator i = cons.begin(); i != cons.end(); ++i) { if ((i->second != con) && (i->second->kinkList.size() != 0) && (i->second->status == "online" || i->second->status == "looking")) tosearch.push_back(i->second); } json_t* rootnode = json_loads(payload.c_str(), 0, 0); if (!rootnode) return FERR_BAD_SYNTAX; json_t* kinksnode = json_object_get(rootnode, "kinks"); if (!json_is_array(kinksnode)) return FERR_BAD_SYNTAX; if (json_array_size(kinksnode) > 5) return FERR_TOO_MANY_SEARCH_TERMS; json_t* gendersnode = json_object_get(rootnode, "genders"); if (json_is_array(gendersnode)) SearchFilterList(gendersnode, tosearch, "Gender"); json_t* orientationsnode = json_object_get(rootnode, "orientations"); if (json_is_array(orientationsnode)) SearchFilterList(orientationsnode, tosearch, "Orientation"); json_t* languagesnode = json_object_get(rootnode, "languages"); if (json_is_array(languagesnode)) SearchFilterList(languagesnode, tosearch, "Language preference"); json_t* furryprefsnode = json_object_get(rootnode, "furryprefs"); if (json_is_array(furryprefsnode)) SearchFilterList(furryprefsnode, tosearch, "Furry preference"); json_t* rolesnode = json_object_get(rootnode, "roles"); if (json_is_array(rolesnode)) SearchFilterList(rolesnode, tosearch, "Dom/Sub Role"); json_t* positionsnode = json_object_get(rootnode, "positions"); if (json_is_array(positionsnode)) SearchFilterList(positionsnode, tosearch, "Position"); if (json_array_size(kinksnode) > 0) SearchFilterListF(kinksnode, tosearch); int num_found = tosearch.size(); if (num_found == 0) return FERR_NO_SEARCH_RESULTS; else if (num_found > 350) return FERR_TOO_MANY_SEARCH_RESULTS; json_t* newroot = json_object(); json_t* chararray = json_array(); for (clst_t::const_iterator i = tosearch.begin(); i != tosearch.end(); ++i) { json_array_append_new(chararray, json_string_nocheck((*i)->characterName.c_str()) ); } json_object_set_new_nocheck(newroot, "characters", chararray); json_object_set_new_nocheck(newroot, "kinks", kinksnode); string message("FKS "); const char* fksstr = json_dumps(newroot, JSON_COMPACT); message += fksstr; free((void*) fksstr); json_decref(newroot); MessagePtr outMessage(MessageBuffer::fromString(message)); con->send(outMessage); json_decref(rootnode); //DLOG(INFO) << "Finished search."; return FERR_OK; } <commit_msg>Optimizations to search.<commit_after>/* * Copyright (c) 2011-2013, "Kira" * 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 "precompiled_headers.hpp" #include "native_command.hpp" #include "logging.hpp" #include "connection.hpp" #include "fjson.hpp" #include "login_evhttp.hpp" #include "server.hpp" #include "startup_config.hpp" #include "server_state.hpp" #include <google/profiler.h> FReturnCode NativeCommand::DebugCommand(ConnectionPtr& con, string& payload) { if (con->admin != true) return FERR_NOT_ADMIN; json_t* topnode = json_loads(payload.c_str(), 0, 0); if (!topnode) return FERR_BAD_SYNTAX; DLOG(INFO) << "Debug event with payload: " << payload; json_t* cmdnode = json_object_get(topnode, "command"); if (!json_is_string(cmdnode)) { json_decref(topnode); return FERR_BAD_SYNTAX; } string command = json_string_value(cmdnode); if (command == "isolate") { if (con->debugL) { con->sendDebugReply("Your connection is already running an isolated Lua state."); } else { string luamessage; FReturnCode isolateret = con->isolateLua(luamessage); if (isolateret == FERR_OK) { con->sendDebugReply("Your connection is now running an isolated Lua state."); } else if (isolateret == FERR_LUA) { string errmsg = "Failed to move your connection into an isolated Lua state. Lua returned the error: " + luamessage; con->sendDebugReply(errmsg); } else { con->sendDebugReply("Failed to move your connection into an isolated Lua state. An unknown error happened."); } } } else if (command == "deisolate") { if (!con->debugL) { con->sendDebugReply("Your connection is not currently running an isolated Lua state."); } else { con->deisolateLua(); con->sendDebugReply("Your connection has been returned to the global Lua state."); } } else if (command == "profile-start") { ProfilerStart("./cpu.out"); } else if (command == "profile-stop") { ProfilerStop(); } else if (command == "logger-start") { Server::loggerStart(); } else if (command == "logger-stop") { Server::loggerStop(); } else if (command == "status") { //TODO: Make this command do something. string statusmessage = "Status: "; if (con->debugL) statusmessage += "Running isolated. "; //statusmessage += "Connected from: "; con->sendDebugReply(statusmessage); } else if (command == "reload") { if (con->debugL) { string luamessage; FReturnCode reloadret = con->reloadIsolation(luamessage); if (reloadret == FERR_OK) { con->sendDebugReply("The isolated Lua state for your connection is now running the latest on disk Lua."); } else if (reloadret == FERR_LUA) { string errormsg = "It was not possible to reload the isolated Lua state for your connection because" " of a Lua error. Lua returned the error: " + luamessage + "\nYou are still running the previous version."; con->sendDebugReply(errormsg); } else { con->sendDebugReply("It was not possible to reload the isolated Lua state for your connection because of an unknown error.\n" "You are still running the previous version." ); } } else { json_t* argnode = json_object_get(topnode, "arg"); if (!json_is_string(argnode)) { json_decref(topnode); return FERR_BAD_SYNTAX; } string arg = json_string_value(argnode); if (arg == "yes") { string luamessage; FReturnCode reloadret = Server::reloadLuaState(luamessage); if (reloadret == FERR_OK) { con->sendDebugReply("The global Lua state has been reloaded."); } else if (reloadret == FERR_LUA) { string errormsg = "It was not possible to reload the global Lua state because of a Lua error. Lua returned the error: " + luamessage + "\nEveryone is still running the previous version."; con->sendDebugReply(errormsg); } else { con->sendDebugReply("It was not possible to reload the global Lua state because of an unknown error.\n" "Everyone is still running the previous version." ); } } else { con->sendDebugReply("You must confirm reloading the global Lua state by providing the argument of \"yes\"."); } } } else if (command == "halt") { Server::startShutdown(); } else if (command == "help") { con->sendDebugReply( "Possible commands are: help, status, isolate, deisolate, reload, halt\n" "help: Prints this message.\n" "status: Prints information about your connection, including if you are in an isolated Lua state.\n" "isolate: Attempts to place your connection in an isolated Lua state. Returns a detailed error message upon failure.\n" "deisolate: Removes your connection from an isolated Lua state if you are in one. Returns a detailed error message upon failure.\n" "reload: Reloads the Lua code for a state. In a global state you are required to confirm reloading. Returns a detailed error message upon failure.\n" "halt: This will immediately bring the server down after saving important data." ); } else { con->sendDebugReply("Unknown debug command. Try 'help'?"); } json_decref(topnode); return FERR_OK; } FReturnCode NativeCommand::IdentCommand(ConnectionPtr& con, string& payload) { LOG(INFO) << "Ident command with payload: " << payload; if (con->identified || con->authStarted) return FERR_ALREADY_IDENT; con->authStarted = true; if (ServerState::getConnectionCount() >= StartupConfig::getDouble("maxusers")) return FERR_SERVER_FULL; json_t* tempnode = nullptr; json_t* topnode = json_loads(payload.c_str(), 0, 0); if (!topnode) return FERR_BAD_SYNTAX; LoginRequest* request = new LoginRequest; request->connection = con; json_t* methodnode = json_object_get(topnode, "method"); if (!json_is_string(methodnode)) { json_decref(topnode); delete request; return FERR_BAD_SYNTAX; } string method = json_string_value(methodnode); if (method == "ticket") { request->method = LOGIN_METHOD_TICKET; tempnode = json_object_get(topnode, "account"); if (!json_is_string(tempnode)) goto fail; request->account = json_string_value(tempnode); tempnode = json_object_get(topnode, "ticket"); if (!json_is_string(tempnode)) goto fail; request->ticket = json_string_value(tempnode); tempnode = json_object_get(topnode, "character"); if (!json_is_string(tempnode)) goto fail; request->characterName = json_string_value(tempnode); tempnode = json_object_get(topnode, "cname"); if(!json_is_string(tempnode)) goto fail; request->clientName = json_string_value(tempnode); tempnode = json_object_get(topnode, "cversion"); if(!json_is_string(tempnode)) goto fail; request->clientVersion = json_string_value(tempnode); tempnode = nullptr; } else { json_decref(topnode); delete request; return FERR_UNKNOWN_AUTH_METHOD; } if (!LoginEvHTTPClient::addRequest(request)) { json_decref(topnode); delete request; return FERR_NO_LOGIN_SLOT; } LoginEvHTTPClient::sendWakeup(); json_decref(topnode); return FERR_OK; fail: json_decref(topnode); delete request; return FERR_BAD_SYNTAX; } void SearchFilterList(const json_t* node, unordered_set<ConnectionPtr>& conlist, string item) { unordered_set<string> items; size_t size = json_array_size(node); for (size_t i = 0; i < size; ++i) { json_t* jn = json_array_get(node, i); if (json_is_string(jn)) items.insert(json_string_value(jn)); } for (auto i = conlist.begin(); i != conlist.end();) { if (items.find((*i)->infotagMap[item]) == items.end()) i = conlist.erase(i); else ++i; } } void SearchFilterListF(const json_t* node, unordered_set<ConnectionPtr>& conlist) { list<int> items; size_t size = json_array_size(node); for (size_t i = 0; i < size; ++i) { json_t* jn = json_array_get(node, i); if (json_is_string(jn)) { items.push_back((int) atoi(json_string_value(jn))); } else if (json_is_integer(jn)) { items.push_back((int) json_integer_value(jn)); } } for (auto i = conlist.begin(); i != conlist.end();) { bool found = true; for (list<int>::const_iterator n = items.begin(); n != items.end(); ++n) { if ((*i)->kinkList.find((*n)) == (*i)->kinkList.end()) { found = false; break; } } if (found) ++i; else i = conlist.erase(i); } } FReturnCode NativeCommand::SearchCommand(intrusive_ptr< ConnectionInstance >& con, string& payload) { //DLOG(INFO) << "Starting search with payload " << payload; static string FKSstring("FKS"); static double timeout = 5.0; double time = Server::getEventTime(); if (con->timers[FKSstring] > (time - timeout)) return FERR_THROTTLE_SEARCH; else con->timers[FKSstring] = time; typedef unordered_set<ConnectionPtr> clist_t; clist_t tosearch; const conptrmap_t cons = ServerState::getConnections(); for (conptrmap_t::const_iterator i = cons.begin(); i != cons.end(); ++i) { if ((i->second != con) && (i->second->kinkList.size() != 0) && (i->second->status == "online" || i->second->status == "looking")) tosearch.insert(i->second); } json_t* rootnode = json_loads(payload.c_str(), 0, 0); if (!rootnode) return FERR_BAD_SYNTAX; json_t* kinksnode = json_object_get(rootnode, "kinks"); if (!json_is_array(kinksnode)) return FERR_BAD_SYNTAX; if (json_array_size(kinksnode) > 5) return FERR_TOO_MANY_SEARCH_TERMS; json_t* gendersnode = json_object_get(rootnode, "genders"); if (json_is_array(gendersnode)) SearchFilterList(gendersnode, tosearch, "Gender"); json_t* orientationsnode = json_object_get(rootnode, "orientations"); if (json_is_array(orientationsnode)) SearchFilterList(orientationsnode, tosearch, "Orientation"); json_t* languagesnode = json_object_get(rootnode, "languages"); if (json_is_array(languagesnode)) SearchFilterList(languagesnode, tosearch, "Language preference"); json_t* furryprefsnode = json_object_get(rootnode, "furryprefs"); if (json_is_array(furryprefsnode)) SearchFilterList(furryprefsnode, tosearch, "Furry preference"); json_t* rolesnode = json_object_get(rootnode, "roles"); if (json_is_array(rolesnode)) SearchFilterList(rolesnode, tosearch, "Dom/Sub Role"); json_t* positionsnode = json_object_get(rootnode, "positions"); if (json_is_array(positionsnode)) SearchFilterList(positionsnode, tosearch, "Position"); if (json_array_size(kinksnode) > 0) SearchFilterListF(kinksnode, tosearch); int num_found = tosearch.size(); if (num_found == 0) return FERR_NO_SEARCH_RESULTS; else if (num_found > 350) return FERR_TOO_MANY_SEARCH_RESULTS; json_t* newroot = json_object(); json_t* chararray = json_array(); for (clist_t::const_iterator i = tosearch.begin(); i != tosearch.end(); ++i) { json_array_append_new(chararray, json_string_nocheck((*i)->characterName.c_str()) ); } json_object_set_new_nocheck(newroot, "characters", chararray); json_object_set_new_nocheck(newroot, "kinks", kinksnode); string message("FKS "); const char* fksstr = json_dumps(newroot, JSON_COMPACT); message += fksstr; free((void*) fksstr); json_decref(newroot); MessagePtr outMessage(MessageBuffer::fromString(message)); con->send(outMessage); json_decref(rootnode); //DLOG(INFO) << "Finished search."; return FERR_OK; } <|endoftext|>
<commit_before>#include "Heartbeat.h" #include "Arduino.h" #include "TimerOne.h" /** * @brief ISR for toggling the heartbeat LED. */ void Heartbeat::toggle(void){ #if defined(__MK20DX256__) || defined(__MK20DX128__) // The teensy does have a toggle register! GPIOC_PTOR = 1 << 5; #else // This doesn't have a toggle register, so // we have to do this manually. PORTB = 1 << 5 ^ PORTB; #endif } /** * @brief Starts the heartbeat LED on PB5 using a timer. */ void Heartbeat::start(void){ // Make sure pin is output. #if defined(__MK20DX256__) || defined(__MK20DX128__) pinMode(13, OUTPUT); #else DDRB = 1 << 5 | DDRB; #endif // Make a timer that runs every 500,000 milliseconds. Timer1.initialize(500000); // And attach a static toggle pin ISR. Timer1.attachInterrupt(Heartbeat::toggle); } /** * @brief Blinks the LED much quicker to show that we are in an error state. */ void Heartbeat::panic(void){ // Start a timer. Timer1.initialize(); // Attach a static toggle pin ISR to said timer every 50,000 microseconds. Timer1.attachInterrupt(Heartbeat::toggle, 50000); } <commit_msg>Made heartbeat timer be 1 second but also added an interrupt to the timer via capture/compare ISR.<commit_after>#include "Heartbeat.h" #include "Arduino.h" #include "TimerOne.h" /** * @brief ISR for toggling the heartbeat LED. */ void Heartbeat::toggle(void){ #if defined(__MK20DX256__) || defined(__MK20DX128__) // The teensy does have a toggle register! GPIOC_PTOR = 1 << 5; #else // This doesn't have a toggle register, so // we have to do this manually. PORTB = 1 << 5 ^ PORTB; #endif } /** * @brief Starts the heartbeat LED on PB5 using a timer. */ void Heartbeat::start(void){ // Make sure pin is output. #if defined(__MK20DX256__) || defined(__MK20DX128__) pinMode(13, OUTPUT); #else DDRB = 1 << 5 | DDRB; #endif // Start a timer. Timer1.initialize(); // Attach a static toggle pin ISR to said timer every 500,000 microseconds. Timer1.attachInterrupt(Heartbeat::toggle, 500000); } } /** * @brief Blinks the LED much quicker to show that we are in an error state. */ void Heartbeat::panic(void){ // Start a timer. Timer1.initialize(); // Attach a static toggle pin ISR to said timer every 50,000 microseconds. Timer1.attachInterrupt(Heartbeat::toggle, 50000); } <|endoftext|>
<commit_before>#include "spotlightDemo.h" #include "vrambatcher.h" #include <nds/arm9/window.h> #include <cmath> #include <nds/arm9/input.h> #define M_PI 3.14159265358979323846 #define FULL_ROTATION M_PI*2 #define D45 FULL_ROTATION/8 #define MD45 FULL_ROTATION/-8 #define D135 (FULL_ROTATION/4+D45) #define MD135 -D135 #define MAX_SPREAD M_PI/2 #define MIN_SPREAD M_PI/32 SpotLightDemo::SpotLightDemo() : lightX(128), lightY(96), angle(M_PI/4), spread(M_PI/16) {} SpotLightDemo::~SpotLightDemo() {} float normalizeAngle(float x) { // Wrap angle in [-pi, pi] x = fmod(x + M_PI, FULL_ROTATION); return x >= 0 ? (x - M_PI) : (x + M_PI); } int clamp(int n, int min, int max) { return std::max(min, std::min(n, max)); } void SpotLightDemo::PrepareFrame(VramBatcher &batcher) { WindowingDemo::PrepareFrame(batcher); float leftAngle = normalizeAngle(angle + spread); float rightAngle = normalizeAngle(angle - spread); int top = 0, bottom = SCREEN_HEIGHT - 1; if (rightAngle >= 0 && leftAngle >= 0) { bottom = lightY; } else if (leftAngle <= 0 && rightAngle <= 0) { top = lightY; } top = clamp(top, 0, SCREEN_HEIGHT - 1); bottom = clamp(bottom, 0, SCREEN_HEIGHT - 1); WIN0_Y0 = top; WIN0_Y1 = bottom; float tanLeft = std::tan(leftAngle); float tanRight = std::tan(rightAngle); for (int scanline = top; scanline < bottom; ++scanline) { int left = lightX, right = lightX; if (leftAngle > 0 && rightAngle > 0) { left += (lightY - scanline) / tanLeft; right += (lightY - scanline) / tanRight; } else if (leftAngle < 0 && rightAngle < 0) { left += (lightY - scanline) / tanRight; right += (lightY - scanline) / tanLeft; } else if (leftAngle > 0 && rightAngle < 0) { if (lightY > scanline) left += (lightY - scanline) / tanLeft; else left += (lightY - scanline) / tanRight; right = SCREEN_WIDTH - 1; } else { if (lightY > scanline) right += (lightY - scanline) / tanRight; else right += (lightY - scanline) / tanLeft; left = 0; } left = clamp(left, 0, SCREEN_WIDTH - 1); right = clamp(right, 0, SCREEN_WIDTH - 1); batcher.AddPoke(scanline, left, &WIN0_X0); batcher.AddPoke(scanline, right, &WIN0_X1); } } void SpotLightDemo::AcceptInput() { WindowingDemo::AcceptInput(); auto keys = keysCurrent(); if (keys & KEY_L) { angle -= 0.02; angle = normalizeAngle(angle); printf("Angle: %f\n", angle); } else if (keys & KEY_R) { angle += 0.02; angle = normalizeAngle(angle); printf("Angle: %f\n", angle); } if (keys & KEY_X && spread < MAX_SPREAD) { spread += 0.02; printf("Spread: %f\n", spread); } else if (keys & KEY_Y && spread > MIN_SPREAD) { spread -= 0.02; if (spread < MIN_SPREAD) { spread = MIN_SPREAD; } printf("Spread: %f\n", spread); } if (keys & KEY_UP) { --lightY; printf("Light XY: %d, %d\n", lightX, lightY); } else if (keys & KEY_DOWN) { ++lightY; printf("Light XY: %d, %d\n", lightX, lightY); } if (keys & KEY_LEFT) { --lightX; printf("Light XY: %d, %d\n", lightX, lightY); } else if (keys & KEY_RIGHT) { ++lightX; printf("Light XY: %d, %d\n", lightX, lightY); } } <commit_msg>Use tabs, not spaces for real<commit_after>#include "spotlightDemo.h" #include "vrambatcher.h" #include <nds/arm9/window.h> #include <cmath> #include <nds/arm9/input.h> #define M_PI 3.14159265358979323846 #define FULL_ROTATION M_PI*2 #define D45 FULL_ROTATION/8 #define MD45 FULL_ROTATION/-8 #define D135 (FULL_ROTATION/4+D45) #define MD135 -D135 #define MAX_SPREAD M_PI/2 #define MIN_SPREAD M_PI/32 SpotLightDemo::SpotLightDemo() : lightX(128), lightY(96), angle(M_PI/4), spread(M_PI/16) {} SpotLightDemo::~SpotLightDemo() {} float normalizeAngle(float x) { // Wrap angle in [-pi, pi] x = fmod(x + M_PI, FULL_ROTATION); return x >= 0 ? (x - M_PI) : (x + M_PI); } int clamp(int n, int min, int max) { return std::max(min, std::min(n, max)); } void SpotLightDemo::PrepareFrame(VramBatcher &batcher) { WindowingDemo::PrepareFrame(batcher); float leftAngle = normalizeAngle(angle + spread); float rightAngle = normalizeAngle(angle - spread); int top = 0, bottom = SCREEN_HEIGHT - 1; if (rightAngle >= 0 && leftAngle >= 0) { bottom = lightY; } else if (leftAngle <= 0 && rightAngle <= 0) { top = lightY; } top = clamp(top, 0, SCREEN_HEIGHT - 1); bottom = clamp(bottom, 0, SCREEN_HEIGHT - 1); WIN0_Y0 = top; WIN0_Y1 = bottom; float tanLeft = std::tan(leftAngle); float tanRight = std::tan(rightAngle); for (int scanline = top; scanline < bottom; ++scanline) { int left = lightX, right = lightX; if (leftAngle > 0 && rightAngle > 0) { left += (lightY - scanline) / tanLeft; right += (lightY - scanline) / tanRight; } else if (leftAngle < 0 && rightAngle < 0) { left += (lightY - scanline) / tanRight; right += (lightY - scanline) / tanLeft; } else if (leftAngle > 0 && rightAngle < 0) { if (lightY > scanline) left += (lightY - scanline) / tanLeft; else left += (lightY - scanline) / tanRight; right = SCREEN_WIDTH - 1; } else { if (lightY > scanline) right += (lightY - scanline) / tanRight; else right += (lightY - scanline) / tanLeft; left = 0; } left = clamp(left, 0, SCREEN_WIDTH - 1); right = clamp(right, 0, SCREEN_WIDTH - 1); batcher.AddPoke(scanline, left, &WIN0_X0); batcher.AddPoke(scanline, right, &WIN0_X1); } } void SpotLightDemo::AcceptInput() { WindowingDemo::AcceptInput(); auto keys = keysCurrent(); if (keys & KEY_L) { angle -= 0.02; angle = normalizeAngle(angle); printf("Angle: %f\n", angle); } else if (keys & KEY_R) { angle += 0.02; angle = normalizeAngle(angle); printf("Angle: %f\n", angle); } if (keys & KEY_X && spread < MAX_SPREAD) { spread += 0.02; printf("Spread: %f\n", spread); } else if (keys & KEY_Y && spread > MIN_SPREAD) { spread -= 0.02; if (spread < MIN_SPREAD) { spread = MIN_SPREAD; } printf("Spread: %f\n", spread); } if (keys & KEY_UP) { --lightY; printf("Light XY: %d, %d\n", lightX, lightY); } else if (keys & KEY_DOWN) { ++lightY; printf("Light XY: %d, %d\n", lightX, lightY); } if (keys & KEY_LEFT) { --lightX; printf("Light XY: %d, %d\n", lightX, lightY); } else if (keys & KEY_RIGHT) { ++lightX; printf("Light XY: %d, %d\n", lightX, lightY); } } <|endoftext|>
<commit_before>#include "image-util.hpp" #include "include-opencv.hpp" #include "include-simd.hpp" #include <fmo/differentiator.hpp> #include <fmo/processing.hpp> namespace fmo { namespace { constexpr uint8_t threshDecrement = 1; constexpr uint8_t threshIncrement = 1; constexpr uint8_t threshMin = 10; constexpr uint8_t threshMax = 254; } Differentiator::Config::Config() : thresh(23), noiseMin(0.0038), noiseMax(0.0047), adjustPeriod(3) {} Differentiator::Differentiator(const Config& cfg) : mCfg(cfg), mThresh(std::min(std::max(cfg.thresh, threshMin), threshMax)) { mNoise.reserve(mCfg.adjustPeriod); } struct AddAndThreshJob : public cv::ParallelLoopBody { #if defined(FMO_HAVE_NEON) using batch_t = uint8x16_t; using batch3_t = uint8x16x3_t; static void impl(const uint8_t* src, const uint8_t* srcEnd, uint8_t* dst, uint8_t thresh) { batch_t threshVec = vld1q_dup_u8(&thresh); for (; src < srcEnd; src += SRC_BATCH_SIZE, dst += DST_BATCH_SIZE) { batch3_t v = vld3q_u8(src); batch_t sum = vqaddq_u8(vqaddq_u8(v.val[0], v.val[1]), v.val[2]); sum = vcgtq_u8(sum, threshVec); vst1q_u8(dst, sum); } } #else using batch_t = uint8_t; static void impl(const uint8_t* src, const uint8_t* srcEnd, uint8_t* dst, uint8_t thresh) { int t = int(thresh); for (; src < srcEnd; src += SRC_BATCH_SIZE, dst += DST_BATCH_SIZE) { *dst = ((src[0] + src[1] + src[2]) > t) ? uint8_t(0xFF) : uint8_t(0); } } #endif enum : size_t { SRC_BATCH_SIZE = sizeof(batch_t) * 3, DST_BATCH_SIZE = sizeof(batch_t), }; AddAndThreshJob(const uint8_t* src, uint8_t* dst, uint8_t thresh) : mSrc(src), mDst(dst), mThresh(thresh) {} virtual void operator()(const cv::Range& pieces) const override { size_t firstSrc = size_t(pieces.start) * SRC_BATCH_SIZE; size_t lastSrc = size_t(pieces.end) * SRC_BATCH_SIZE; size_t firstDst = size_t(pieces.start) * DST_BATCH_SIZE; const uint8_t* src = mSrc + firstSrc; const uint8_t* srcEnd = mSrc + lastSrc; uint8_t* dst = mDst + firstDst; impl(src, srcEnd, dst, mThresh); } private: const uint8_t* const mSrc; uint8_t* const mDst; uint8_t mThresh; }; void addAndThresh(const Image& src, Image& dst, uint8_t thresh) { const Format format = src.format(); const Dims dims = src.dims(); const size_t pixels = size_t(dims.width) * size_t(dims.height); const size_t pieces = pixels / AddAndThreshJob::DST_BATCH_SIZE; if (getPixelStep(format) != 3) { throw std::runtime_error("addAndThresh(): bad format"); } // run the job in parallel dst.resize(Format::GRAY, dims); AddAndThreshJob job{src.data(), dst.data(), thresh}; cv::parallel_for_(cv::Range{0, int(pieces)}, job, cv::getNumThreads()); // process the last few bytes individually size_t lastIndex = pieces * AddAndThreshJob::DST_BATCH_SIZE; const uint8_t* data = src.data() + (lastIndex * 3); uint8_t* out = dst.data() + lastIndex; uint8_t* outEnd = dst.data() + pixels; int t = int(thresh); for (; out < outEnd; out++, data += 3) { *out = ((data[0] + data[1] + data[2]) > t) ? uint8_t(0xFF) : uint8_t(0); } } void Differentiator::operator()(const Mat& src1, const Mat& src2, Image& dst) { // calibrate threshold based on measured noise if (mNoise.size() >= mCfg.adjustPeriod) { std::sort(begin(mNoise), end(mNoise)); auto median = begin(mNoise) + (mNoise.size() / 2); int noiseAmount = *median; mNoise.clear(); int numPixels = src1.dims().width * src1.dims().height; double noiseFrac = double(noiseAmount) / double(numPixels); if (noiseFrac > mCfg.noiseMax) { mThresh += threshIncrement; mThresh = std::min(mThresh, threshMax); } if (noiseFrac < mCfg.noiseMin) { mThresh -= threshDecrement; mThresh = std::max(mThresh, threshMin); } } // calculate absolute differences absdiff(src1, src2, mAbsDiff); // threshold switch (mAbsDiff.format()) { case Format::GRAY: { greater_than(mAbsDiff, dst, mThresh); return; } case Format::BGR: case Format::YUV: { addAndThresh(mAbsDiff, dst, mThresh); return; } default: throw std::runtime_error("Differentiator: unsupported format"); } } void Differentiator::reportAmountOfNoise(int noise) { mNoise.push_back(noise); } } <commit_msg>Fix GCC warning<commit_after>#include "image-util.hpp" #include "include-opencv.hpp" #include "include-simd.hpp" #include <fmo/differentiator.hpp> #include <fmo/processing.hpp> namespace fmo { namespace { constexpr uint8_t threshDecrement = 1; constexpr uint8_t threshIncrement = 1; constexpr uint8_t threshMin = 10; constexpr uint8_t threshMax = 254; } Differentiator::Config::Config() : thresh(23), noiseMin(0.0038), noiseMax(0.0047), adjustPeriod(3) {} Differentiator::Differentiator(const Config& cfg) : mCfg(cfg), mThresh(std::min(std::max(cfg.thresh, threshMin), threshMax)) { mNoise.reserve(mCfg.adjustPeriod); } struct AddAndThreshJob : public cv::ParallelLoopBody { #if defined(FMO_HAVE_NEON) using batch_t = uint8x16_t; using batch3_t = uint8x16x3_t; static void impl(const uint8_t* src, const uint8_t* srcEnd, uint8_t* dst, uint8_t thresh) { batch_t threshVec = vld1q_dup_u8(&thresh); for (; src < srcEnd; src += SRC_BATCH_SIZE, dst += DST_BATCH_SIZE) { batch3_t v = vld3q_u8(src); batch_t sum = vqaddq_u8(vqaddq_u8(v.val[0], v.val[1]), v.val[2]); sum = vcgtq_u8(sum, threshVec); vst1q_u8(dst, sum); } } #else using batch_t = uint8_t; static void impl(const uint8_t* src, const uint8_t* srcEnd, uint8_t* dst, uint8_t thresh) { int t = int(thresh); for (; src < srcEnd; src += SRC_BATCH_SIZE, dst += DST_BATCH_SIZE) { *dst = ((src[0] + src[1] + src[2]) > t) ? uint8_t(0xFF) : uint8_t(0); } } #endif enum : size_t { SRC_BATCH_SIZE = sizeof(batch_t) * 3, DST_BATCH_SIZE = sizeof(batch_t), }; AddAndThreshJob(const uint8_t* src, uint8_t* dst, uint8_t thresh) : mSrc(src), mDst(dst), mThresh(thresh) {} virtual void operator()(const cv::Range& pieces) const override { size_t firstSrc = size_t(pieces.start) * SRC_BATCH_SIZE; size_t lastSrc = size_t(pieces.end) * SRC_BATCH_SIZE; size_t firstDst = size_t(pieces.start) * DST_BATCH_SIZE; const uint8_t* src = mSrc + firstSrc; const uint8_t* srcEnd = mSrc + lastSrc; uint8_t* dst = mDst + firstDst; impl(src, srcEnd, dst, mThresh); } private: const uint8_t* const mSrc; uint8_t* const mDst; uint8_t mThresh; }; void addAndThresh(const Image& src, Image& dst, uint8_t thresh) { const Format format = src.format(); const Dims dims = src.dims(); const size_t pixels = size_t(dims.width) * size_t(dims.height); const size_t pieces = pixels / AddAndThreshJob::DST_BATCH_SIZE; if (getPixelStep(format) != 3) { throw std::runtime_error("addAndThresh(): bad format"); } // run the job in parallel dst.resize(Format::GRAY, dims); AddAndThreshJob job{src.data(), dst.data(), thresh}; cv::parallel_for_(cv::Range{0, int(pieces)}, job, cv::getNumThreads()); // process the last few bytes individually size_t lastIndex = pieces * AddAndThreshJob::DST_BATCH_SIZE; const uint8_t* data = src.data() + (lastIndex * 3); uint8_t* out = dst.data() + lastIndex; uint8_t* outEnd = dst.data() + pixels; int t = int(thresh); for (; out < outEnd; out++, data += 3) { *out = ((data[0] + data[1] + data[2]) > t) ? uint8_t(0xFF) : uint8_t(0); } } void Differentiator::operator()(const Mat& src1, const Mat& src2, Image& dst) { // calibrate threshold based on measured noise if (int(mNoise.size()) >= mCfg.adjustPeriod) { std::sort(begin(mNoise), end(mNoise)); auto median = begin(mNoise) + (mNoise.size() / 2); int noiseAmount = *median; mNoise.clear(); int numPixels = src1.dims().width * src1.dims().height; double noiseFrac = double(noiseAmount) / double(numPixels); if (noiseFrac > mCfg.noiseMax) { mThresh += threshIncrement; mThresh = std::min(mThresh, threshMax); } if (noiseFrac < mCfg.noiseMin) { mThresh -= threshDecrement; mThresh = std::max(mThresh, threshMin); } } // calculate absolute differences absdiff(src1, src2, mAbsDiff); // threshold switch (mAbsDiff.format()) { case Format::GRAY: { greater_than(mAbsDiff, dst, mThresh); return; } case Format::BGR: case Format::YUV: { addAndThresh(mAbsDiff, dst, mThresh); return; } default: throw std::runtime_error("Differentiator: unsupported format"); } } void Differentiator::reportAmountOfNoise(int noise) { mNoise.push_back(noise); } } <|endoftext|>
<commit_before>#include <itkImageRegionConstIterator.h> #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkFDKConeBeamReconstructionFilter.h" #include "rtkConstantImageSource.h" template<class TImage> void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType; ImageIteratorType itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage::PixelType TestVal = itTest.Get(); typename TImage::PixelType RefVal = itRef.Get(); TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (2.0-ErrorPerPixel)/2.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 0.06) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 0.06." << std::endl; exit( EXIT_FAILURE); } if (PSNR < 24.5) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 24.5" << std::endl; exit( EXIT_FAILURE); } } int main(int argc, char* argv[]) { const unsigned int Dimension = 3; typedef float OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; const unsigned int NumberOfProjectionImages = 180; // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New(); origin[0] = -127.; origin[1] = -127.; origin[2] = -127.; size[0] = 128; size[1] = 128; size[2] = 128; spacing[0] = 2.; spacing[1] = 2.; spacing[2] = 2.; tomographySource->SetOrigin( origin ); tomographySource->SetSpacing( spacing ); tomographySource->SetSize( size ); tomographySource->SetConstant( 0. ); ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New(); origin[0] = -254.; origin[1] = -254.; origin[2] = -254.; size[0] = 128; size[1] = 128; size[2] = NumberOfProjectionImages; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; projectionsSource->SetOrigin( origin ); projectionsSource->SetSpacing( spacing ); projectionsSource->SetSize( size ); projectionsSource->SetConstant( 0. ); // Geometry object typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages); // Shepp Logan projections filter typedef rtk::SheppLoganPhantomFilter<OutputImageType, OutputImageType> SLPType; SLPType::Pointer slp=SLPType::New(); slp->SetInput( projectionsSource->GetOutput() ); slp->SetGeometry(geometry); TRY_AND_EXIT_ON_ITK_EXCEPTION( slp->Update() ); // Create a reference object (in this case a 3D phantom reference). typedef rtk::DrawSheppLoganFilter<OutputImageType, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->SetInput( tomographySource->GetOutput() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() ) // FDK reconstruction filtering typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType; FDKCPUType::Pointer feldkamp = FDKCPUType::New(); feldkamp->SetInput( 0, tomographySource->GetOutput() ); feldkamp->SetInput( 1, slp->GetOutput() ); feldkamp->SetGeometry( geometry ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; exit(EXIT_SUCCESS); } <commit_msg>Threshold ErrorPerPixel increased to 0.061<commit_after>#include <itkImageRegionConstIterator.h> #include "rtkSheppLoganPhantomFilter.h" #include "rtkDrawSheppLoganFilter.h" #include "rtkFDKConeBeamReconstructionFilter.h" #include "rtkConstantImageSource.h" template<class TImage> void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref) { typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType; ImageIteratorType itTest( recon, recon->GetBufferedRegion() ); ImageIteratorType itRef( ref, ref->GetBufferedRegion() ); typedef double ErrorType; ErrorType TestError = 0.; ErrorType EnerError = 0.; itTest.GoToBegin(); itRef.GoToBegin(); while( !itRef.IsAtEnd() ) { typename TImage::PixelType TestVal = itTest.Get(); typename TImage::PixelType RefVal = itRef.Get(); TestError += vcl_abs(RefVal - TestVal); EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.); ++itTest; ++itRef; } // Error per Pixel ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl; // MSE ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels(); std::cout << "MSE = " << MSE << std::endl; // PSNR ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE); std::cout << "PSNR = " << PSNR << "dB" << std::endl; // QI ErrorType QI = (2.0-ErrorPerPixel)/2.0; std::cout << "QI = " << QI << std::endl; // Checking results if (ErrorPerPixel > 0.061) { std::cerr << "Test Failed, Error per pixel not valid! " << ErrorPerPixel << " instead of 0.06." << std::endl; exit( EXIT_FAILURE); } if (PSNR < 24.5) { std::cerr << "Test Failed, PSNR not valid! " << PSNR << " instead of 24.5" << std::endl; exit( EXIT_FAILURE); } } int main(int argc, char* argv[]) { const unsigned int Dimension = 3; typedef float OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; const unsigned int NumberOfProjectionImages = 180; // Constant image sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; ConstantImageSourceType::Pointer tomographySource = ConstantImageSourceType::New(); origin[0] = -127.; origin[1] = -127.; origin[2] = -127.; size[0] = 128; size[1] = 128; size[2] = 128; spacing[0] = 2.; spacing[1] = 2.; spacing[2] = 2.; tomographySource->SetOrigin( origin ); tomographySource->SetSpacing( spacing ); tomographySource->SetSize( size ); tomographySource->SetConstant( 0. ); ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New(); origin[0] = -254.; origin[1] = -254.; origin[2] = -254.; size[0] = 128; size[1] = 128; size[2] = NumberOfProjectionImages; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; projectionsSource->SetOrigin( origin ); projectionsSource->SetSpacing( spacing ); projectionsSource->SetSize( size ); projectionsSource->SetConstant( 0. ); // Geometry object typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages); // Shepp Logan projections filter typedef rtk::SheppLoganPhantomFilter<OutputImageType, OutputImageType> SLPType; SLPType::Pointer slp=SLPType::New(); slp->SetInput( projectionsSource->GetOutput() ); slp->SetGeometry(geometry); TRY_AND_EXIT_ON_ITK_EXCEPTION( slp->Update() ); // Create a reference object (in this case a 3D phantom reference). typedef rtk::DrawSheppLoganFilter<OutputImageType, OutputImageType> DSLType; DSLType::Pointer dsl = DSLType::New(); dsl->SetInput( tomographySource->GetOutput() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() ) // FDK reconstruction filtering typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType; FDKCPUType::Pointer feldkamp = FDKCPUType::New(); feldkamp->SetInput( 0, tomographySource->GetOutput() ); feldkamp->SetInput( 1, slp->GetOutput() ); feldkamp->SetGeometry( geometry ); TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() ); CheckImageQuality<OutputImageType>(feldkamp->GetOutput(), dsl->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>// $Id$ // Load ITS digits. // Argument mode is a bitwise or determining which layers to import: // 1, 2 : SPD // 4, 8 : SDD // 16, 32 : SSD // By default import all layers. void its_digits(Int_t mode=63) { AliRunLoader* rl = Alieve::Event::AssertRunLoader(); rl->LoadDigits("ITS"); TTree* dt = rl->GetTreeD("ITS", false); Alieve::ITSDigitsInfo* di = new Alieve::ITSDigitsInfo(); di->SetTree(dt); di->Dump(); AliITSgeom* g = di->fGeom; gStyle->SetPalette(1, 0); gReve->DisableRedraw(); TString sSector; TString bsSector="Sector"; TString sStave; TString bsStave="Stave"; TString sLadder; TString bsLadder="Ladder"; Int_t i=0; Int_t nsec, nstave, nlad, nMod; if (mode & 1) { Reve::RenderElementList* l = new Reve::RenderElementList("SPD0"); l->SetTitle("SPDs' first layer"); l->SetMainColor((Color_t)2); gReve->AddRenderElement(l); for(nsec=0; nsec<10; nsec++) { sSector=bsSector; sSector+=nsec; Reve::RenderElementList* relSector = new Reve::RenderElementList(sSector.Data()); relSector->SetMainColor((Color_t)2); gReve->AddRenderElement(l, relSector); for(nstave=0; nstave<2; nstave++){ sStave=bsStave; sStave += nstave; Reve::RenderElementList* relStave = new Reve::RenderElementList(sStave.Data()); relStave->SetMainColor((Color_t)2); gReve->AddRenderElement(relSector, relStave); for(nMod=0; nMod<4; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di, (Color_t)2); gReve->AddRenderElement(relStave, m); } } } } if (mode & 2) { Reve::RenderElementList* l = new Reve::RenderElementList("SPD1"); l->SetTitle("SPDs' second layer"); l->SetMainColor((Color_t)2); gReve->AddRenderElement(l); for(nsec=0; nsec<10; nsec++) { sSector=bsSector; sSector+=nsec; Reve::RenderElementList* relSector = new Reve::RenderElementList(sSector.Data()); relSector->SetMainColor((Color_t)2); gReve->AddRenderElement(l, relSector); for(nstave=0; nstave<4; nstave++){ sStave=bsStave; sStave += nstave; Reve::RenderElementList* relStave = new Reve::RenderElementList(sStave.Data()); relStave->SetMainColor((Color_t)2); gReve->AddRenderElement(relSector, relStave); for(nMod=0; nMod<4; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di, (Color_t)2); gReve->AddRenderElement(relStave, m); } } } } if (mode & 4) { Reve::RenderElementList* l = new Reve::RenderElementList("SDD2"); l->SetTitle("SDDs' first layer"); l->SetMainColor((Color_t)3); gReve->AddRenderElement(l); for(nlad=0; nlad<14; nlad++) { sLadder=bsLadder; sLadder+=nlad; Reve::RenderElementList* relLadder = new Reve::RenderElementList(sLadder.Data()); relLadder->SetMainColor((Color_t)3); gReve->AddRenderElement(l, relLadder); for(nMod=0; nMod<6; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di, (Color_t)3); gReve->AddRenderElement(relLadder, m); } } } if (mode & 8) { Reve::RenderElementList* l = new Reve::RenderElementList("SDD3"); l->SetTitle("SDDs' second layer"); l->SetMainColor((Color_t)3); gReve->AddRenderElement(l); for(nlad=0; nlad<22; nlad++) { sLadder=bsLadder; sLadder+=nlad; Reve::RenderElementList* relLadder = new Reve::RenderElementList(sLadder.Data()); relLadder->SetMainColor((Color_t)3); gReve->AddRenderElement(l, relLadder); for(nMod=0; nMod<8; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di, (Color_t)3); gReve->AddRenderElement(relLadder, m); } } } if (mode & 16) { Reve::RenderElementList* l = new Reve::RenderElementList("SSD4"); l->SetTitle("SSDs' first layer"); l->SetMainColor((Color_t)4); gReve->AddRenderElement(l); for(nlad=0; nlad<34; nlad++) { sLadder=bsLadder; sLadder+=nlad; Reve::RenderElementList* relLadder = new Reve::RenderElementList(sLadder.Data()); relLadder->SetMainColor((Color_t)4); gReve->AddRenderElement(l, relLadder); for(nMod=0; nMod<22; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di, (Color_t)4); gReve->AddRenderElement(relLadder, m); } } } if (mode & 32) { Reve::RenderElementList* l = new Reve::RenderElementList("SSD5"); l->SetTitle("SSDs' second layer"); l->SetMainColor((Color_t)4); gReve->AddRenderElement(l); for(nlad=0; nlad<38; nlad++) { sLadder=bsLadder; sLadder+=nlad; Reve::RenderElementList* relLadder = new Reve::RenderElementList(sLadder.Data()); relLadder->SetMainColor((Color_t)4); gReve->AddRenderElement(l, relLadder); for(nMod=0; nMod<25; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di, (Color_t)4); gReve->AddRenderElement(relLadder, m); } } } gReve->EnableRedraw(); } <commit_msg>Removed frame-color from ctors, now part of shared frame-box properties.<commit_after>// $Id$ // Load ITS digits. // Argument mode is a bitwise or determining which layers to import: // 1, 2 : SPD // 4, 8 : SDD // 16, 32 : SSD // By default import all layers. void its_digits(Int_t mode=63) { AliRunLoader* rl = Alieve::Event::AssertRunLoader(); rl->LoadDigits("ITS"); TTree* dt = rl->GetTreeD("ITS", false); Alieve::ITSDigitsInfo* di = new Alieve::ITSDigitsInfo(); di->SetTree(dt); di->Dump(); // Could initialize ITSModule statics (?) AliITSgeom* g = di->fGeom; gStyle->SetPalette(1, 0); // Initialize palettes (?) gReve->DisableRedraw(); TString sSector; TString bsSector="Sector"; TString sStave; TString bsStave="Stave"; TString sLadder; TString bsLadder="Ladder"; Int_t i=0; Int_t nsec, nstave, nlad, nMod; if (mode & 1) { Reve::RenderElementList* l = new Reve::RenderElementList("SPD0"); l->SetTitle("SPDs' first layer"); l->SetMainColor((Color_t)2); gReve->AddRenderElement(l); for(nsec=0; nsec<10; nsec++) { sSector=bsSector; sSector+=nsec; Reve::RenderElementList* relSector = new Reve::RenderElementList(sSector.Data()); relSector->SetMainColor((Color_t)2); gReve->AddRenderElement(l, relSector); for(nstave=0; nstave<2; nstave++){ sStave=bsStave; sStave += nstave; Reve::RenderElementList* relStave = new Reve::RenderElementList(sStave.Data()); relStave->SetMainColor((Color_t)2); gReve->AddRenderElement(relSector, relStave); for(nMod=0; nMod<4; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di); gReve->AddRenderElement(relStave, m); } } } } if (mode & 2) { Reve::RenderElementList* l = new Reve::RenderElementList("SPD1"); l->SetTitle("SPDs' second layer"); l->SetMainColor((Color_t)2); gReve->AddRenderElement(l); for(nsec=0; nsec<10; nsec++) { sSector=bsSector; sSector+=nsec; Reve::RenderElementList* relSector = new Reve::RenderElementList(sSector.Data()); relSector->SetMainColor((Color_t)2); gReve->AddRenderElement(l, relSector); for(nstave=0; nstave<4; nstave++){ sStave=bsStave; sStave += nstave; Reve::RenderElementList* relStave = new Reve::RenderElementList(sStave.Data()); relStave->SetMainColor((Color_t)2); gReve->AddRenderElement(relSector, relStave); for(nMod=0; nMod<4; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di); gReve->AddRenderElement(relStave, m); } } } } if (mode & 4) { Reve::RenderElementList* l = new Reve::RenderElementList("SDD2"); l->SetTitle("SDDs' first layer"); l->SetMainColor((Color_t)3); gReve->AddRenderElement(l); for(nlad=0; nlad<14; nlad++) { sLadder=bsLadder; sLadder+=nlad; Reve::RenderElementList* relLadder = new Reve::RenderElementList(sLadder.Data()); relLadder->SetMainColor((Color_t)3); gReve->AddRenderElement(l, relLadder); for(nMod=0; nMod<6; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di); gReve->AddRenderElement(relLadder, m); } } } if (mode & 8) { Reve::RenderElementList* l = new Reve::RenderElementList("SDD3"); l->SetTitle("SDDs' second layer"); l->SetMainColor((Color_t)3); gReve->AddRenderElement(l); for(nlad=0; nlad<22; nlad++) { sLadder=bsLadder; sLadder+=nlad; Reve::RenderElementList* relLadder = new Reve::RenderElementList(sLadder.Data()); relLadder->SetMainColor((Color_t)3); gReve->AddRenderElement(l, relLadder); for(nMod=0; nMod<8; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di); gReve->AddRenderElement(relLadder, m); } } } if (mode & 16) { Reve::RenderElementList* l = new Reve::RenderElementList("SSD4"); l->SetTitle("SSDs' first layer"); l->SetMainColor((Color_t)4); gReve->AddRenderElement(l); for(nlad=0; nlad<34; nlad++) { sLadder=bsLadder; sLadder+=nlad; Reve::RenderElementList* relLadder = new Reve::RenderElementList(sLadder.Data()); relLadder->SetMainColor((Color_t)4); gReve->AddRenderElement(l, relLadder); for(nMod=0; nMod<22; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di); gReve->AddRenderElement(relLadder, m); } } } if (mode & 32) { Reve::RenderElementList* l = new Reve::RenderElementList("SSD5"); l->SetTitle("SSDs' second layer"); l->SetMainColor((Color_t)4); gReve->AddRenderElement(l); for(nlad=0; nlad<38; nlad++) { sLadder=bsLadder; sLadder+=nlad; Reve::RenderElementList* relLadder = new Reve::RenderElementList(sLadder.Data()); relLadder->SetMainColor((Color_t)4); gReve->AddRenderElement(l, relLadder); for(nMod=0; nMod<25; nMod++) { Alieve::ITSModule* m = new Alieve::ITSModule(i++, di); gReve->AddRenderElement(relLadder, m); } } } gReve->EnableRedraw(); } <|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ctime> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <utils.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char *argv[]) { bool localMem = false; bool print = false; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int nrSamplesPerBlock = 0; unsigned int nrDMsPerBlock = 0; unsigned int nrSamplesPerThread = 0; unsigned int nrDMsPerThread = 0; unsigned int unroll = 0; long long unsigned int wrongSamples = 0; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); print = args.getSwitch("-print"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); localMem = args.getSwitch("-local"); nrSamplesPerBlock = args.getSwitchArgument< unsigned int >("-sb"); nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db"); nrSamplesPerThread = args.getSwitchArgument< unsigned int >("-st"); nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt"); unroll = args.getSwitchArgument< unsigned int >("-unroll"); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step")); } catch ( isa::utils::SwitchNotFound &err ) { std::cerr << err.what() << std::endl; return 1; }catch ( std::exception &err ) { std::cerr << "Usage: " << argv[0] << " [-print] -opencl_platform ... -opencl_device ... -padding ... [-local] -sb ... -db ... -st ... -dt ... -unroll ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); std::vector< int > * shifts = PulsarSearch::getShifts(observation); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]); // Allocate memory cl::Buffer shifts_d; std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel()); cl::Buffer dispersedData_d; std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); cl::Buffer dedispersedData_d; std::vector< dataType > controlData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); try { shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(int), NULL, NULL); dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), NULL, NULL); dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), NULL, NULL); } catch ( cl::Error &err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } srand(time(NULL)); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerDispersedChannel(); sample++ ) { dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10); } } // Copy data structures to device try { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(int), reinterpret_cast< void * >(shifts->data()), NULL, NULL); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data()), NULL, NULL); } catch ( cl::Error &err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } // Generate kernel std::string * code = PulsarSearch::getDedispersionOpenCL< dataType >(localMem, nrSamplesPerBlock, nrDMsPerBlock, nrSamplesPerThread, nrDMsPerThread, unroll, typeName, observation, *shifts); cl::Kernel * kernel; if ( print ) { std::cout << *code << std::endl; } try { kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError &err ) { std::cerr << err.what() << std::endl; return 1; } // Run OpenCL kernel and CPU control try { cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / nrSamplesPerThread, observation.getNrDMs() / nrDMsPerThread); cl::NDRange local(nrSamplesPerBlock, nrDMsPerBlock); kernel->setArg(0, dispersedData_d); kernel->setArg(1, dedispersedData_d); kernel->setArg(2, shifts_d); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local); PulsarSearch::dedispersion< dataType >(observation, dispersedData, controlData, *shifts); clQueues->at(clDeviceID)[0].enqueueReadBuffer(dedispersedData_d, CL_TRUE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data())); } catch ( cl::Error &err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { if ( !isa::utils::same(controlData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample], dedispersedData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample]) ) { wrongSamples++; } } } if ( wrongSamples > 0 ) { std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) << "%)." << std::endl; } else { std::cout << "TEST PASSED." << std::endl; } return 0; } <commit_msg>getDedispersionOpenCL is not a template anymore.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <ctime> #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <utils.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> typedef float dataType; std::string typeName("float"); int main(int argc, char *argv[]) { bool localMem = false; bool print = false; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int nrSamplesPerBlock = 0; unsigned int nrDMsPerBlock = 0; unsigned int nrSamplesPerThread = 0; unsigned int nrDMsPerThread = 0; unsigned int unroll = 0; long long unsigned int wrongSamples = 0; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); print = args.getSwitch("-print"); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); localMem = args.getSwitch("-local"); nrSamplesPerBlock = args.getSwitchArgument< unsigned int >("-sb"); nrDMsPerBlock = args.getSwitchArgument< unsigned int >("-db"); nrSamplesPerThread = args.getSwitchArgument< unsigned int >("-st"); nrDMsPerThread = args.getSwitchArgument< unsigned int >("-dt"); unroll = args.getSwitchArgument< unsigned int >("-unroll"); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step")); } catch ( isa::utils::SwitchNotFound &err ) { std::cerr << err.what() << std::endl; return 1; }catch ( std::exception &err ) { std::cerr << "Usage: " << argv[0] << " [-print] -opencl_platform ... -opencl_device ... -padding ... [-local] -sb ... -db ... -st ... -dt ... -unroll ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl; return 1; } // Initialize OpenCL cl::Context * clContext = new cl::Context(); std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); std::vector< int > * shifts = PulsarSearch::getShifts(observation); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + (*shifts)[((observation.getNrDMs() - 1) * observation.getNrPaddedChannels())]); // Allocate memory cl::Buffer shifts_d; std::vector< dataType > dispersedData = std::vector< dataType >(observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel()); cl::Buffer dispersedData_d; std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); cl::Buffer dedispersedData_d; std::vector< dataType > controlData = std::vector< dataType >(observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond()); try { shifts_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(int), NULL, NULL); dispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, dispersedData.size() * sizeof(dataType), NULL, NULL); dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), NULL, NULL); } catch ( cl::Error &err ) { std::cerr << "OpenCL error allocating memory: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } srand(time(NULL)); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerDispersedChannel(); sample++ ) { dispersedData[(channel * observation.getNrSamplesPerDispersedChannel()) + sample] = static_cast< dataType >(rand() % 10); } } // Copy data structures to device try { clQueues->at(clDeviceID)[0].enqueueWriteBuffer(shifts_d, CL_FALSE, 0, shifts->size() * sizeof(int), reinterpret_cast< void * >(shifts->data()), NULL, NULL); clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dispersedData_d, CL_FALSE, 0, dispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dispersedData.data()), NULL, NULL); } catch ( cl::Error &err ) { std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } // Generate kernel std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, nrSamplesPerBlock, nrDMsPerBlock, nrSamplesPerThread, nrDMsPerThread, unroll, typeName, observation, *shifts); cl::Kernel * kernel; if ( print ) { std::cout << *code << std::endl; } try { kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError &err ) { std::cerr << err.what() << std::endl; return 1; } // Run OpenCL kernel and CPU control try { cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / nrSamplesPerThread, observation.getNrDMs() / nrDMsPerThread); cl::NDRange local(nrSamplesPerBlock, nrDMsPerBlock); kernel->setArg(0, dispersedData_d); kernel->setArg(1, dedispersedData_d); kernel->setArg(2, shifts_d); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local); PulsarSearch::dedispersion< dataType >(observation, dispersedData, controlData, *shifts); clQueues->at(clDeviceID)[0].enqueueReadBuffer(dedispersedData_d, CL_TRUE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data())); } catch ( cl::Error &err ) { std::cerr << "OpenCL error kernel execution: " << isa::utils::toString< cl_int >(err.err()) << "." << std::endl; return 1; } for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { if ( !isa::utils::same(controlData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample], dedispersedData[(dm * observation.getNrSamplesPerPaddedSecond()) + sample]) ) { wrongSamples++; } } } if ( wrongSamples > 0 ) { std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond()) << "%)." << std::endl; } else { std::cout << "TEST PASSED." << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <ir/index_manager/index/IndexWriter.h> #include <ir/index_manager/index/Indexer.h> #include <ir/index_manager/index/IndexMerger.h> #include <ir/index_manager/index/OnlineIndexMerger.h> #include <ir/index_manager/index/OfflineIndexMerger.h> #include <ir/index_manager/index/ImmediateMerger.h> #include <ir/index_manager/index/MultiWayMerger.h> #include <ir/index_manager/index/IndexBarrelWriter.h> #include <ir/index_manager/index/IndexerPropertyConfig.h> using namespace std; using namespace izenelib::ir::indexmanager; IndexWriter::IndexWriter(Indexer* pIndex) :pIndexBarrelWriter_(NULL) ,ppCachedDocs_(NULL) ,nNumCachedDocs_(100) ,nNumCacheUsed_(0) ,pCurBarrelInfo_(NULL) ,pIndexMerger_(NULL) ,pMemCache_(NULL) ,pIndexer_(pIndex) ,pCurDocCount_(NULL) { pBarrelsInfo_ = pIndexer_->getBarrelsInfo(); setupCache(); } IndexWriter::~IndexWriter() { destroyCache(); if (pMemCache_) { delete pMemCache_; pMemCache_ = NULL; } if (pIndexBarrelWriter_) delete pIndexBarrelWriter_; if (pIndexMerger_) delete pIndexMerger_; } void IndexWriter::setupCache() { if (ppCachedDocs_) destroyCache(); ppCachedDocs_ = new IndexerDocument*[nNumCachedDocs_]; for (int i = 0;i<nNumCachedDocs_;i++) ppCachedDocs_[i] = NULL; } void IndexWriter::clearCache() { if (ppCachedDocs_) { for (int i = 0;i<nNumCachedDocs_;i++) { if (ppCachedDocs_[i] != NULL) { delete ppCachedDocs_[i]; ppCachedDocs_[i] = NULL; } } } nNumCacheUsed_ = 0; } void IndexWriter::destroyCache() { clearCache(); delete[] ppCachedDocs_; ppCachedDocs_ = NULL; nNumCacheUsed_ = 0; } void IndexWriter::mergeIndex(IndexMerger* pMerger) { boost::mutex::scoped_lock lock(this->mutex_); pMerger->setDirectory(pIndexer_->getDirectory()); if(pIndexer_->getIndexReader()->getDocFilter()) pMerger->setDocFilter(pIndexer_->getIndexReader()->getDocFilter()); ///there is a in-memory index if ((pIndexBarrelWriter_) && pCurDocCount_ && ((*pCurDocCount_) > 0)) { IndexMerger* pTmp = pIndexMerger_; pIndexMerger_ = pMerger; mergeAndWriteCachedIndex(); pIndexMerger_ = pTmp; } else { if (pCurBarrelInfo_) { //pBarrelsInfo_->deleteLastBarrel(); pCurBarrelInfo_ = NULL; pCurDocCount_ = NULL; } pIndexer_->setDirty(true); pMerger->merge(pBarrelsInfo_); } pIndexer_->getIndexReader()->delDocFilter(); } void IndexWriter::createBarrelWriter() { pBarrelsInfo_->addBarrel(pBarrelsInfo_->newBarrel().c_str(),0); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; if (!pMemCache_) pMemCache_ = new MemCache((size_t)pIndexer_->getIndexManagerConfig()->indexStrategy_.memory_); pIndexBarrelWriter_ = new IndexBarrelWriter(pIndexer_,pMemCache_,pCurBarrelInfo_->getName().c_str()); pCurBarrelInfo_->setWriter(pIndexBarrelWriter_); pIndexBarrelWriter_->setCollectionsMeta(pIndexer_->getCollectionsMeta()); if(!strcasecmp(pIndexer_->pConfigurationManager_->mergeStrategy_.param_.c_str(),"no")) pIndexMerger_ = NULL; else if(!strcasecmp(pIndexer_->pConfigurationManager_->mergeStrategy_.param_.c_str(),"imm")) pIndexMerger_ = new ImmediateMerger(pIndexer_->getDirectory()); else if(!strcasecmp(pIndexer_->pConfigurationManager_->mergeStrategy_.param_.c_str(),"mway")) pIndexMerger_ = new MultiWayMerger(pIndexer_->getDirectory()); else pIndexMerger_ = new OnlineIndexMerger(pIndexer_->getDirectory()); } void IndexWriter::mergeAndWriteCachedIndex() { pIndexer_->setDirty(true); pIndexMerger_->merge(pBarrelsInfo_); pBarrelsInfo_->write(pIndexer_->getDirectory()); if (pIndexBarrelWriter_->cacheEmpty() == false)///memory index has not been written to database yet. { pIndexBarrelWriter_->close(); } pBarrelsInfo_->addBarrel(pBarrelsInfo_->newBarrel().c_str(),0); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurBarrelInfo_->setWriter(pIndexBarrelWriter_); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; } void IndexWriter::flush() { if((!pIndexBarrelWriter_)&&(nNumCacheUsed_ <=0 )) return; flushDocuments(); BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel(); if (pLastBarrel == NULL) return; pLastBarrel->setBaseDocID(baseDocIDMap_); if (pIndexBarrelWriter_->cacheEmpty() == false)///memory index has not been written to database yet. { pIndexBarrelWriter_->close(); if (pIndexMerger_) pIndexMerger_->transferToDisk(pIndexBarrelWriter_->barrelName.c_str()); } pIndexer_->setDirty(true); pLastBarrel->setWriter(NULL); pBarrelsInfo_->write(pIndexer_->getDirectory()); delete pIndexBarrelWriter_; pIndexBarrelWriter_ = NULL; } void IndexWriter::close() { if (!pIndexBarrelWriter_) return; flush(); } void IndexWriter::mergeAndWriteCachedIndex2() { pIndexer_->setDirty(true); BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel(); pLastBarrel->setBaseDocID(baseDocIDMap_); if (pIndexBarrelWriter_->cacheEmpty() == false)///memory index has not been written to database yet. { pIndexBarrelWriter_->close(); pLastBarrel->setWriter(NULL); if (pIndexMerger_) pIndexMerger_->addToMerge(pBarrelsInfo_,pBarrelsInfo_->getLastBarrel()); if (pIndexMerger_) pIndexMerger_->transferToDisk(pIndexBarrelWriter_->barrelName.c_str()); } pBarrelsInfo_->addBarrel(pBarrelsInfo_->newBarrel().c_str(),0); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurBarrelInfo_->setWriter(pIndexBarrelWriter_); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; } void IndexWriter::justWriteCachedIndex() { ///Used for MANAGER_TYPE_CLIENTPROCESS ///It does not update barrel info, only flush indices to barrel "_0" pBarrelsInfo_->write(pIndexer_->getDirectory()); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; } void IndexWriter::addDocument(IndexerDocument* pDoc) { //boost::mutex::scoped_lock lock(this->mutex_); ppCachedDocs_[nNumCacheUsed_++] = pDoc; if (isCacheFull()) flushDocuments(); } void IndexWriter::indexDocument(IndexerDocument* pDoc) { if (!pIndexBarrelWriter_) createBarrelWriter(); DocId uniqueID; pDoc->getDocId(uniqueID); if (pIndexBarrelWriter_->cacheFull()) { if(pIndexer_->getIndexerType() == MANAGER_TYPE_CLIENTPROCESS) justWriteCachedIndex(); else ///merge index mergeAndWriteCachedIndex2(); baseDocIDMap_.clear(); baseDocIDMap_[uniqueID.colId] = uniqueID.docId; pIndexBarrelWriter_->open(pCurBarrelInfo_->getName().c_str()); } pBarrelsInfo_->updateMaxDoc(uniqueID.docId); pIndexBarrelWriter_->addDocument(pDoc); (*pCurDocCount_)++; } void IndexWriter::flushDocuments() { boost::mutex::scoped_lock lock(this->mutex_); if (nNumCacheUsed_ <=0 ) return; for (int i=0;i<nNumCacheUsed_;i++) { DocId uniqueID; ppCachedDocs_[i]->getDocId(uniqueID); if (baseDocIDMap_.find(uniqueID.colId) == baseDocIDMap_.end()) baseDocIDMap_.insert(make_pair(uniqueID.colId,uniqueID.docId)); indexDocument(ppCachedDocs_[i]); } clearCache(); } bool IndexWriter::startUpdate() { BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel(); if(pLastBarrel == NULL) return false; IndexBarrelWriter* pBarrelWriter = pLastBarrel->getWriter(); if(pBarrelWriter) flush(); pBarrelsInfo_->addBarrel(pBarrelsInfo_->newBarrel().c_str(),0); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; if (!pMemCache_) pMemCache_ = new MemCache((size_t)pIndexer_->getIndexManagerConfig()->indexStrategy_.memory_); if(!pIndexBarrelWriter_) { pIndexBarrelWriter_ = new IndexBarrelWriter(pIndexer_,pMemCache_,pCurBarrelInfo_->getName().c_str()); pIndexBarrelWriter_->setCollectionsMeta(pIndexer_->getCollectionsMeta()); } pCurBarrelInfo_->setWriter(pIndexBarrelWriter_); if(!pIndexMerger_) { delete pIndexMerger_; pIndexMerger_ = NULL; } bool* pHasUpdateDocs = &(pCurBarrelInfo_->hasUpdateDocs); *pHasUpdateDocs = true; return true; } bool IndexWriter::removeCollection(collectionid_t colID, count_t colCount) { boost::mutex::scoped_lock lock(this->mutex_); Directory* pDirectory = pIndexer_->getDirectory(); BarrelInfo* pPreviousBarrelInfo = NULL; for (int i = 0; i < pBarrelsInfo_->getBarrelCount(); i++) { BarrelInfo* pBarrelInfo = (*pBarrelsInfo_)[i]; if (pPreviousBarrelInfo) { count_t prevBarrelDocCount = pBarrelInfo->baseDocIDMap[colID] - pPreviousBarrelInfo->baseDocIDMap[colID]; colCount -= prevBarrelDocCount; pPreviousBarrelInfo->setDocCount(pPreviousBarrelInfo->getDocCount() - prevBarrelDocCount); } pPreviousBarrelInfo = pBarrelInfo; pBarrelInfo->baseDocIDMap.erase(colID); if (pBarrelInfo->baseDocIDMap.empty()) { pBarrelsInfo_->removeBarrel(pDirectory,pBarrelInfo->getName()); pPreviousBarrelInfo = NULL; i--; continue; } string s = pBarrelInfo->getName() + ".fdi"; IndexInput* fdiInput = pDirectory->openInput(s.c_str()); CollectionsInfo* pCollectionsInfo = new CollectionsInfo(); pCollectionsInfo->read(fdiInput); pCollectionsInfo->removeCollectionInfo(colID); fdiInput->close(); delete fdiInput; pDirectory->deleteFile(s); IndexOutput* fieldsStream = pDirectory->createOutput(s.c_str()); pCollectionsInfo->write(fieldsStream); delete fieldsStream; } if (pPreviousBarrelInfo) { pPreviousBarrelInfo->setDocCount(colCount); } pBarrelsInfo_->write(pDirectory); return true; } <commit_msg>base doc id of index barrel is not correctly set when index is resumed<commit_after>#include <ir/index_manager/index/IndexWriter.h> #include <ir/index_manager/index/Indexer.h> #include <ir/index_manager/index/IndexMerger.h> #include <ir/index_manager/index/OnlineIndexMerger.h> #include <ir/index_manager/index/OfflineIndexMerger.h> #include <ir/index_manager/index/ImmediateMerger.h> #include <ir/index_manager/index/MultiWayMerger.h> #include <ir/index_manager/index/IndexBarrelWriter.h> #include <ir/index_manager/index/IndexerPropertyConfig.h> using namespace std; using namespace izenelib::ir::indexmanager; IndexWriter::IndexWriter(Indexer* pIndex) :pIndexBarrelWriter_(NULL) ,ppCachedDocs_(NULL) ,nNumCachedDocs_(100) ,nNumCacheUsed_(0) ,pCurBarrelInfo_(NULL) ,pIndexMerger_(NULL) ,pMemCache_(NULL) ,pIndexer_(pIndex) ,pCurDocCount_(NULL) { pBarrelsInfo_ = pIndexer_->getBarrelsInfo(); setupCache(); } IndexWriter::~IndexWriter() { destroyCache(); if (pMemCache_) { delete pMemCache_; pMemCache_ = NULL; } if (pIndexBarrelWriter_) delete pIndexBarrelWriter_; if (pIndexMerger_) delete pIndexMerger_; } void IndexWriter::setupCache() { if (ppCachedDocs_) destroyCache(); ppCachedDocs_ = new IndexerDocument*[nNumCachedDocs_]; for (int i = 0;i<nNumCachedDocs_;i++) ppCachedDocs_[i] = NULL; } void IndexWriter::clearCache() { if (ppCachedDocs_) { for (int i = 0;i<nNumCachedDocs_;i++) { if (ppCachedDocs_[i] != NULL) { delete ppCachedDocs_[i]; ppCachedDocs_[i] = NULL; } } } nNumCacheUsed_ = 0; } void IndexWriter::destroyCache() { clearCache(); delete[] ppCachedDocs_; ppCachedDocs_ = NULL; nNumCacheUsed_ = 0; } void IndexWriter::mergeIndex(IndexMerger* pMerger) { boost::mutex::scoped_lock lock(this->mutex_); pMerger->setDirectory(pIndexer_->getDirectory()); if(pIndexer_->getIndexReader()->getDocFilter()) pMerger->setDocFilter(pIndexer_->getIndexReader()->getDocFilter()); ///there is a in-memory index if ((pIndexBarrelWriter_) && pCurDocCount_ && ((*pCurDocCount_) > 0)) { IndexMerger* pTmp = pIndexMerger_; pIndexMerger_ = pMerger; mergeAndWriteCachedIndex(); pIndexMerger_ = pTmp; } else { if (pCurBarrelInfo_) { //pBarrelsInfo_->deleteLastBarrel(); pCurBarrelInfo_ = NULL; pCurDocCount_ = NULL; } pIndexer_->setDirty(true); pMerger->merge(pBarrelsInfo_); } pIndexer_->getIndexReader()->delDocFilter(); } void IndexWriter::createBarrelWriter() { pBarrelsInfo_->addBarrel(pBarrelsInfo_->newBarrel().c_str(),0); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; if (!pMemCache_) pMemCache_ = new MemCache((size_t)pIndexer_->getIndexManagerConfig()->indexStrategy_.memory_); pIndexBarrelWriter_ = new IndexBarrelWriter(pIndexer_,pMemCache_,pCurBarrelInfo_->getName().c_str()); pCurBarrelInfo_->setWriter(pIndexBarrelWriter_); pIndexBarrelWriter_->setCollectionsMeta(pIndexer_->getCollectionsMeta()); if(!strcasecmp(pIndexer_->pConfigurationManager_->mergeStrategy_.param_.c_str(),"no")) pIndexMerger_ = NULL; else if(!strcasecmp(pIndexer_->pConfigurationManager_->mergeStrategy_.param_.c_str(),"imm")) pIndexMerger_ = new ImmediateMerger(pIndexer_->getDirectory()); else if(!strcasecmp(pIndexer_->pConfigurationManager_->mergeStrategy_.param_.c_str(),"mway")) pIndexMerger_ = new MultiWayMerger(pIndexer_->getDirectory()); else pIndexMerger_ = new OnlineIndexMerger(pIndexer_->getDirectory()); } void IndexWriter::mergeAndWriteCachedIndex() { pIndexer_->setDirty(true); pIndexMerger_->merge(pBarrelsInfo_); pBarrelsInfo_->write(pIndexer_->getDirectory()); if (pIndexBarrelWriter_->cacheEmpty() == false)///memory index has not been written to database yet. { pIndexBarrelWriter_->close(); } pBarrelsInfo_->addBarrel(pBarrelsInfo_->newBarrel().c_str(),0); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurBarrelInfo_->setWriter(pIndexBarrelWriter_); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; } void IndexWriter::flush() { if((!pIndexBarrelWriter_)&&(nNumCacheUsed_ <=0 )) return; flushDocuments(); BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel(); if (pLastBarrel == NULL) return; pLastBarrel->setBaseDocID(baseDocIDMap_); baseDocIDMap_.clear(); if (pIndexBarrelWriter_->cacheEmpty() == false)///memory index has not been written to database yet. { pIndexBarrelWriter_->close(); if (pIndexMerger_) pIndexMerger_->transferToDisk(pIndexBarrelWriter_->barrelName.c_str()); } pIndexer_->setDirty(true); pLastBarrel->setWriter(NULL); pBarrelsInfo_->write(pIndexer_->getDirectory()); delete pIndexBarrelWriter_; pIndexBarrelWriter_ = NULL; } void IndexWriter::close() { if (!pIndexBarrelWriter_) return; flush(); } void IndexWriter::mergeAndWriteCachedIndex2() { pIndexer_->setDirty(true); BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel(); pLastBarrel->setBaseDocID(baseDocIDMap_); if (pIndexBarrelWriter_->cacheEmpty() == false)///memory index has not been written to database yet. { pIndexBarrelWriter_->close(); pLastBarrel->setWriter(NULL); if (pIndexMerger_) pIndexMerger_->addToMerge(pBarrelsInfo_,pBarrelsInfo_->getLastBarrel()); if (pIndexMerger_) pIndexMerger_->transferToDisk(pIndexBarrelWriter_->barrelName.c_str()); } pBarrelsInfo_->addBarrel(pBarrelsInfo_->newBarrel().c_str(),0); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurBarrelInfo_->setWriter(pIndexBarrelWriter_); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; } void IndexWriter::justWriteCachedIndex() { ///Used for MANAGER_TYPE_CLIENTPROCESS ///It does not update barrel info, only flush indices to barrel "_0" pBarrelsInfo_->write(pIndexer_->getDirectory()); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; } void IndexWriter::addDocument(IndexerDocument* pDoc) { //boost::mutex::scoped_lock lock(this->mutex_); ppCachedDocs_[nNumCacheUsed_++] = pDoc; if (isCacheFull()) flushDocuments(); } void IndexWriter::indexDocument(IndexerDocument* pDoc) { if (!pIndexBarrelWriter_) createBarrelWriter(); DocId uniqueID; pDoc->getDocId(uniqueID); if (pIndexBarrelWriter_->cacheFull()) { if(pIndexer_->getIndexerType() == MANAGER_TYPE_CLIENTPROCESS) justWriteCachedIndex(); else ///merge index mergeAndWriteCachedIndex2(); baseDocIDMap_.clear(); baseDocIDMap_[uniqueID.colId] = uniqueID.docId; pIndexBarrelWriter_->open(pCurBarrelInfo_->getName().c_str()); } pBarrelsInfo_->updateMaxDoc(uniqueID.docId); pIndexBarrelWriter_->addDocument(pDoc); (*pCurDocCount_)++; } void IndexWriter::flushDocuments() { boost::mutex::scoped_lock lock(this->mutex_); if (nNumCacheUsed_ <=0 ) return; for (int i=0;i<nNumCacheUsed_;i++) { DocId uniqueID; ppCachedDocs_[i]->getDocId(uniqueID); if (baseDocIDMap_.find(uniqueID.colId) == baseDocIDMap_.end()) baseDocIDMap_.insert(make_pair(uniqueID.colId,uniqueID.docId)); indexDocument(ppCachedDocs_[i]); } clearCache(); } bool IndexWriter::startUpdate() { BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel(); if(pLastBarrel == NULL) return false; IndexBarrelWriter* pBarrelWriter = pLastBarrel->getWriter(); if(pBarrelWriter) flush(); pBarrelsInfo_->addBarrel(pBarrelsInfo_->newBarrel().c_str(),0); pCurBarrelInfo_ = pBarrelsInfo_->getLastBarrel(); pCurDocCount_ = &(pCurBarrelInfo_->nNumDocs); *pCurDocCount_ = 0; if (!pMemCache_) pMemCache_ = new MemCache((size_t)pIndexer_->getIndexManagerConfig()->indexStrategy_.memory_); if(!pIndexBarrelWriter_) { pIndexBarrelWriter_ = new IndexBarrelWriter(pIndexer_,pMemCache_,pCurBarrelInfo_->getName().c_str()); pIndexBarrelWriter_->setCollectionsMeta(pIndexer_->getCollectionsMeta()); } pCurBarrelInfo_->setWriter(pIndexBarrelWriter_); if(!pIndexMerger_) { delete pIndexMerger_; pIndexMerger_ = NULL; } bool* pHasUpdateDocs = &(pCurBarrelInfo_->hasUpdateDocs); *pHasUpdateDocs = true; return true; } bool IndexWriter::removeCollection(collectionid_t colID, count_t colCount) { boost::mutex::scoped_lock lock(this->mutex_); Directory* pDirectory = pIndexer_->getDirectory(); BarrelInfo* pPreviousBarrelInfo = NULL; for (int i = 0; i < pBarrelsInfo_->getBarrelCount(); i++) { BarrelInfo* pBarrelInfo = (*pBarrelsInfo_)[i]; if (pPreviousBarrelInfo) { count_t prevBarrelDocCount = pBarrelInfo->baseDocIDMap[colID] - pPreviousBarrelInfo->baseDocIDMap[colID]; colCount -= prevBarrelDocCount; pPreviousBarrelInfo->setDocCount(pPreviousBarrelInfo->getDocCount() - prevBarrelDocCount); } pPreviousBarrelInfo = pBarrelInfo; pBarrelInfo->baseDocIDMap.erase(colID); if (pBarrelInfo->baseDocIDMap.empty()) { pBarrelsInfo_->removeBarrel(pDirectory,pBarrelInfo->getName()); pPreviousBarrelInfo = NULL; i--; continue; } string s = pBarrelInfo->getName() + ".fdi"; IndexInput* fdiInput = pDirectory->openInput(s.c_str()); CollectionsInfo* pCollectionsInfo = new CollectionsInfo(); pCollectionsInfo->read(fdiInput); pCollectionsInfo->removeCollectionInfo(colID); fdiInput->close(); delete fdiInput; pDirectory->deleteFile(s); IndexOutput* fieldsStream = pDirectory->createOutput(s.c_str()); pCollectionsInfo->write(fieldsStream); delete fieldsStream; } if (pPreviousBarrelInfo) { pPreviousBarrelInfo->setDocCount(colCount); } pBarrelsInfo_->write(pDirectory); return true; } <|endoftext|>
<commit_before><commit_msg>bad defensive check fixed<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: md5.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 13:30:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <rtl/digest.h> class ByteString; rtlDigestError calc_md5_checksum( const char *filename, ByteString &aChecksum ); <commit_msg>INTEGRATION: CWS changefileheader (1.3.292); FILE MERGED 2008/03/28 15:41:02 rt 1.3.292.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: md5.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <rtl/digest.h> class ByteString; rtlDigestError calc_md5_checksum( const char *filename, ByteString &aChecksum ); <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: Property.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: oj $ $Date: 2001-05-09 12:59:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONNECTIVITY_java_util_Properties #define CONNECTIVITY_java_util_Properties #ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_ #include "java/lang/Object.hxx" #endif namespace connectivity { class java_util_Properties : public java_lang_Object { protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); public: static jclass getMyClass(); virtual ~java_util_Properties(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_util_Properties( JNIEnv * pEnv, jobject myObj ) : java_lang_Object( pEnv, myObj ){} java_util_Properties( ); void setProperty(const ::rtl::OUString key, const ::rtl::OUString& value); }; } #endif // CONNECTIVITY_java_util_Properties<commit_msg>new line missing<commit_after>/************************************************************************* * * $RCSfile: Property.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: oj $ $Date: 2001-05-11 09:25:55 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONNECTIVITY_java_util_Properties #define CONNECTIVITY_java_util_Properties #ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_ #include "java/lang/Object.hxx" #endif namespace connectivity { class java_util_Properties : public java_lang_Object { protected: // statische Daten fuer die Klasse static jclass theClass; // der Destruktor um den Object-Counter zu aktualisieren static void saveClassRef( jclass pClass ); public: static jclass getMyClass(); virtual ~java_util_Properties(); // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird: java_util_Properties( JNIEnv * pEnv, jobject myObj ) : java_lang_Object( pEnv, myObj ){} java_util_Properties( ); void setProperty(const ::rtl::OUString key, const ::rtl::OUString& value); }; } #endif // CONNECTIVITY_java_util_Properties <|endoftext|>
<commit_before>#ifndef MJOLNIR_POTENTIAL_GLOBAL_3SPN2_COMMON_HPP #define MJOLNIR_POTENTIAL_GLOBAL_3SPN2_COMMON_HPP #include <cstdint> namespace mjolnir { namespace parameter_3SPN2 { enum class bead_kind: std::uint8_t { Phosphate, Sugar, BaseA, BaseT, BaseG, BaseC, Unknown }; // X is for default parameter enum class base_kind : std::uint8_t {A=0, T=1, G=2, C=3, X}; enum class base_pair_kind : std::uint8_t {AT, TA, GC, CG}; enum class base_stack_kind : std::uint8_t { AA = 0, AT = 1, AG = 2, AC = 3, TA = 4, TT = 5, TG = 6, TC = 7, GA = 8, GT = 9, GG = 10, GC = 11, CA = 12, CT = 13, CG = 14, CC = 15 }; enum class cross_stack_kind: std::uint8_t { // Si Bi Bj Sj // 5' o -- o===o -- o 3' // ^ / \ / \ | // | P o x o P | // | \ / \ / v // 3' o -- o===o -- o 5' // Bi3 Bj5 // // sense 5 -- antisense 5 (Bi - Bj5) AA5 = 0, AT5 = 1, AG5 = 2, AC5 = 3, TA5 = 4, TT5 = 5, TG5 = 6, TC5 = 7, GA5 = 8, GT5 = 9, GG5 = 10, GC5 = 11, CA5 = 12, CT5 = 13, CG5 = 14, CC5 = 15, // sense 3 -- antisense 3 (Bj - Bi3) AA3 = 16, AT3 = 17, AG3 = 18, AC3 = 19, TA3 = 20, TT3 = 21, TG3 = 22, TC3 = 23, GA3 = 24, GT3 = 25, GG3 = 26, GC3 = 27, CA3 = 28, CT3 = 29, CG3 = 30, CC3 = 31 }; template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const bead_kind bk) { switch(bk) { case bead_kind::Phosphate: {os << "Phosphate"; return os;} case bead_kind::Sugar: {os << "Sugar" ; return os;} case bead_kind::BaseA: {os << "BaseA" ; return os;} case bead_kind::BaseT: {os << "BaseT" ; return os;} case bead_kind::BaseG: {os << "BaseG" ; return os;} case bead_kind::BaseC: {os << "BaseC" ; return os;} case bead_kind::Unknown: {os << "Unknown" ; return os;} default: {os << "invalid" ; return os;} } } template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const base_kind bk) { switch(bk) { case base_kind::A: {os << "A"; return os;} case base_kind::T: {os << "T"; return os;} case base_kind::G: {os << "G"; return os;} case base_kind::C: {os << "C"; return os;} case base_kind::X: {os << "X"; return os;} default:{os << "invalid"; return os;} } } template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const base_pair_kind bk) { switch(bk) { case base_pair_kind::AT: {os << "AT"; return os;} case base_pair_kind::TA: {os << "TA"; return os;} case base_pair_kind::GC: {os << "GC"; return os;} case base_pair_kind::CG: {os << "CG"; return os;} default: {os << "invalid"; return os;} } } template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const base_stack_kind bs) { switch(bs) { case base_stack_kind::AA: {os << "AA"; return os;} case base_stack_kind::AT: {os << "AT"; return os;} case base_stack_kind::AG: {os << "AG"; return os;} case base_stack_kind::AC: {os << "AC"; return os;} case base_stack_kind::TA: {os << "TA"; return os;} case base_stack_kind::TT: {os << "TT"; return os;} case base_stack_kind::TG: {os << "TG"; return os;} case base_stack_kind::TC: {os << "TC"; return os;} case base_stack_kind::GA: {os << "GA"; return os;} case base_stack_kind::GT: {os << "GT"; return os;} case base_stack_kind::GG: {os << "GG"; return os;} case base_stack_kind::GC: {os << "GC"; return os;} case base_stack_kind::CA: {os << "CA"; return os;} case base_stack_kind::CT: {os << "CT"; return os;} case base_stack_kind::CG: {os << "CG"; return os;} case base_stack_kind::CC: {os << "CC"; return os;} default: {os << "invalid"; return os;} } } template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const cross_stack_kind cs) { switch(cs) { case cross_stack_kind::AA5: {os << "AA5"; return os;} case cross_stack_kind::AT5: {os << "AT5"; return os;} case cross_stack_kind::AG5: {os << "AG5"; return os;} case cross_stack_kind::AC5: {os << "AC5"; return os;} case cross_stack_kind::TA5: {os << "TA5"; return os;} case cross_stack_kind::TT5: {os << "TT5"; return os;} case cross_stack_kind::TG5: {os << "TG5"; return os;} case cross_stack_kind::TC5: {os << "TC5"; return os;} case cross_stack_kind::GA5: {os << "GA5"; return os;} case cross_stack_kind::GT5: {os << "GT5"; return os;} case cross_stack_kind::GG5: {os << "GG5"; return os;} case cross_stack_kind::GC5: {os << "GC5"; return os;} case cross_stack_kind::CA5: {os << "CA5"; return os;} case cross_stack_kind::CT5: {os << "CT5"; return os;} case cross_stack_kind::CG5: {os << "CG5"; return os;} case cross_stack_kind::CC5: {os << "CC5"; return os;} case cross_stack_kind::AA3: {os << "AA3"; return os;} case cross_stack_kind::AT3: {os << "AT3"; return os;} case cross_stack_kind::AG3: {os << "AG3"; return os;} case cross_stack_kind::AC3: {os << "AC3"; return os;} case cross_stack_kind::TA3: {os << "TA3"; return os;} case cross_stack_kind::TT3: {os << "TT3"; return os;} case cross_stack_kind::TG3: {os << "TG3"; return os;} case cross_stack_kind::TC3: {os << "TC3"; return os;} case cross_stack_kind::GA3: {os << "GA3"; return os;} case cross_stack_kind::GT3: {os << "GT3"; return os;} case cross_stack_kind::GG3: {os << "GG3"; return os;} case cross_stack_kind::GC3: {os << "GC3"; return os;} case cross_stack_kind::CA3: {os << "CA3"; return os;} case cross_stack_kind::CT3: {os << "CT3"; return os;} case cross_stack_kind::CG3: {os << "CG3"; return os;} case cross_stack_kind::CC3: {os << "CC3"; return os;} default: {os << "invalid"; return os;} } } } // 3SPN2 } // mjolnir #endif// MJOLNIR_POTENTIAL_GLOBAL_3SPN2_COMMON_HPP <commit_msg>feat: add INVALID to cross_stack_kind<commit_after>#ifndef MJOLNIR_POTENTIAL_GLOBAL_3SPN2_COMMON_HPP #define MJOLNIR_POTENTIAL_GLOBAL_3SPN2_COMMON_HPP #include <cstdint> namespace mjolnir { namespace parameter_3SPN2 { enum class bead_kind: std::uint8_t { Phosphate, Sugar, BaseA, BaseT, BaseG, BaseC, Unknown }; // X is for default parameter enum class base_kind : std::uint8_t {A=0, T=1, G=2, C=3, X}; enum class base_pair_kind : std::uint8_t {AT, TA, GC, CG}; enum class base_stack_kind : std::uint8_t { AA = 0, AT = 1, AG = 2, AC = 3, TA = 4, TT = 5, TG = 6, TC = 7, GA = 8, GT = 9, GG = 10, GC = 11, CA = 12, CT = 13, CG = 14, CC = 15 }; enum class cross_stack_kind: std::uint8_t { // Si Bi Bj Sj // 5' o -- o===o -- o 3' // ^ / \ / \ | // | P o x o P | // | \ / \ / v // 3' o -- o===o -- o 5' // Bi3 Bj5 // // sense 5 -- antisense 5 (Bi - Bj5) AA5 = 0, AT5 = 1, AG5 = 2, AC5 = 3, TA5 = 4, TT5 = 5, TG5 = 6, TC5 = 7, GA5 = 8, GT5 = 9, GG5 = 10, GC5 = 11, CA5 = 12, CT5 = 13, CG5 = 14, CC5 = 15, // sense 3 -- antisense 3 (Bj - Bi3) AA3 = 16, AT3 = 17, AG3 = 18, AC3 = 19, TA3 = 20, TT3 = 21, TG3 = 22, TC3 = 23, GA3 = 24, GT3 = 25, GG3 = 26, GC3 = 27, CA3 = 28, CT3 = 29, CG3 = 30, CC3 = 31, INVALID = 255 }; template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const bead_kind bk) { switch(bk) { case bead_kind::Phosphate: {os << "Phosphate"; return os;} case bead_kind::Sugar: {os << "Sugar" ; return os;} case bead_kind::BaseA: {os << "BaseA" ; return os;} case bead_kind::BaseT: {os << "BaseT" ; return os;} case bead_kind::BaseG: {os << "BaseG" ; return os;} case bead_kind::BaseC: {os << "BaseC" ; return os;} case bead_kind::Unknown: {os << "Unknown" ; return os;} default: {os << "invalid" ; return os;} } } template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const base_kind bk) { switch(bk) { case base_kind::A: {os << "A"; return os;} case base_kind::T: {os << "T"; return os;} case base_kind::G: {os << "G"; return os;} case base_kind::C: {os << "C"; return os;} case base_kind::X: {os << "X"; return os;} default:{os << "invalid"; return os;} } } template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const base_pair_kind bk) { switch(bk) { case base_pair_kind::AT: {os << "AT"; return os;} case base_pair_kind::TA: {os << "TA"; return os;} case base_pair_kind::GC: {os << "GC"; return os;} case base_pair_kind::CG: {os << "CG"; return os;} default: {os << "invalid"; return os;} } } template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const base_stack_kind bs) { switch(bs) { case base_stack_kind::AA: {os << "AA"; return os;} case base_stack_kind::AT: {os << "AT"; return os;} case base_stack_kind::AG: {os << "AG"; return os;} case base_stack_kind::AC: {os << "AC"; return os;} case base_stack_kind::TA: {os << "TA"; return os;} case base_stack_kind::TT: {os << "TT"; return os;} case base_stack_kind::TG: {os << "TG"; return os;} case base_stack_kind::TC: {os << "TC"; return os;} case base_stack_kind::GA: {os << "GA"; return os;} case base_stack_kind::GT: {os << "GT"; return os;} case base_stack_kind::GG: {os << "GG"; return os;} case base_stack_kind::GC: {os << "GC"; return os;} case base_stack_kind::CA: {os << "CA"; return os;} case base_stack_kind::CT: {os << "CT"; return os;} case base_stack_kind::CG: {os << "CG"; return os;} case base_stack_kind::CC: {os << "CC"; return os;} default: {os << "invalid"; return os;} } } template<typename charT, typename traitsT> std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const cross_stack_kind cs) { switch(cs) { case cross_stack_kind::AA5: {os << "AA5"; return os;} case cross_stack_kind::AT5: {os << "AT5"; return os;} case cross_stack_kind::AG5: {os << "AG5"; return os;} case cross_stack_kind::AC5: {os << "AC5"; return os;} case cross_stack_kind::TA5: {os << "TA5"; return os;} case cross_stack_kind::TT5: {os << "TT5"; return os;} case cross_stack_kind::TG5: {os << "TG5"; return os;} case cross_stack_kind::TC5: {os << "TC5"; return os;} case cross_stack_kind::GA5: {os << "GA5"; return os;} case cross_stack_kind::GT5: {os << "GT5"; return os;} case cross_stack_kind::GG5: {os << "GG5"; return os;} case cross_stack_kind::GC5: {os << "GC5"; return os;} case cross_stack_kind::CA5: {os << "CA5"; return os;} case cross_stack_kind::CT5: {os << "CT5"; return os;} case cross_stack_kind::CG5: {os << "CG5"; return os;} case cross_stack_kind::CC5: {os << "CC5"; return os;} case cross_stack_kind::AA3: {os << "AA3"; return os;} case cross_stack_kind::AT3: {os << "AT3"; return os;} case cross_stack_kind::AG3: {os << "AG3"; return os;} case cross_stack_kind::AC3: {os << "AC3"; return os;} case cross_stack_kind::TA3: {os << "TA3"; return os;} case cross_stack_kind::TT3: {os << "TT3"; return os;} case cross_stack_kind::TG3: {os << "TG3"; return os;} case cross_stack_kind::TC3: {os << "TC3"; return os;} case cross_stack_kind::GA3: {os << "GA3"; return os;} case cross_stack_kind::GT3: {os << "GT3"; return os;} case cross_stack_kind::GG3: {os << "GG3"; return os;} case cross_stack_kind::GC3: {os << "GC3"; return os;} case cross_stack_kind::CA3: {os << "CA3"; return os;} case cross_stack_kind::CT3: {os << "CT3"; return os;} case cross_stack_kind::CG3: {os << "CG3"; return os;} case cross_stack_kind::CC3: {os << "CC3"; return os;} default: {os << "invalid"; return os;} } } } // 3SPN2 } // mjolnir #endif// MJOLNIR_POTENTIAL_GLOBAL_3SPN2_COMMON_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2019 oxarbitrage and contributors. * * The MIT License * * 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 <graphene/custom_operations/custom_operations_plugin.hpp> #include <fc/crypto/hex.hpp> #include <iostream> #include <graphene/app/database_api.hpp> namespace graphene { namespace custom_operations { namespace detail { class custom_operations_plugin_impl { public: custom_operations_plugin_impl(custom_operations_plugin& _plugin) : _self( _plugin ) { } virtual ~custom_operations_plugin_impl(); void onBlock( const signed_block& b ); graphene::chain::database& database() { return _self.database(); } custom_operations_plugin& _self; private: }; struct custom_op_visitor { typedef void result_type; account_id_type _fee_payer; database* _db; custom_op_visitor(database& db, account_id_type fee_payer) { _db = &db; _fee_payer = fee_payer; }; template<typename T> void operator()(T &v) const { v.validate(); custom_generic_evaluator evaluator(*_db, _fee_payer); evaluator.do_apply(v); } }; void custom_operations_plugin_impl::onBlock( const signed_block& b ) { graphene::chain::database& db = database(); const vector<optional< operation_history_object > >& hist = db.get_applied_operations(); for( const optional< operation_history_object >& o_operation : hist ) { if(!o_operation.valid() || !o_operation->op.is_type<custom_operation>()) continue; const custom_operation& custom_op = o_operation->op.get<custom_operation>(); if(custom_op.data.size() == 0) continue; try { auto unpacked = fc::raw::unpack<custom_plugin_operation>(custom_op.data); custom_op_visitor vtor(db, custom_op.fee_payer()); unpacked.visit(vtor); } catch (fc::exception& e) { // only api node will know if the unpack, validate or apply fails dlog("Custom operations plugin serializing error: ${ex} in operation: ${op}", ("ex", e.to_detail_string())("op", fc::json::to_string(custom_op))); continue; } } } custom_operations_plugin_impl::~custom_operations_plugin_impl() { return; } } // end namespace detail custom_operations_plugin::custom_operations_plugin() : my( new detail::custom_operations_plugin_impl(*this) ) { } custom_operations_plugin::~custom_operations_plugin() { } std::string custom_operations_plugin::plugin_name()const { return "custom_operations"; } std::string custom_operations_plugin::plugin_description()const { return "Stores arbitrary data for accounts by creating specially crafted custom operations."; } void custom_operations_plugin::plugin_set_program_options( boost::program_options::options_description& cli, boost::program_options::options_description& cfg ) { } void custom_operations_plugin::plugin_initialize(const boost::program_options::variables_map& options) { database().add_index< primary_index< account_storage_index > >(); database().applied_block.connect( [this]( const signed_block& b) { my->onBlock(b); } ); } void custom_operations_plugin::plugin_startup() { ilog("custom_operations: plugin_startup() begin"); } } } <commit_msg>add after_block option to custom operations plugin<commit_after>/* * Copyright (c) 2019 oxarbitrage and contributors. * * The MIT License * * 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 <graphene/custom_operations/custom_operations_plugin.hpp> #include <fc/crypto/hex.hpp> #include <iostream> #include <graphene/app/database_api.hpp> namespace graphene { namespace custom_operations { namespace detail { class custom_operations_plugin_impl { public: custom_operations_plugin_impl(custom_operations_plugin& _plugin) : _self( _plugin ) { } virtual ~custom_operations_plugin_impl(); void onBlock(); graphene::chain::database& database() { return _self.database(); } custom_operations_plugin& _self; uint32_t _after_block = 1; private: }; struct custom_op_visitor { typedef void result_type; account_id_type _fee_payer; database* _db; custom_op_visitor(database& db, account_id_type fee_payer) { _db = &db; _fee_payer = fee_payer; }; template<typename T> void operator()(T &v) const { v.validate(); custom_generic_evaluator evaluator(*_db, _fee_payer); evaluator.do_apply(v); } }; void custom_operations_plugin_impl::onBlock() { graphene::chain::database& db = database(); const vector<optional< operation_history_object > >& hist = db.get_applied_operations(); for( const optional< operation_history_object >& o_operation : hist ) { if(!o_operation.valid() || !o_operation->op.is_type<custom_operation>()) continue; const custom_operation& custom_op = o_operation->op.get<custom_operation>(); if(custom_op.data.size() == 0) continue; try { auto unpacked = fc::raw::unpack<custom_plugin_operation>(custom_op.data); custom_op_visitor vtor(db, custom_op.fee_payer()); unpacked.visit(vtor); } catch (fc::exception& e) { // only api node will know if the unpack, validate or apply fails dlog("Custom operations plugin serializing error: ${ex} in operation: ${op}", ("ex", e.to_detail_string())("op", fc::json::to_string(custom_op))); continue; } } } custom_operations_plugin_impl::~custom_operations_plugin_impl() { return; } } // end namespace detail custom_operations_plugin::custom_operations_plugin() : my( new detail::custom_operations_plugin_impl(*this) ) { } custom_operations_plugin::~custom_operations_plugin() { } std::string custom_operations_plugin::plugin_name()const { return "custom_operations"; } std::string custom_operations_plugin::plugin_description()const { return "Stores arbitrary data for accounts by creating specially crafted custom operations."; } void custom_operations_plugin::plugin_set_program_options( boost::program_options::options_description& cli, boost::program_options::options_description& cfg ) { cli.add_options() ("custom-operations-start-after-block", boost::program_options::value<uint32_t>(), "Start processing custom operations transactions with the plugin only after this block(1)") ; cfg.add(cli); } void custom_operations_plugin::plugin_initialize(const boost::program_options::variables_map& options) { database().add_index< primary_index< account_storage_index > >(); if (options.count("custom-operations-start-after-block")) { my->_after_block = options["elasticsearch-bulk-replay"].as<uint32_t>(); } database().applied_block.connect( [this]( const signed_block& b) { if( b.block_num() >= my->_after_block ) my->onBlock(); } ); } void custom_operations_plugin::plugin_startup() { ilog("custom_operations: plugin_startup() begin"); } } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) Stefan Tr�ger (stefantroeger@gmx.net) 2015 * * Copyright (c) Alexander Golubev (Fat-Zer) <fatzer2@gmail.com> 2015 * * * * This file is part of the FreeCAD CAx development system. * * * * 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., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #include <string> #endif #include <Base/Exception.h> #include <Base/Placement.h> #include <App/Document.h> #include "OriginFeature.h" #include "Origin.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif using namespace App; PROPERTY_SOURCE(App::Origin, App::DocumentObject) const char* Origin::AxisRoles[3] = {"X_Axis", "Y_Axis", "Z_Axis"}; const char* Origin::PlaneRoles[3] = {"XY_Plane", "XZ_Plane", "YZ_Plane"}; Origin::Origin(void) { ADD_PROPERTY_TYPE ( OriginFeatures, (0), 0, App::Prop_Hidden, "Axis and baseplanes controlled by the origin" ); } Origin::~Origin(void) { } App::OriginFeature *Origin::getOriginFeature( const char *role) const { const auto & features = OriginFeatures.getValues (); auto featIt = std::find_if (features.begin(), features.end(), [role] (App::DocumentObject *obj) { return obj->isDerivedFrom ( App::OriginFeature::getClassTypeId () ) && strcmp (static_cast<App::OriginFeature *>(obj)->Role.getValue(), role) == 0; } ); if (featIt != features.end()) { return static_cast<App::OriginFeature *>(*featIt); } else { std::stringstream err; err << "Origin \"" << getNameInDocument () << "\" doesn't contain feature with role \"" << role << '"'; throw Base::Exception ( err.str().c_str () ); } } App::Line *Origin::getAxis( const char *role ) const { App::OriginFeature *feat = getOriginFeature (role); if ( feat->isDerivedFrom(App::Line::getClassTypeId () ) ) { return static_cast<App::Line *> (feat); } else { std::stringstream err; err << "Origin \"" << getNameInDocument () << "\" contains bad Axis object for role \"" << role << '"'; throw Base::Exception ( err.str().c_str () ); } } App::Plane *Origin::getPlane( const char *role ) const { App::OriginFeature *feat = getOriginFeature (role); if ( feat->isDerivedFrom(App::Plane::getClassTypeId () ) ) { return static_cast<App::Plane *> (feat); } else { std::stringstream err; err << "Origin \"" << getNameInDocument () << "\" comtains bad Plane object for role \"" << role << '"'; throw Base::Exception ( err.str().c_str () ); } } bool Origin::hasObject (DocumentObject *obj) const { const auto & features = OriginFeatures.getValues (); return std::find (features.begin(), features.end(), obj) != features.end (); } short Origin::mustExecute(void) const { if (OriginFeatures.isTouched ()) { return 1; } else { return DocumentObject::mustExecute(); } } App::DocumentObjectExecReturn *Origin::execute(void) { try { // try to find all base axis and planes in the origin for (const char* role: AxisRoles) { App::Line *axis = getAxis (role); assert(axis); } for (const char* role: PlaneRoles) { App::Plane *plane = getPlane (role); assert(plane); } } catch (const Base::Exception &ex) { setError (); return new App::DocumentObjectExecReturn ( ex.what () ); } return DocumentObject::execute (); } void Origin::setupObject () { const static struct { const Base::Type type; const char *role; Base::Rotation rot; } setupData [] = { {App::Line::getClassTypeId(), "X_Axis", Base::Rotation () }, {App::Line::getClassTypeId(), "Y_Axis", Base::Rotation ( Base::Vector3d (1,1,1), M_PI*2/3 ) }, {App::Line::getClassTypeId(), "Z_Axis", Base::Rotation ( Base::Vector3d (1,1,1), M_PI*4/3 ) }, {App::Plane::getClassTypeId (), "XY_Plane", Base::Rotation () }, {App::Plane::getClassTypeId (), "XZ_Plane", Base::Rotation ( Base::Vector3d (0,1,1), M_PI ), }, {App::Plane::getClassTypeId (), "YZ_Plane", Base::Rotation ( Base::Vector3d (1,1,1), M_PI*2/3 ) }, }; App::Document *doc = getDocument (); std::vector<App::DocumentObject *> links; for (auto data: setupData) { std::string objName = doc->getUniqueObjectName ( data.role ); App::DocumentObject *featureObj = doc->addObject ( data.type.getName(), objName.c_str () ); assert ( featureObj && featureObj->isDerivedFrom ( App::OriginFeature::getClassTypeId () ) ); App::OriginFeature *feature = static_cast <App::OriginFeature *> ( featureObj ); feature->Placement.setValue ( Base::Placement ( Base::Vector3d (), data.rot ) ); feature->Role.setValue ( data.role ); links.push_back (feature); } OriginFeatures.setValues (links); } void Origin::unsetupObject () { const auto &objsLnk = OriginFeatures.getValues (); // Copy to set to assert we won't call methode more then one time for each object std::set<App::DocumentObject *> objs (objsLnk.begin(), objsLnk.end()); // Remove all controlled objects for (auto obj: objs ) { // Check that previous deletes wasn't inderectly removed one of our objects const auto &objsLnk = OriginFeatures.getValues (); if ( std::find(objsLnk.begin(), objsLnk.end(), obj) != objsLnk.end()) { if ( ! obj->isDeleting () ) { obj->getDocument ()->remObject (obj->getNameInDocument()); } } } } <commit_msg>PartDesign: reverse XZ plane to match legacy orientations<commit_after>/*************************************************************************** * Copyright (c) Stefan Tr�ger (stefantroeger@gmx.net) 2015 * * Copyright (c) Alexander Golubev (Fat-Zer) <fatzer2@gmail.com> 2015 * * * * This file is part of the FreeCAD CAx development system. * * * * 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., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #include <string> #endif #include <Base/Exception.h> #include <Base/Placement.h> #include <App/Document.h> #include "OriginFeature.h" #include "Origin.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif using namespace App; PROPERTY_SOURCE(App::Origin, App::DocumentObject) const char* Origin::AxisRoles[3] = {"X_Axis", "Y_Axis", "Z_Axis"}; const char* Origin::PlaneRoles[3] = {"XY_Plane", "XZ_Plane", "YZ_Plane"}; Origin::Origin(void) { ADD_PROPERTY_TYPE ( OriginFeatures, (0), 0, App::Prop_Hidden, "Axis and baseplanes controlled by the origin" ); } Origin::~Origin(void) { } App::OriginFeature *Origin::getOriginFeature( const char *role) const { const auto & features = OriginFeatures.getValues (); auto featIt = std::find_if (features.begin(), features.end(), [role] (App::DocumentObject *obj) { return obj->isDerivedFrom ( App::OriginFeature::getClassTypeId () ) && strcmp (static_cast<App::OriginFeature *>(obj)->Role.getValue(), role) == 0; } ); if (featIt != features.end()) { return static_cast<App::OriginFeature *>(*featIt); } else { std::stringstream err; err << "Origin \"" << getNameInDocument () << "\" doesn't contain feature with role \"" << role << '"'; throw Base::Exception ( err.str().c_str () ); } } App::Line *Origin::getAxis( const char *role ) const { App::OriginFeature *feat = getOriginFeature (role); if ( feat->isDerivedFrom(App::Line::getClassTypeId () ) ) { return static_cast<App::Line *> (feat); } else { std::stringstream err; err << "Origin \"" << getNameInDocument () << "\" contains bad Axis object for role \"" << role << '"'; throw Base::Exception ( err.str().c_str () ); } } App::Plane *Origin::getPlane( const char *role ) const { App::OriginFeature *feat = getOriginFeature (role); if ( feat->isDerivedFrom(App::Plane::getClassTypeId () ) ) { return static_cast<App::Plane *> (feat); } else { std::stringstream err; err << "Origin \"" << getNameInDocument () << "\" comtains bad Plane object for role \"" << role << '"'; throw Base::Exception ( err.str().c_str () ); } } bool Origin::hasObject (DocumentObject *obj) const { const auto & features = OriginFeatures.getValues (); return std::find (features.begin(), features.end(), obj) != features.end (); } short Origin::mustExecute(void) const { if (OriginFeatures.isTouched ()) { return 1; } else { return DocumentObject::mustExecute(); } } App::DocumentObjectExecReturn *Origin::execute(void) { try { // try to find all base axis and planes in the origin for (const char* role: AxisRoles) { App::Line *axis = getAxis (role); assert(axis); } for (const char* role: PlaneRoles) { App::Plane *plane = getPlane (role); assert(plane); } } catch (const Base::Exception &ex) { setError (); return new App::DocumentObjectExecReturn ( ex.what () ); } return DocumentObject::execute (); } void Origin::setupObject () { const static struct { const Base::Type type; const char *role; Base::Rotation rot; } setupData [] = { {App::Line::getClassTypeId(), "X_Axis", Base::Rotation () }, {App::Line::getClassTypeId(), "Y_Axis", Base::Rotation ( Base::Vector3d (1,1,1), M_PI*2/3 ) }, {App::Line::getClassTypeId(), "Z_Axis", Base::Rotation ( Base::Vector3d (1,1,1), M_PI*4/3 ) }, {App::Plane::getClassTypeId (), "XY_Plane", Base::Rotation () }, {App::Plane::getClassTypeId (), "XZ_Plane", Base::Rotation ( 1.0, 0.0, 0.0, 1.0 ), }, {App::Plane::getClassTypeId (), "YZ_Plane", Base::Rotation ( Base::Vector3d (1,1,1), M_PI*2/3 ) }, }; App::Document *doc = getDocument (); std::vector<App::DocumentObject *> links; for (auto data: setupData) { std::string objName = doc->getUniqueObjectName ( data.role ); App::DocumentObject *featureObj = doc->addObject ( data.type.getName(), objName.c_str () ); assert ( featureObj && featureObj->isDerivedFrom ( App::OriginFeature::getClassTypeId () ) ); App::OriginFeature *feature = static_cast <App::OriginFeature *> ( featureObj ); feature->Placement.setValue ( Base::Placement ( Base::Vector3d (), data.rot ) ); feature->Role.setValue ( data.role ); links.push_back (feature); } OriginFeatures.setValues (links); } void Origin::unsetupObject () { const auto &objsLnk = OriginFeatures.getValues (); // Copy to set to assert we won't call methode more then one time for each object std::set<App::DocumentObject *> objs (objsLnk.begin(), objsLnk.end()); // Remove all controlled objects for (auto obj: objs ) { // Check that previous deletes wasn't inderectly removed one of our objects const auto &objsLnk = OriginFeatures.getValues (); if ( std::find(objsLnk.begin(), objsLnk.end(), obj) != objsLnk.end()) { if ( ! obj->isDeleting () ) { obj->getDocument ()->remObject (obj->getNameInDocument()); } } } } <|endoftext|>
<commit_before>#include <SCD/CD/CD_Pair.h> #include <SCD/CD/CD_Simplex.h> #include <SCD/CD/CD_SimplexEnhanced.h> #include <iostream> //#ifndef NOGLUT //#define SHOW_LAST_SIMLPEX //#endif //#define CD_SAFE_VERSION //use when the scalar has a perfect precision #define PENETRATION_DEPTH //#define CD_PAIR_VERBOUS_MODE //#define CD_ITERATION_LIMIT 50 //use when the real-time constraints are too high fo current performances while keeping the same global precision. //no theoretical guarantee on the precision nor the collision-safeness when used - Default value is 20 #define _EPSILON_ 1e-24 #define _PRECISION_ 1e-6 using namespace SCD; inline Vector3 LinearSystem(Matrix3x3& A, Vector3& y) { Matrix3x3 B; A.Inversion(B); return (B*y); } CD_Pair::CD_Pair(S_Object *obj1, S_Object *obj2):sObj1_(obj1),sObj2_(obj2),lastDirection_(1.0,0.0,0.0), lastFeature1_(-1),lastFeature2_(-1),distance_(0),stamp1_(sObj1_->checkStamp()),stamp2_(sObj2_->checkStamp()), precision_(_PRECISION_),epsilon_(_EPSILON_),witPointsAreComputed_(false),s1_(Point3()),s2_(Point3()),s_(Point3()),sp_(Point3()),depthPair(obj1,obj2) { --stamp1_; --stamp2_; depthPair.setRelativePrecision(_PRECISION_); depthPair.setEpsilon(_EPSILON_); } CD_Pair::~CD_Pair(void) { } Scalar CD_Pair::getDistance() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { return distance_; } else { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); return distance_; } } Scalar CD_Pair::getDistanceWithoutPenetrationDepth() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { if (distance_ > 0) return distance_; return 0; } else { GJK(); if (collision_) return 0; return distance_; } } Scalar CD_Pair::reComputeClosestPoints(Point3& p1,Point3& p2) { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); witPoints(p1,p2); return distance_; } void CD_Pair::setRelativePrecision(Scalar s) { precision_=s*s; depthPair.setRelativePrecision(s); } void CD_Pair::setEpsilon(Scalar s) { epsilon_=s; depthPair.setEpsilon(s); } Scalar CD_Pair::getClosestPoints(Point3 &p1, Point3 &p2) { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { if (!witPointsAreComputed_) { witPointsAreComputed_=true; witPoints(p1,p2); } p1=p1_; p2=p2_; return distance_; } else { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); witPoints(p1,p2); witPointsAreComputed_=true; return distance_; } } Scalar CD_Pair::penetrationDepth() { #ifdef PENETRATION_DEPTH if (collision_)//Objects are in collision { distance_=-depthPair.getPenetrationDepth(lastDirection_,p1_,p2_,sp_,s1_,s2_); if (distance_<0) { lastDirection_.Set(0,1,0); } return distance_; } else { return distance_; } #else return distance_; #endif } Scalar CD_Pair::GJK() { Vector3& v=lastDirection_; #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"#####GJK START######"<<std::endl; #endif witPointsAreComputed_=false; int& lf1=lastFeature1_; int& lf2=lastFeature2_; Point3 sup1=sObj1_->support(v,lf1); Point3 sup2=sObj2_->support(-v,lf2); #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"Last features"<<lf1<<" "<<lf2<<std::endl; #endif Point3 sup(sup1); sup-=sup2; s1_=sup1; s2_=sup2; s_=sup; sp_=sup; CD_SimplexKeptPoints k; projectionComputed_=false; bool cont=true; Point3 proj; Vector3 S01; Vector3 S02; Scalar a1,a2,a3,a4,a5,a6; distance_=infinity; #ifdef CD_ITERATION_LIMIT int cnt=0; #endif while (cont) { #ifdef CD_ITERATION_LIMIT if (++cnt>CD_ITERATION_LIMIT) break; //the iterations number limit has been reached #endif switch (s_.getType()) { case CD_Triangle: { S01=s_[1]; S01-=s_[2]; S02=s_[0]; S02-=s_[2]; a1=S01*s_[0],a2=S01*s_[1],a3=S01*s_[2],a4=S02*s_[0],a5=S02*s_[1],a6=S02*s_[2]; lambda0_=a2*a6-a3*a5; lambda1_=a3*a4-a1*a6; lambda2_=a1*a5-a2*a4; det_=1/(lambda0_+lambda1_+lambda2_); lambda0_*=det_; lambda1_*=det_; lambda2_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_+s_[2]*lambda2_; v=-proj; break; } case CD_Segment: { S01=s_[1]; S01-=s_[0]; lambda0_=S01*s_[1]; lambda1_=-(S01*s_[0]); det_=1/(lambda0_+lambda1_); lambda0_*=det_; lambda1_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_; v=-proj; break; } default: { proj=s_[0]; v=-proj; } } Scalar newdist=v.normsquared(); if (distance_ <= newdist) //the distance is not monotonous { cont=false; } else { if ( (distance_= newdist)<=sp_.farthestPointDistance()*epsilon_)//v is considered zero { collision_=true; cont=false; } else { sup1=sObj1_->support(v,lf1); sup2=sObj2_->support(-v,lf2); #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"Last features"<<lf1<<" "<<lf2<<std::endl; std::cout<<"supports"<<sup1<<" "<<sup2<<std::endl; # ifdef CD_ITERATION_LIMIT std::cout<<"Iterations"<<cnt<<std::endl; # endif #endif sup=sup1; sup-=sup2; if ((distance_-proj*sup)<(precision_*distance_))//precision reached { collision_=false; cont=false; projectionComputed_=true; } else { sp_+=sup; sp_.updateVectors(); #ifndef SAFE_VERSION if (sp_.isAffinelyDependent()) { cont=false; collision_=false; projectionComputed_=true; } else #endif { sp_.getClosestSubSimplexGJK(k); sp_.filter(k); s1_+=sup1; s2_+=sup2; if (sp_.getType()==CD_Tetrahedron) { cont=false; s1_+=sup1; s2_+=sup2; collision_=true; } else { s_=sp_; s1_.filter(k); s2_.filter(k); } } } } } } #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"#####GJK END######"<<std::endl; #endif return distance_; } void CD_Pair::setVector(const Vector3 &v) { lastDirection_=v; } void CD_Pair::witPoints(Point3 &p1, Point3 &p2) { Point3 proj; Vector3& v=lastDirection_; if (collision_) { p1=p1_; p2=p2_; return; } switch (s_.getType()) { case CD_Triangle: { { if (!projectionComputed_) { Vector3 S01(s_[1]-s_[2]), S02(s_[0]-s_[2]); Scalar a1=S01*s_[0],a2=S01*s_[1],a3=S01*s_[2],a4=S02*s_[0],a5=S02*s_[1],a6=S02*s_[2]; lambda0_=a2*a6-a3*a5; lambda1_=a3*a4-a1*a6; lambda2_=a1*a5-a2*a4; det_=1/(lambda0_+lambda1_+lambda2_); lambda0_*=det_; lambda1_*=det_; lambda2_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_+s_[2]*lambda2_; v=-proj; } p1_=p1=s1_[0]*lambda0_+s1_[1]*lambda1_+s1_[2]*lambda2_; p2_=p2=s2_[0]*lambda0_+s2_[1]*lambda1_+s2_[2]*lambda2_; } #ifdef SHOW_LAST_SIMLPEX glDisable(GL_DEPTH_TEST); glColor4d(0,0.5,1,0.5); glBegin(GL_TRIANGLES); glVertex3d(s1_[0][0],s1_[0][1],s1_[0][2]); glVertex3d(s1_[1][0],s1_[1][1],s1_[1][2]); glVertex3d(s1_[2][0],s1_[2][1],s1_[2][2]); glVertex3d(s2_[0][0],s2_[0][1],s2_[0][2]); glVertex3d(s2_[1][0],s2_[1][1],s2_[1][2]); glVertex3d(s2_[2][0],s2_[2][1],s2_[2][2]); glEnd(); glEnable(GL_DEPTH_TEST); #endif return; } case CD_Segment: { if (!projectionComputed_) { Vector3 S01(s_[1]-s_[0]); lambda1_=-(S01*s_[0]); lambda0_=S01*s_[1]; det_=1/(lambda0_+lambda1_); lambda0_*=det_; lambda1_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_; v=-proj; } p1_=p1=s1_[0]*lambda0_+s1_[1]*lambda1_; p2_=p2=s2_[0]*lambda0_+s2_[1]*lambda1_; #ifdef SHOW_LAST_SIMLPEX glDisable(GL_DEPTH_TEST); glColor4d(0,0.5,1,0.5); glBegin(GL_LINES); glVertex3d(s1_[0][0],s1_[0][1],s1_[0][2]); glVertex3d(s1_[1][0],s1_[1][1],s1_[1][2]); glVertex3d(s2_[0][0],s2_[0][1],s2_[0][2]); glVertex3d(s2_[1][0],s2_[1][1],s2_[1][2]); glEnd(); glEnable(GL_DEPTH_TEST); #endif return ; } default: { p1_=p1=s1_[0]; p2_=p2=s2_[0]; return ; } } } bool CD_Pair::isInCollision() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { return collision_; } else { Scalar prec=precision_; precision_=1; GJK(); precision_=prec; return collision_; } } <commit_msg>Code factorization<commit_after>#include <SCD/CD/CD_Pair.h> #include <SCD/CD/CD_Simplex.h> #include <SCD/CD/CD_SimplexEnhanced.h> #include <iostream> //#ifndef NOGLUT //#define SHOW_LAST_SIMLPEX //#endif //#define CD_SAFE_VERSION //use when the scalar has a perfect precision #define PENETRATION_DEPTH //#define CD_PAIR_VERBOUS_MODE //#define CD_ITERATION_LIMIT 50 //use when the real-time constraints are too high fo current performances while keeping the same global precision. //no theoretical guarantee on the precision nor the collision-safeness when used - Default value is 20 #define _EPSILON_ 1e-24 #define _PRECISION_ 1e-6 using namespace SCD; inline Vector3 LinearSystem(Matrix3x3& A, Vector3& y) { Matrix3x3 B; A.Inversion(B); return (B*y); } CD_Pair::CD_Pair(S_Object *obj1, S_Object *obj2):sObj1_(obj1),sObj2_(obj2),lastDirection_(1.0,0.0,0.0), lastFeature1_(-1),lastFeature2_(-1),distance_(0),stamp1_(sObj1_->checkStamp()),stamp2_(sObj2_->checkStamp()), precision_(_PRECISION_),epsilon_(_EPSILON_),witPointsAreComputed_(false),s1_(Point3()),s2_(Point3()),s_(Point3()),sp_(Point3()),depthPair(obj1,obj2) { --stamp1_; --stamp2_; depthPair.setRelativePrecision(_PRECISION_); depthPair.setEpsilon(_EPSILON_); } CD_Pair::~CD_Pair(void) { } Scalar CD_Pair::getDistance() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { return distance_; } else { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); return distance_; } } Scalar CD_Pair::getDistanceWithoutPenetrationDepth() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { if (distance_ > 0) return distance_; return 0; } else { GJK(); if (collision_) return 0; return distance_; } } Scalar CD_Pair::reComputeClosestPoints(Point3& p1,Point3& p2) { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); witPoints(p1,p2); return distance_; } void CD_Pair::setRelativePrecision(Scalar s) { precision_=s*s; depthPair.setRelativePrecision(s); } void CD_Pair::setEpsilon(Scalar s) { epsilon_=s; depthPair.setEpsilon(s); } Scalar CD_Pair::getClosestPoints(Point3 &p1, Point3 &p2) { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { if (!witPointsAreComputed_) { witPointsAreComputed_=true; witPoints(p1,p2); } p1=p1_; p2=p2_; return distance_; } else { stamp1_=sObj1_->checkStamp(); stamp2_=sObj2_->checkStamp(); GJK(); penetrationDepth(); witPoints(p1,p2); witPointsAreComputed_=true; return distance_; } } Scalar CD_Pair::penetrationDepth() { #ifdef PENETRATION_DEPTH if (collision_)//Objects are in collision { distance_=-depthPair.getPenetrationDepth(lastDirection_,p1_,p2_,sp_,s1_,s2_); if (distance_<0) { lastDirection_.Set(0,1,0); } return distance_; } else { return distance_; } #else return distance_; #endif } Scalar CD_Pair::GJK() { Vector3& v=lastDirection_; #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"#####GJK START######"<<std::endl; #endif witPointsAreComputed_=false; int& lf1=lastFeature1_; int& lf2=lastFeature2_; Point3 sup1=sObj1_->support(v,lf1); Point3 sup2=sObj2_->support(-v,lf2); #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"Last features"<<lf1<<" "<<lf2<<std::endl; #endif Point3 sup(sup1); sup-=sup2; s1_=sup1; s2_=sup2; s_=sup; sp_=sup; CD_SimplexKeptPoints k; projectionComputed_=false; bool cont=true; Point3 proj; Vector3 S01; Vector3 S02; Scalar a1,a2,a3,a4,a5,a6; distance_=infinity; #ifdef CD_ITERATION_LIMIT int cnt=0; #endif while (cont) { #ifdef CD_ITERATION_LIMIT if (++cnt>CD_ITERATION_LIMIT) break; //the iterations number limit has been reached #endif switch (s_.getType()) { case CD_Triangle: { S01=s_[1]; S01-=s_[2]; S02=s_[0]; S02-=s_[2]; a1=S01*s_[0],a2=S01*s_[1],a3=S01*s_[2],a4=S02*s_[0],a5=S02*s_[1],a6=S02*s_[2]; lambda0_=a2*a6-a3*a5; lambda1_=a3*a4-a1*a6; lambda2_=a1*a5-a2*a4; det_=1/(lambda0_+lambda1_+lambda2_); lambda0_*=det_; lambda1_*=det_; lambda2_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_+s_[2]*lambda2_; break; } case CD_Segment: { S01=s_[1]; S01-=s_[0]; lambda0_=S01*s_[1]; lambda1_=-(S01*s_[0]); det_=1/(lambda0_+lambda1_); lambda0_*=det_; lambda1_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_; break; } default: { proj=s_[0]; } } Scalar newdist=proj.normsquared(); if (distance_ <= newdist) //the distance is not monotonous { cont=false; } else { v=-proj; distance_= newdist; if ( distance_<=sp_.farthestPointDistance()*epsilon_)//v is considered zero { collision_=true; cont=false; } else { sup1=sObj1_->support(v,lf1); sup2=sObj2_->support(-v,lf2); #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"Last features"<<lf1<<" "<<lf2<<std::endl; std::cout<<"supports"<<sup1<<" "<<sup2<<std::endl; # ifdef CD_ITERATION_LIMIT std::cout<<"Iterations"<<cnt<<std::endl; # endif #endif sup=sup1; sup-=sup2; if ((distance_-proj*sup)<(precision_*distance_))//precision reached { collision_=false; cont=false; projectionComputed_=true; } else { sp_+=sup; sp_.updateVectors(); #ifndef SAFE_VERSION if (sp_.isAffinelyDependent()) { cont=false; collision_=false; projectionComputed_=true; } else #endif { sp_.getClosestSubSimplexGJK(k); sp_.filter(k); s1_+=sup1; s2_+=sup2; if (sp_.getType()==CD_Tetrahedron) { cont=false; s1_+=sup1; s2_+=sup2; collision_=true; } else { s_=sp_; s1_.filter(k); s2_.filter(k); } } } } } } #ifdef CD_PAIR_VERBOUS_MODE std::cout<<"#####GJK END######"<<std::endl; #endif return distance_; } void CD_Pair::setVector(const Vector3 &v) { lastDirection_=v; } void CD_Pair::witPoints(Point3 &p1, Point3 &p2) { Point3 proj; Vector3& v=lastDirection_; if (collision_) { p1=p1_; p2=p2_; return; } switch (s_.getType()) { case CD_Triangle: { { if (!projectionComputed_) { Vector3 S01(s_[1]-s_[2]), S02(s_[0]-s_[2]); Scalar a1=S01*s_[0],a2=S01*s_[1],a3=S01*s_[2],a4=S02*s_[0],a5=S02*s_[1],a6=S02*s_[2]; lambda0_=a2*a6-a3*a5; lambda1_=a3*a4-a1*a6; lambda2_=a1*a5-a2*a4; det_=1/(lambda0_+lambda1_+lambda2_); lambda0_*=det_; lambda1_*=det_; lambda2_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_+s_[2]*lambda2_; v=-proj; } p1_=p1=s1_[0]*lambda0_+s1_[1]*lambda1_+s1_[2]*lambda2_; p2_=p2=s2_[0]*lambda0_+s2_[1]*lambda1_+s2_[2]*lambda2_; } #ifdef SHOW_LAST_SIMLPEX glDisable(GL_DEPTH_TEST); glColor4d(0,0.5,1,0.5); glBegin(GL_TRIANGLES); glVertex3d(s1_[0][0],s1_[0][1],s1_[0][2]); glVertex3d(s1_[1][0],s1_[1][1],s1_[1][2]); glVertex3d(s1_[2][0],s1_[2][1],s1_[2][2]); glVertex3d(s2_[0][0],s2_[0][1],s2_[0][2]); glVertex3d(s2_[1][0],s2_[1][1],s2_[1][2]); glVertex3d(s2_[2][0],s2_[2][1],s2_[2][2]); glEnd(); glEnable(GL_DEPTH_TEST); #endif return; } case CD_Segment: { if (!projectionComputed_) { Vector3 S01(s_[1]-s_[0]); lambda1_=-(S01*s_[0]); lambda0_=S01*s_[1]; det_=1/(lambda0_+lambda1_); lambda0_*=det_; lambda1_*=det_; proj=s_[0]*lambda0_+s_[1]*lambda1_; v=-proj; } p1_=p1=s1_[0]*lambda0_+s1_[1]*lambda1_; p2_=p2=s2_[0]*lambda0_+s2_[1]*lambda1_; #ifdef SHOW_LAST_SIMLPEX glDisable(GL_DEPTH_TEST); glColor4d(0,0.5,1,0.5); glBegin(GL_LINES); glVertex3d(s1_[0][0],s1_[0][1],s1_[0][2]); glVertex3d(s1_[1][0],s1_[1][1],s1_[1][2]); glVertex3d(s2_[0][0],s2_[0][1],s2_[0][2]); glVertex3d(s2_[1][0],s2_[1][1],s2_[1][2]); glEnd(); glEnable(GL_DEPTH_TEST); #endif return ; } default: { p1_=p1=s1_[0]; p2_=p2=s2_[0]; return ; } } } bool CD_Pair::isInCollision() { if ((stamp1_==sObj1_->checkStamp())&&(stamp2_==sObj2_->checkStamp())) { return collision_; } else { Scalar prec=precision_; precision_=1; GJK(); precision_=prec; return collision_; } } <|endoftext|>
<commit_before>#include <iostream> #include <libport/unistd.h> #include <libport/cstdio> #include <libport/fd-stream.hh> namespace libport { FdStream::FdStream(fd_type write, fd_type read) : std::iostream(buf_ = new FdBuf(write, read)) { rdbuf(buf_); } FdStream::~FdStream() { delete buf_; } void FdStream::own_fd(bool v) { buf_->own_fd(v); } bool FdStream::own_fd() const { return buf_->own_fd(); } FdBuf::FdBuf(fd_type write, fd_type read) : write_(write) , read_(read) , own_(false) { setg(ibuf_, ibuf_, ibuf_); setp(obuf_, obuf_ + BUFSIZ - 1); } FdBuf::~FdBuf() { sync(); if (own_) { close(write_); close(read_); } } int FdBuf::underflow() { ssize_t c = read(read_, ibuf_, BUFSIZ); if (c == 0) { setg(ibuf_, ibuf_, ibuf_); return EOF; } setg(ibuf_, ibuf_, ibuf_ + c); return ibuf_[0]; } int FdBuf::overflow(int c) { obuf_[BUFSIZ - 1] = c; setp(obuf_ + BUFSIZ, obuf_ + BUFSIZ - 1); sync(); return EOF + 1; // "A value different from EOF" } int FdBuf::sync() { char* data = obuf_; while (data < pptr()) { // FIXME: don't busy loop ssize_t n = write(write_, data, pptr() - data); data += n; } return 0; // Success } void FdBuf::own_fd(bool v) { own_ = v; } bool FdBuf::own_fd() const { return own_; } unsigned FdStream::fd_read() { return buf_->fd_read(); } unsigned FdStream::fd_write() { return buf_->fd_write(); } unsigned FdBuf::fd_read() { return read_; } unsigned FdBuf::fd_write() { return write_; } } <commit_msg>Revert bad fd-stream fix.<commit_after>#include <iostream> #include <libport/unistd.h> #include <libport/cstdio> #include <libport/fd-stream.hh> namespace libport { FdStream::FdStream(fd_type write, fd_type read) : std::iostream(buf_ = new FdBuf(write, read)) { rdbuf(buf_); } FdStream::~FdStream() { delete buf_; } void FdStream::own_fd(bool v) { buf_->own_fd(v); } bool FdStream::own_fd() const { return buf_->own_fd(); } FdBuf::FdBuf(fd_type write, fd_type read) : write_(write) , read_(read) , own_(false) { setg(ibuf_, ibuf_, ibuf_); setp(obuf_, obuf_ + BUFSIZ - 1); } FdBuf::~FdBuf() { sync(); if (own_) { close(write_); close(read_); } } int FdBuf::underflow() { ssize_t c = read(read_, ibuf_, BUFSIZ); if (c == 0) { setg(ibuf_, ibuf_, ibuf_); return EOF; } setg(ibuf_, ibuf_, ibuf_ + c); return ibuf_[0]; } int FdBuf::overflow(int c) { obuf_[BUFSIZ - 1] = c; setp(obuf_ + BUFSIZ, 0); sync(); return EOF + 1; // "A value different from EOF" } int FdBuf::sync() { if (pptr() - obuf_) { write(write_, obuf_, pptr() - obuf_); setp(obuf_, obuf_ + BUFSIZ - 1); } return 0; // Success } void FdBuf::own_fd(bool v) { own_ = v; } bool FdBuf::own_fd() const { return own_; } unsigned FdStream::fd_read() { return buf_->fd_read(); } unsigned FdStream::fd_write() { return buf_->fd_write(); } unsigned FdBuf::fd_read() { return read_; } unsigned FdBuf::fd_write() { return write_; } } <|endoftext|>
<commit_before>#include <pistache/client.h> #include <pistache/cookie.h> #include <pistache/endpoint.h> #include <pistache/http.h> #include "gtest/gtest.h" #include <chrono> #include <unordered_map> using namespace Pistache; struct CookieHandler : public Http::Handler { HTTP_PROTOTYPE(CookieHandler) void onRequest(const Http::Request& request, Http::ResponseWriter response) override { // Synthetic behaviour, just for testing purposes for(auto&& cookie: request.cookies()) { response.cookies().add(cookie); } response.send(Http::Code::Ok, "Ok"); } }; TEST(http_client_test, one_client_with_one_request_with_cookies) { const std::string address = "localhost:9085"; Http::Endpoint server(address); auto flags = Tcp::Options::InstallSignalHandler | Tcp::Options::ReuseAddr; auto server_opts = Http::Endpoint::options().flags(flags); server.init(server_opts); server.setHandler(Http::make_handler<CookieHandler>()); server.serveThreaded(); Http::Client client; client.init(); std::vector<Async::Promise<Http::Response>> responses; const std::string name1 = "FOO"; const std::string value1 = "bar"; auto cookie1 = Http::Cookie(name1, value1); const std::string name2 = "FIZZ"; const std::string value2 = "Buzz"; auto cookie2 = Http::Cookie(name2, value2); const std::string name3 = "Key"; const std::string value3 = "value"; auto cookie3 = Http::Cookie(name3, value3); auto rb = client.get(address).cookie(cookie1).cookie(cookie2).cookie(cookie3); auto response = rb.send(); std::unordered_map<std::string, std::string> cookiesStorages; response.then([&](Http::Response rsp) { for (auto&& cookie: rsp.cookies()) { cookiesStorages[cookie.name] = cookie.value; std::cout << "get: " << cookie.name << "\n"; } }, Async::IgnoreException); responses.push_back(std::move(response)); auto sync = Async::whenAll(responses.begin(), responses.end()); Async::Barrier<std::vector<Http::Response>> barrier(sync); barrier.wait_for(std::chrono::seconds(5)); server.shutdown(); client.shutdown(); ASSERT_NE(cookiesStorages.find(name1), cookiesStorages.end()); ASSERT_EQ(cookiesStorages[name1], value1); ASSERT_NE(cookiesStorages.find(name2), cookiesStorages.end()); ASSERT_EQ(cookiesStorages[name2], value2); ASSERT_NE(cookiesStorages.find(name3), cookiesStorages.end()); ASSERT_EQ(cookiesStorages[name3], value3); } <commit_msg>Tiny code style fix<commit_after>#include <pistache/client.h> #include <pistache/cookie.h> #include <pistache/endpoint.h> #include <pistache/http.h> #include "gtest/gtest.h" #include <chrono> #include <unordered_map> using namespace Pistache; struct CookieHandler : public Http::Handler { HTTP_PROTOTYPE(CookieHandler) void onRequest(const Http::Request& request, Http::ResponseWriter response) override { // Synthetic behaviour, just for testing purposes for(auto&& cookie: request.cookies()) { response.cookies().add(cookie); } response.send(Http::Code::Ok, "Ok"); } }; TEST(http_client_test, one_client_with_one_request_with_cookies) { const std::string address = "localhost:9085"; Http::Endpoint server(address); auto flags = Tcp::Options::InstallSignalHandler | Tcp::Options::ReuseAddr; auto server_opts = Http::Endpoint::options().flags(flags); server.init(server_opts); server.setHandler(Http::make_handler<CookieHandler>()); server.serveThreaded(); Http::Client client; client.init(); std::vector<Async::Promise<Http::Response>> responses; const std::string name1 = "FOO"; const std::string value1 = "bar"; auto cookie1 = Http::Cookie(name1, value1); const std::string name2 = "FIZZ"; const std::string value2 = "Buzz"; auto cookie2 = Http::Cookie(name2, value2); const std::string name3 = "Key"; const std::string value3 = "value"; auto cookie3 = Http::Cookie(name3, value3); auto rb = client.get(address).cookie(cookie1).cookie(cookie2).cookie(cookie3); auto response = rb.send(); std::unordered_map<std::string, std::string> cookiesStorages; response.then([&](Http::Response rsp) { for (auto&& cookie: rsp.cookies()) { cookiesStorages[cookie.name] = cookie.value; std::cout << "get: " << cookie.name << "\n"; } }, Async::IgnoreException); responses.push_back(std::move(response)); auto sync = Async::whenAll(responses.begin(), responses.end()); Async::Barrier<std::vector<Http::Response>> barrier(sync); barrier.wait_for(std::chrono::seconds(5)); server.shutdown(); client.shutdown(); ASSERT_NE(cookiesStorages.find(name1), cookiesStorages.end()); ASSERT_EQ(cookiesStorages[name1], value1); ASSERT_NE(cookiesStorages.find(name2), cookiesStorages.end()); ASSERT_EQ(cookiesStorages[name2], value2); ASSERT_NE(cookiesStorages.find(name3), cookiesStorages.end()); ASSERT_EQ(cookiesStorages[name3], value3); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Vesched_infoon 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 "cyber/scheduler/scheduler.h" #include <utility> #include "cyber/common/global_data.h" #include "cyber/common/util.h" #include "cyber/data/data_visitor.h" #include "cyber/scheduler/policy/classic.h" #include "cyber/scheduler/policy/task_choreo.h" #include "cyber/scheduler/processor.h" #include "cyber/scheduler/processor_context.h" namespace apollo { namespace cyber { namespace scheduler { using apollo::cyber::common::GlobalData; Scheduler::Scheduler() : stop_(false) { auto gconf = GlobalData::Instance()->Config(); for (auto& conf : gconf.scheduler_conf().confs()) { sched_confs_[conf.process_name()] = conf; } SchedConf sconf; auto itr = sched_confs_.find(GlobalData::Instance()->ProcessName()); // default conf defined in proto will be used // if no specialized conf defined if (itr != sched_confs_.end()) { sconf = itr->second; } sched_policy_ = sconf.policy(); proc_num_ = sconf.proc_num(); task_pool_size_ = sconf.task_pool_size(); cpu_binding_start_index_ = sconf.cpu_binding_start_index(); for (auto& conf : gconf.choreo_conf()) { if (conf.process_name() == GlobalData::Instance()->ProcessName()) { for (auto& choreo : conf.choreos()) { cr_confs_[choreo.name()] = choreo; } } } CreateProcessor(); } void Scheduler::CreateProcessor() { for (uint32_t i = 0; i < proc_num_; i++) { auto proc = std::make_shared<Processor>(); proc->SetId(i); std::shared_ptr<ProcessorContext> ctx; switch (sched_policy_) { case SchedPolicy::CLASSIC: ctx.reset(new ClassicContext()); break; case SchedPolicy::CHOREO: ctx.reset(new TaskChoreoContext()); break; default: ctx.reset(new TaskChoreoContext()); break; } ctx->SetId(i); proc->BindContext(ctx); ctx->BindProc(proc); proc_ctxs_.emplace_back(ctx); proc->SetCpuBindingStartIndex( cpu_binding_start_index_); proc->Start(); } // For taskchoreo policy: put tasks w/o processor assigned to a classic pool. if (sched_policy_ == SchedPolicy::CHOREO) { for (uint32_t i = 0; i < task_pool_size_; i++) { auto proc = std::make_shared<Processor>(); std::shared_ptr<ProcessorContext> ctx; ctx.reset(classic_4_choreo_ = new ClassicContext()); proc->BindContext(ctx); ctx->BindProc(proc); proc_ctxs_.emplace_back(ctx); proc->Start(); } } } void Scheduler::ShutDown() { if (stop_.exchange(true)) { return; } for (auto& proc_ctx : proc_ctxs_) { proc_ctx->ShutDown(); } proc_ctxs_.clear(); } Scheduler::~Scheduler() {} bool Scheduler::CreateTask(const RoutineFactory& factory, const std::string& name) { return CreateTask(factory.create_routine(), name, factory.GetDataVisitor()); } bool Scheduler::CreateTask(std::function<void()>&& func, const std::string& name, std::shared_ptr<DataVisitorBase> visitor) { if (stop_) { AERROR << "scheduler is stoped, cannot create task!"; return false; } auto task_id = GlobalData::RegisterTaskName(name); { ReadLockGuard<AtomicRWLock> rg(rw_lock_); if (cr_ctx_.find(task_id) != cr_ctx_.end()) { AERROR << "Routine [" << name << "] has been exists"; return false; } cr_ctx_[task_id] = 0; } auto cr = std::make_shared<CRoutine>(func); cr->set_id(task_id); cr->set_name(name); Choreo conf; if (cr_confs_.find(name) != cr_confs_.end()) { conf = cr_confs_[name]; cr->set_priority(conf.priority()); if (conf.has_processor_index()) { auto proc_id = conf.processor_index(); cr->set_processor_id(proc_id); } } WriteLockGuard<AtomicRWLock> rg(rw_lock_); if (!proc_ctxs_[0]->DispatchTask(cr)) { return false; } if (visitor != nullptr) { visitor->RegisterNotifyCallback([this, task_id, name]() { if (stop_) { return; } this->NotifyProcessor(task_id); }); } return true; } bool Scheduler::NotifyTask(uint64_t task_id) { if (stop_) { return true; } return NotifyProcessor(task_id); } bool Scheduler::NotifyProcessor(uint64_t cr_id) { if (stop_) { return true; } ReadLockGuard<AtomicRWLock> rg(rw_lock_); auto itr = cr_ctx_.find(cr_id); if (itr != cr_ctx_.end()) { proc_ctxs_[itr->second]->Notify(cr_id); return true; } return false; } bool Scheduler::RemoveTask(const std::string& name) { if (stop_) { return true; } auto task_id = GlobalData::RegisterTaskName(name); { WriteLockGuard<AtomicRWLock> wg(rw_lock_); cr_ctx_.erase(task_id); } return RemoveCRoutine(task_id); } bool Scheduler::RemoveCRoutine(uint64_t cr_id) { if (stop_) { return true; } WriteLockGuard<AtomicRWLock> rw(rw_lock_); auto p = cr_ctx_.find(cr_id); if (p != cr_ctx_.end()) { cr_ctx_.erase(cr_id); proc_ctxs_[p->second]->RemoveCRoutine(cr_id); } return true; } } // namespace scheduler } // namespace cyber } // namespace apollo <commit_msg>framework: fix coredump<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Vesched_infoon 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 "cyber/scheduler/scheduler.h" #include <utility> #include "cyber/common/global_data.h" #include "cyber/common/util.h" #include "cyber/data/data_visitor.h" #include "cyber/scheduler/policy/classic.h" #include "cyber/scheduler/policy/task_choreo.h" #include "cyber/scheduler/processor.h" #include "cyber/scheduler/processor_context.h" namespace apollo { namespace cyber { namespace scheduler { using apollo::cyber::common::GlobalData; Scheduler::Scheduler() : stop_(false) { auto gconf = GlobalData::Instance()->Config(); for (auto& conf : gconf.scheduler_conf().confs()) { sched_confs_[conf.process_name()] = conf; } SchedConf sconf; auto itr = sched_confs_.find(GlobalData::Instance()->ProcessName()); // default conf defined in proto will be used // if no specialized conf defined if (itr != sched_confs_.end()) { sconf = itr->second; } sched_policy_ = sconf.policy(); proc_num_ = sconf.proc_num(); task_pool_size_ = sconf.task_pool_size(); cpu_binding_start_index_ = sconf.cpu_binding_start_index(); for (auto& conf : gconf.choreo_conf()) { if (conf.process_name() == GlobalData::Instance()->ProcessName()) { for (auto& choreo : conf.choreos()) { cr_confs_[choreo.name()] = choreo; } } } CreateProcessor(); } void Scheduler::CreateProcessor() { for (uint32_t i = 0; i < proc_num_; i++) { auto proc = std::make_shared<Processor>(); proc->SetId(i); std::shared_ptr<ProcessorContext> ctx; switch (sched_policy_) { case SchedPolicy::CLASSIC: ctx.reset(new ClassicContext()); break; case SchedPolicy::CHOREO: ctx.reset(new TaskChoreoContext()); break; default: ctx.reset(new TaskChoreoContext()); break; } ctx->SetId(i); proc->BindContext(ctx); ctx->BindProc(proc); proc_ctxs_.emplace_back(ctx); proc->SetCpuBindingStartIndex( cpu_binding_start_index_); proc->Start(); } // For taskchoreo policy: put tasks w/o processor assigned to a classic pool. if (sched_policy_ == SchedPolicy::CHOREO) { for (uint32_t i = 0; i < task_pool_size_; i++) { auto proc = std::make_shared<Processor>(); std::shared_ptr<ProcessorContext> ctx; ctx.reset(classic_4_choreo_ = new ClassicContext()); ctx->SetId(proc_num_ + i); proc->BindContext(ctx); ctx->BindProc(proc); proc_ctxs_.emplace_back(ctx); proc->SetCpuBindingStartIndex( cpu_binding_start_index_); proc->Start(); } } } void Scheduler::ShutDown() { if (stop_.exchange(true)) { return; } for (auto& proc_ctx : proc_ctxs_) { proc_ctx->ShutDown(); } proc_ctxs_.clear(); } Scheduler::~Scheduler() {} bool Scheduler::CreateTask(const RoutineFactory& factory, const std::string& name) { return CreateTask(factory.create_routine(), name, factory.GetDataVisitor()); } bool Scheduler::CreateTask(std::function<void()>&& func, const std::string& name, std::shared_ptr<DataVisitorBase> visitor) { if (stop_) { AERROR << "scheduler is stoped, cannot create task!"; return false; } auto task_id = GlobalData::RegisterTaskName(name); { ReadLockGuard<AtomicRWLock> rg(rw_lock_); if (cr_ctx_.find(task_id) != cr_ctx_.end()) { AERROR << "Routine [" << name << "] has been exists"; return false; } cr_ctx_[task_id] = 0; } auto cr = std::make_shared<CRoutine>(func); cr->set_id(task_id); cr->set_name(name); Choreo conf; if (cr_confs_.find(name) != cr_confs_.end()) { conf = cr_confs_[name]; cr->set_priority(conf.priority()); if (conf.has_processor_index()) { auto proc_id = conf.processor_index(); cr->set_processor_id(proc_id); } } WriteLockGuard<AtomicRWLock> rg(rw_lock_); if (!proc_ctxs_[0]->DispatchTask(cr)) { return false; } if (visitor != nullptr) { visitor->RegisterNotifyCallback([this, task_id, name]() { if (stop_) { return; } this->NotifyProcessor(task_id); }); } return true; } bool Scheduler::NotifyTask(uint64_t task_id) { if (stop_) { return true; } return NotifyProcessor(task_id); } bool Scheduler::NotifyProcessor(uint64_t cr_id) { if (stop_) { return true; } ReadLockGuard<AtomicRWLock> rg(rw_lock_); auto itr = cr_ctx_.find(cr_id); if (itr != cr_ctx_.end()) { proc_ctxs_[itr->second]->Notify(cr_id); return true; } return false; } bool Scheduler::RemoveTask(const std::string& name) { if (stop_) { return true; } auto task_id = GlobalData::RegisterTaskName(name); { WriteLockGuard<AtomicRWLock> wg(rw_lock_); cr_ctx_.erase(task_id); } return RemoveCRoutine(task_id); } bool Scheduler::RemoveCRoutine(uint64_t cr_id) { if (stop_) { return true; } WriteLockGuard<AtomicRWLock> rw(rw_lock_); auto p = cr_ctx_.find(cr_id); if (p != cr_ctx_.end()) { cr_ctx_.erase(cr_id); proc_ctxs_[p->second]->RemoveCRoutine(cr_id); } return true; } } // namespace scheduler } // namespace cyber } // namespace apollo <|endoftext|>
<commit_before>/* * * Copyright 2015, 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 <memory> #include "server.h" #include <node.h> #include <nan.h> #include <vector> #include "grpc/grpc.h" #include "grpc/grpc_security.h" #include "grpc/support/log.h" #include "call.h" #include "completion_queue_async_worker.h" #include "server_credentials.h" #include "timeval.h" namespace grpc { namespace node { using std::unique_ptr; using v8::Array; using v8::Boolean; using v8::Date; using v8::Exception; using v8::Function; using v8::FunctionTemplate; using v8::Handle; using v8::HandleScope; using v8::Local; using v8::Number; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; NanCallback *Server::constructor; Persistent<FunctionTemplate> Server::fun_tpl; class NewCallOp : public Op { public: NewCallOp() { call = NULL; grpc_call_details_init(&details); grpc_metadata_array_init(&request_metadata); } ~NewCallOp() { grpc_call_details_destroy(&details); grpc_metadata_array_destroy(&request_metadata); } Handle<Value> GetNodeValue() const { NanEscapableScope(); if (call == NULL) { return NanEscapeScope(NanNull()); } Handle<Object> obj = NanNew<Object>(); obj->Set(NanNew("call"), Call::WrapStruct(call)); obj->Set(NanNew("method"), NanNew(details.method)); obj->Set(NanNew("host"), NanNew(details.host)); obj->Set(NanNew("deadline"), NanNew<Date>(TimespecToMilliseconds(details.deadline))); obj->Set(NanNew("metadata"), ParseMetadata(&request_metadata)); return NanEscapeScope(obj); } bool ParseOp(Handle<Value> value, grpc_op *out, shared_ptr<Resources> resources) { return true; } grpc_call *call; grpc_call_details details; grpc_metadata_array request_metadata; protected: std::string GetTypeString() const { return "new call"; } }; Server::Server(grpc_server *server) : wrapped_server(server) {} Server::~Server() { grpc_server_destroy(wrapped_server); } void Server::Init(Handle<Object> exports) { NanScope(); Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New); tpl->SetClassName(NanNew("Server")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NanSetPrototypeTemplate(tpl, "requestCall", NanNew<FunctionTemplate>(RequestCall)->GetFunction()); NanSetPrototypeTemplate( tpl, "addHttp2Port", NanNew<FunctionTemplate>(AddHttp2Port)->GetFunction()); NanSetPrototypeTemplate( tpl, "addSecureHttp2Port", NanNew<FunctionTemplate>(AddSecureHttp2Port)->GetFunction()); NanSetPrototypeTemplate(tpl, "start", NanNew<FunctionTemplate>(Start)->GetFunction()); NanSetPrototypeTemplate(tpl, "shutdown", NanNew<FunctionTemplate>(Shutdown)->GetFunction()); NanAssignPersistent(fun_tpl, tpl); Handle<Function> ctr = tpl->GetFunction(); constructor = new NanCallback(ctr); exports->Set(NanNew("Server"), ctr); } bool Server::HasInstance(Handle<Value> val) { return NanHasInstance(fun_tpl, val); } NAN_METHOD(Server::New) { NanScope(); /* If this is not a constructor call, make a constructor call and return the result */ if (!args.IsConstructCall()) { const int argc = 1; Local<Value> argv[argc] = {args[0]}; NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv)); } grpc_server *wrapped_server; grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue(); if (args[0]->IsUndefined()) { wrapped_server = grpc_server_create(queue, NULL); } else if (args[0]->IsObject()) { Handle<Object> args_hash(args[0]->ToObject()); Handle<Array> keys(args_hash->GetOwnPropertyNames()); grpc_channel_args channel_args; channel_args.num_args = keys->Length(); channel_args.args = reinterpret_cast<grpc_arg *>( calloc(channel_args.num_args, sizeof(grpc_arg))); /* These are used to keep all strings until then end of the block, then destroy them */ std::vector<NanUtf8String *> key_strings(keys->Length()); std::vector<NanUtf8String *> value_strings(keys->Length()); for (unsigned int i = 0; i < channel_args.num_args; i++) { Handle<String> current_key(keys->Get(i)->ToString()); Handle<Value> current_value(args_hash->Get(current_key)); key_strings[i] = new NanUtf8String(current_key); channel_args.args[i].key = **key_strings[i]; if (current_value->IsInt32()) { channel_args.args[i].type = GRPC_ARG_INTEGER; channel_args.args[i].value.integer = current_value->Int32Value(); } else if (current_value->IsString()) { channel_args.args[i].type = GRPC_ARG_STRING; value_strings[i] = new NanUtf8String(current_value); channel_args.args[i].value.string = **value_strings[i]; } else { free(channel_args.args); return NanThrowTypeError("Arg values must be strings"); } } wrapped_server = grpc_server_create(queue, &channel_args); free(channel_args.args); } else { return NanThrowTypeError("Server expects an object"); } Server *server = new Server(wrapped_server); server->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(Server::RequestCall) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError("requestCall can only be called on a Server"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); NewCallOp *op = new NewCallOp(); unique_ptr<OpVec> ops(new OpVec()); ops->push_back(unique_ptr<Op>(op)); grpc_call_error error = grpc_server_request_call( server->wrapped_server, &op->call, &op->details, &op->request_metadata, CompletionQueueAsyncWorker::GetQueue(), new struct tag(new NanCallback(args[0].As<Function>()), ops.release(), shared_ptr<Resources>(nullptr))); if (error != GRPC_CALL_OK) { return NanThrowError("requestCall failed", error); } CompletionQueueAsyncWorker::Next(); NanReturnUndefined(); } NAN_METHOD(Server::AddHttp2Port) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError("addHttp2Port can only be called on a Server"); } if (!args[0]->IsString()) { return NanThrowTypeError("addHttp2Port's argument must be a String"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); NanReturnValue(NanNew<Number>(grpc_server_add_http2_port( server->wrapped_server, *NanUtf8String(args[0])))); } NAN_METHOD(Server::AddSecureHttp2Port) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError( "addSecureHttp2Port can only be called on a Server"); } if (!args[0]->IsString()) { return NanThrowTypeError( "addSecureHttp2Port's first argument must be a String"); } if (!ServerCredentials::HasInstance(args[1])) { return NanThrowTypeError( "addSecureHttp2Port's second argument must be ServerCredentials"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); ServerCredentials *creds = ObjectWrap::Unwrap<ServerCredentials>( args[1]->ToObject()); NanReturnValue(NanNew<Number>(grpc_server_add_secure_http2_port( server->wrapped_server, *NanUtf8String(args[0]), creds->GetWrappedServerCredentials()))); } NAN_METHOD(Server::Start) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError("start can only be called on a Server"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); grpc_server_start(server->wrapped_server); NanReturnUndefined(); } NAN_METHOD(Server::Shutdown) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError("shutdown can only be called on a Server"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); grpc_server_shutdown(server->wrapped_server); NanReturnUndefined(); } } // namespace node } // namespace grpc <commit_msg>Port Node to new API<commit_after>/* * * Copyright 2015, 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 <memory> #include "server.h" #include <node.h> #include <nan.h> #include <vector> #include "grpc/grpc.h" #include "grpc/grpc_security.h" #include "grpc/support/log.h" #include "call.h" #include "completion_queue_async_worker.h" #include "server_credentials.h" #include "timeval.h" namespace grpc { namespace node { using std::unique_ptr; using v8::Array; using v8::Boolean; using v8::Date; using v8::Exception; using v8::Function; using v8::FunctionTemplate; using v8::Handle; using v8::HandleScope; using v8::Local; using v8::Number; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; NanCallback *Server::constructor; Persistent<FunctionTemplate> Server::fun_tpl; class NewCallOp : public Op { public: NewCallOp() { call = NULL; grpc_call_details_init(&details); grpc_metadata_array_init(&request_metadata); } ~NewCallOp() { grpc_call_details_destroy(&details); grpc_metadata_array_destroy(&request_metadata); } Handle<Value> GetNodeValue() const { NanEscapableScope(); if (call == NULL) { return NanEscapeScope(NanNull()); } Handle<Object> obj = NanNew<Object>(); obj->Set(NanNew("call"), Call::WrapStruct(call)); obj->Set(NanNew("method"), NanNew(details.method)); obj->Set(NanNew("host"), NanNew(details.host)); obj->Set(NanNew("deadline"), NanNew<Date>(TimespecToMilliseconds(details.deadline))); obj->Set(NanNew("metadata"), ParseMetadata(&request_metadata)); return NanEscapeScope(obj); } bool ParseOp(Handle<Value> value, grpc_op *out, shared_ptr<Resources> resources) { return true; } grpc_call *call; grpc_call_details details; grpc_metadata_array request_metadata; protected: std::string GetTypeString() const { return "new call"; } }; Server::Server(grpc_server *server) : wrapped_server(server) {} Server::~Server() { grpc_server_destroy(wrapped_server); } void Server::Init(Handle<Object> exports) { NanScope(); Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New); tpl->SetClassName(NanNew("Server")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NanSetPrototypeTemplate(tpl, "requestCall", NanNew<FunctionTemplate>(RequestCall)->GetFunction()); NanSetPrototypeTemplate( tpl, "addHttp2Port", NanNew<FunctionTemplate>(AddHttp2Port)->GetFunction()); NanSetPrototypeTemplate( tpl, "addSecureHttp2Port", NanNew<FunctionTemplate>(AddSecureHttp2Port)->GetFunction()); NanSetPrototypeTemplate(tpl, "start", NanNew<FunctionTemplate>(Start)->GetFunction()); NanSetPrototypeTemplate(tpl, "shutdown", NanNew<FunctionTemplate>(Shutdown)->GetFunction()); NanAssignPersistent(fun_tpl, tpl); Handle<Function> ctr = tpl->GetFunction(); constructor = new NanCallback(ctr); exports->Set(NanNew("Server"), ctr); } bool Server::HasInstance(Handle<Value> val) { return NanHasInstance(fun_tpl, val); } NAN_METHOD(Server::New) { NanScope(); /* If this is not a constructor call, make a constructor call and return the result */ if (!args.IsConstructCall()) { const int argc = 1; Local<Value> argv[argc] = {args[0]}; NanReturnValue(constructor->GetFunction()->NewInstance(argc, argv)); } grpc_server *wrapped_server; grpc_completion_queue *queue = CompletionQueueAsyncWorker::GetQueue(); if (args[0]->IsUndefined()) { wrapped_server = grpc_server_create(NULL); } else if (args[0]->IsObject()) { Handle<Object> args_hash(args[0]->ToObject()); Handle<Array> keys(args_hash->GetOwnPropertyNames()); grpc_channel_args channel_args; channel_args.num_args = keys->Length(); channel_args.args = reinterpret_cast<grpc_arg *>( calloc(channel_args.num_args, sizeof(grpc_arg))); /* These are used to keep all strings until then end of the block, then destroy them */ std::vector<NanUtf8String *> key_strings(keys->Length()); std::vector<NanUtf8String *> value_strings(keys->Length()); for (unsigned int i = 0; i < channel_args.num_args; i++) { Handle<String> current_key(keys->Get(i)->ToString()); Handle<Value> current_value(args_hash->Get(current_key)); key_strings[i] = new NanUtf8String(current_key); channel_args.args[i].key = **key_strings[i]; if (current_value->IsInt32()) { channel_args.args[i].type = GRPC_ARG_INTEGER; channel_args.args[i].value.integer = current_value->Int32Value(); } else if (current_value->IsString()) { channel_args.args[i].type = GRPC_ARG_STRING; value_strings[i] = new NanUtf8String(current_value); channel_args.args[i].value.string = **value_strings[i]; } else { free(channel_args.args); return NanThrowTypeError("Arg values must be strings"); } } wrapped_server = grpc_server_create(&channel_args); free(channel_args.args); } else { return NanThrowTypeError("Server expects an object"); } grpc_server_register_completion_queue(wrapped_server, queue); Server *server = new Server(wrapped_server); server->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(Server::RequestCall) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError("requestCall can only be called on a Server"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); NewCallOp *op = new NewCallOp(); unique_ptr<OpVec> ops(new OpVec()); ops->push_back(unique_ptr<Op>(op)); grpc_call_error error = grpc_server_request_call( server->wrapped_server, &op->call, &op->details, &op->request_metadata, CompletionQueueAsyncWorker::GetQueue(), new struct tag(new NanCallback(args[0].As<Function>()), ops.release(), shared_ptr<Resources>(nullptr))); if (error != GRPC_CALL_OK) { return NanThrowError("requestCall failed", error); } CompletionQueueAsyncWorker::Next(); NanReturnUndefined(); } NAN_METHOD(Server::AddHttp2Port) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError("addHttp2Port can only be called on a Server"); } if (!args[0]->IsString()) { return NanThrowTypeError("addHttp2Port's argument must be a String"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); NanReturnValue(NanNew<Number>(grpc_server_add_http2_port( server->wrapped_server, *NanUtf8String(args[0])))); } NAN_METHOD(Server::AddSecureHttp2Port) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError( "addSecureHttp2Port can only be called on a Server"); } if (!args[0]->IsString()) { return NanThrowTypeError( "addSecureHttp2Port's first argument must be a String"); } if (!ServerCredentials::HasInstance(args[1])) { return NanThrowTypeError( "addSecureHttp2Port's second argument must be ServerCredentials"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); ServerCredentials *creds = ObjectWrap::Unwrap<ServerCredentials>( args[1]->ToObject()); NanReturnValue(NanNew<Number>(grpc_server_add_secure_http2_port( server->wrapped_server, *NanUtf8String(args[0]), creds->GetWrappedServerCredentials()))); } NAN_METHOD(Server::Start) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError("start can only be called on a Server"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); grpc_server_start(server->wrapped_server); NanReturnUndefined(); } NAN_METHOD(Server::Shutdown) { NanScope(); if (!HasInstance(args.This())) { return NanThrowTypeError("shutdown can only be called on a Server"); } Server *server = ObjectWrap::Unwrap<Server>(args.This()); grpc_server_shutdown(server->wrapped_server); NanReturnUndefined(); } } // namespace node } // namespace grpc <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ron Dreslinski * Steve Reinhardt * Ali Saidi */ /** * @file * Declaration of a request, the overall memory request consisting of the parts of the request that are persistent throughout the transaction. */ #ifndef __MEM_REQUEST_HH__ #define __MEM_REQUEST_HH__ #include <cassert> #include "base/fast_alloc.hh" #include "base/flags.hh" #include "base/misc.hh" #include "sim/host.hh" #include "sim/core.hh" class Request; typedef Request* RequestPtr; class Request : public FastAlloc { friend class Packet; public: typedef uint32_t FlagsType; typedef ::Flags<FlagsType> Flags; /** ASI information for this request if it exists. */ static const FlagsType ASI_BITS = 0x000000FF; /** The request is a Load locked/store conditional. */ static const FlagsType LLSC = 0x00000100; /** The virtual address is also the physical address. */ static const FlagsType PHYSICAL = 0x00000200; /** The request is an ALPHA VPTE pal access (hw_ld). */ static const FlagsType VPTE = 0x00000400; /** Use the alternate mode bits in ALPHA. */ static const FlagsType ALTMODE = 0x00000800; /** The request is to an uncacheable address. */ static const FlagsType UNCACHEABLE = 0x00001000; /** The request should not cause a page fault. */ static const FlagsType NO_FAULT = 0x00002000; /** The request should not cause a memory access. */ static const FlagsType NO_ACCESS = 0x00004000; /** This request will lock or unlock the accessed memory. */ static const FlagsType LOCKED = 0x00008000; /** The request should be prefetched into the exclusive state. */ static const FlagsType PF_EXCLUSIVE = 0x00010000; /** The request should be marked as LRU. */ static const FlagsType EVICT_NEXT = 0x00020000; /** The request should ignore unaligned access faults */ static const FlagsType NO_ALIGN_FAULT = 0x00040000; /** The request was an instruction read. */ static const FlagsType INST_READ = 0x00080000; /** This request is for a memory swap. */ static const FlagsType MEM_SWAP = 0x00100000; static const FlagsType MEM_SWAP_COND = 0x00200000; /** The request should ignore unaligned access faults */ static const FlagsType NO_HALF_WORD_ALIGN_FAULT = 0x00400000; /** This request is to a memory mapped register. */ static const FlagsType MMAPED_IPR = 0x00800000; private: static const FlagsType PUBLIC_FLAGS = 0x00FFFFFF; static const FlagsType PRIVATE_FLAGS = 0xFF000000; /** Whether or not the size is valid. */ static const FlagsType VALID_SIZE = 0x01000000; /** Whether or not paddr is valid (has been written yet). */ static const FlagsType VALID_PADDR = 0x02000000; /** Whether or not the vaddr & asid are valid. */ static const FlagsType VALID_VADDR = 0x04000000; /** Whether or not the pc is valid. */ static const FlagsType VALID_PC = 0x10000000; /** Whether or not the context ID is valid. */ static const FlagsType VALID_CONTEXT_ID = 0x20000000; static const FlagsType VALID_THREAD_ID = 0x40000000; /** Whether or not the sc result is valid. */ static const FlagsType VALID_EXTRA_DATA = 0x80000000; private: /** * The physical address of the request. Valid only if validPaddr * is set. */ Addr paddr; /** * The size of the request. This field must be set when vaddr or * paddr is written via setVirt() or setPhys(), so it is always * valid as long as one of the address fields is valid. */ int size; /** Flag structure for the request. */ Flags flags; /** * The time this request was started. Used to calculate * latencies. This field is set to curTick any time paddr or vaddr * is written. */ Tick time; /** The address space ID. */ int asid; /** The virtual address of the request. */ Addr vaddr; /** * Extra data for the request, such as the return value of * store conditional or the compare value for a CAS. */ uint64_t extraData; /** The context ID (for statistics, typically). */ int _contextId; /** The thread ID (id within this CPU) */ int _threadId; /** program counter of initiating access; for tracing/debugging */ Addr pc; public: /** Minimal constructor. No fields are initialized. */ Request() {} /** * Constructor for physical (e.g. device) requests. Initializes * just physical address, size, flags, and timestamp (to curTick). * These fields are adequate to perform a request. */ Request(Addr paddr, int size, Flags flags) { setPhys(paddr, size, flags); } Request(int asid, Addr vaddr, int size, Flags flags, Addr pc, int cid, int tid) { setThreadContext(cid, tid); setVirt(asid, vaddr, size, flags, pc); } ~Request() {} // for FastAlloc /** * Set up CPU and thread numbers. */ void setThreadContext(int context_id, int thread_id) { _contextId = context_id; _threadId = thread_id; flags.set(VALID_CONTEXT_ID|VALID_THREAD_ID); } /** * Set up a physical (e.g. device) request in a previously * allocated Request object. */ void setPhys(Addr _paddr, int _size, Flags _flags) { assert(_size >= 0); paddr = _paddr; size = _size; time = curTick; flags.set(VALID_PADDR|VALID_SIZE); flags.clear(VALID_VADDR|VALID_PC|VALID_EXTRA_DATA|MMAPED_IPR); flags.update(_flags, PUBLIC_FLAGS); } /** * Set up a virtual (e.g., CPU) request in a previously * allocated Request object. */ void setVirt(int _asid, Addr _vaddr, int _size, Flags _flags, Addr _pc) { assert(_size >= 0); asid = _asid; vaddr = _vaddr; size = _size; pc = _pc; time = curTick; flags.set(VALID_VADDR|VALID_SIZE|VALID_PC); flags.clear(VALID_PADDR|VALID_EXTRA_DATA|MMAPED_IPR); flags.update(_flags, PUBLIC_FLAGS); } /** * Set just the physical address. This should only be used to * record the result of a translation, and thus the vaddr must be * valid before this method is called. Otherwise, use setPhys() * to guarantee that the size and flags are also set. */ void setPaddr(Addr _paddr) { assert(flags.isSet(VALID_VADDR)); paddr = _paddr; flags.set(VALID_PADDR); } /** * Generate two requests as if this request had been split into two * pieces. The original request can't have been translated already. */ void splitOnVaddr(Addr split_addr, RequestPtr &req1, RequestPtr &req2) { assert(flags.isSet(VALID_VADDR)); assert(flags.noneSet(VALID_PADDR)); assert(split_addr > vaddr && split_addr < vaddr + size); req1 = new Request; *req1 = *this; req2 = new Request; *req2 = *this; req1->size = split_addr - vaddr; req2->vaddr = split_addr; req2->size = size - req1->size; } /** * Accessor for paddr. */ Addr getPaddr() { assert(flags.isSet(VALID_PADDR)); return paddr; } /** * Accessor for size. */ int getSize() { assert(flags.isSet(VALID_SIZE)); return size; } /** Accessor for time. */ Tick getTime() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); return time; } void setTime(Tick when) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); time = when; } /** Accessor for flags. */ Flags getFlags() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); return flags & PUBLIC_FLAGS; } Flags anyFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); return flags.isSet(_flags); } Flags allFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); return flags.allSet(_flags); } /** Accessor for flags. */ void setFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); flags.set(_flags); } void clearFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); flags.clear(_flags); } void clearFlags() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); flags.clear(PUBLIC_FLAGS); } /** Accessor function for vaddr.*/ Addr getVaddr() { assert(flags.isSet(VALID_VADDR)); return vaddr; } /** Accessor function for asid.*/ int getAsid() { assert(flags.isSet(VALID_VADDR)); return asid; } /** Accessor function for asi.*/ uint8_t getAsi() { assert(flags.isSet(VALID_VADDR)); return flags & ASI_BITS; } /** Accessor function for asi.*/ void setAsi(uint8_t a) { assert(flags.isSet(VALID_VADDR)); flags.update(a, ASI_BITS); } /** Accessor function for asi.*/ bool isMmapedIpr() { assert(flags.isSet(VALID_PADDR)); return flags.isSet(MMAPED_IPR); } /** Accessor function for asi.*/ void setMmapedIpr(bool r) { assert(VALID_VADDR); flags.set(MMAPED_IPR); } /** Accessor function to check if sc result is valid. */ bool extraDataValid() { return flags.isSet(VALID_EXTRA_DATA); } /** Accessor function for store conditional return value.*/ uint64_t getExtraData() const { assert(flags.isSet(VALID_EXTRA_DATA)); return extraData; } /** Accessor function for store conditional return value.*/ void setExtraData(uint64_t _extraData) { extraData = _extraData; flags.set(VALID_EXTRA_DATA); } bool hasContextId() const { return flags.isSet(VALID_CONTEXT_ID); } /** Accessor function for context ID.*/ int contextId() const { assert(flags.isSet(VALID_CONTEXT_ID)); return _contextId; } /** Accessor function for thread ID. */ int threadId() const { assert(flags.isSet(VALID_THREAD_ID)); return _threadId; } bool hasPC() const { return flags.isSet(VALID_PC); } /** Accessor function for pc.*/ Addr getPC() const { assert(flags.isSet(VALID_PC)); return pc; } /** Accessor Function to Check Cacheability. */ bool isUncacheable() const { return flags.isSet(UNCACHEABLE); } bool isInstRead() const { return flags.isSet(INST_READ); } bool isLLSC() const { return flags.isSet(LLSC); } bool isLocked() const { return flags.isSet(LOCKED); } bool isSwap() const { return flags.isSet(MEM_SWAP|MEM_SWAP_COND); } bool isCondSwap() const { return flags.isSet(MEM_SWAP_COND); } bool isMisaligned() const { if (flags.isSet(NO_ALIGN_FAULT)) return false; if ((vaddr & 0x1)) return true; if (flags.isSet(NO_HALF_WORD_ALIGN_FAULT)) return false; if ((vaddr & 0x2)) return true; return false; } }; #endif // __MEM_REQUEST_HH__ <commit_msg>Mem: Fill out the comment that describes the LOCKED request flag.<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ron Dreslinski * Steve Reinhardt * Ali Saidi */ /** * @file * Declaration of a request, the overall memory request consisting of the parts of the request that are persistent throughout the transaction. */ #ifndef __MEM_REQUEST_HH__ #define __MEM_REQUEST_HH__ #include <cassert> #include "base/fast_alloc.hh" #include "base/flags.hh" #include "base/misc.hh" #include "sim/host.hh" #include "sim/core.hh" class Request; typedef Request* RequestPtr; class Request : public FastAlloc { friend class Packet; public: typedef uint32_t FlagsType; typedef ::Flags<FlagsType> Flags; /** ASI information for this request if it exists. */ static const FlagsType ASI_BITS = 0x000000FF; /** The request is a Load locked/store conditional. */ static const FlagsType LLSC = 0x00000100; /** The virtual address is also the physical address. */ static const FlagsType PHYSICAL = 0x00000200; /** The request is an ALPHA VPTE pal access (hw_ld). */ static const FlagsType VPTE = 0x00000400; /** Use the alternate mode bits in ALPHA. */ static const FlagsType ALTMODE = 0x00000800; /** The request is to an uncacheable address. */ static const FlagsType UNCACHEABLE = 0x00001000; /** The request should not cause a page fault. */ static const FlagsType NO_FAULT = 0x00002000; /** The request should not cause a memory access. */ static const FlagsType NO_ACCESS = 0x00004000; /** This request will lock or unlock the accessed memory. When used with * a load, the access locks the particular chunk of memory. When used * with a store, it unlocks. The rule is that locked accesses have to be * made up of a locked load, some operation on the data, and then a locked * store. */ static const FlagsType LOCKED = 0x00008000; /** The request should be prefetched into the exclusive state. */ static const FlagsType PF_EXCLUSIVE = 0x00010000; /** The request should be marked as LRU. */ static const FlagsType EVICT_NEXT = 0x00020000; /** The request should ignore unaligned access faults */ static const FlagsType NO_ALIGN_FAULT = 0x00040000; /** The request was an instruction read. */ static const FlagsType INST_READ = 0x00080000; /** This request is for a memory swap. */ static const FlagsType MEM_SWAP = 0x00100000; static const FlagsType MEM_SWAP_COND = 0x00200000; /** The request should ignore unaligned access faults */ static const FlagsType NO_HALF_WORD_ALIGN_FAULT = 0x00400000; /** This request is to a memory mapped register. */ static const FlagsType MMAPED_IPR = 0x00800000; private: static const FlagsType PUBLIC_FLAGS = 0x00FFFFFF; static const FlagsType PRIVATE_FLAGS = 0xFF000000; /** Whether or not the size is valid. */ static const FlagsType VALID_SIZE = 0x01000000; /** Whether or not paddr is valid (has been written yet). */ static const FlagsType VALID_PADDR = 0x02000000; /** Whether or not the vaddr & asid are valid. */ static const FlagsType VALID_VADDR = 0x04000000; /** Whether or not the pc is valid. */ static const FlagsType VALID_PC = 0x10000000; /** Whether or not the context ID is valid. */ static const FlagsType VALID_CONTEXT_ID = 0x20000000; static const FlagsType VALID_THREAD_ID = 0x40000000; /** Whether or not the sc result is valid. */ static const FlagsType VALID_EXTRA_DATA = 0x80000000; private: /** * The physical address of the request. Valid only if validPaddr * is set. */ Addr paddr; /** * The size of the request. This field must be set when vaddr or * paddr is written via setVirt() or setPhys(), so it is always * valid as long as one of the address fields is valid. */ int size; /** Flag structure for the request. */ Flags flags; /** * The time this request was started. Used to calculate * latencies. This field is set to curTick any time paddr or vaddr * is written. */ Tick time; /** The address space ID. */ int asid; /** The virtual address of the request. */ Addr vaddr; /** * Extra data for the request, such as the return value of * store conditional or the compare value for a CAS. */ uint64_t extraData; /** The context ID (for statistics, typically). */ int _contextId; /** The thread ID (id within this CPU) */ int _threadId; /** program counter of initiating access; for tracing/debugging */ Addr pc; public: /** Minimal constructor. No fields are initialized. */ Request() {} /** * Constructor for physical (e.g. device) requests. Initializes * just physical address, size, flags, and timestamp (to curTick). * These fields are adequate to perform a request. */ Request(Addr paddr, int size, Flags flags) { setPhys(paddr, size, flags); } Request(int asid, Addr vaddr, int size, Flags flags, Addr pc, int cid, int tid) { setThreadContext(cid, tid); setVirt(asid, vaddr, size, flags, pc); } ~Request() {} // for FastAlloc /** * Set up CPU and thread numbers. */ void setThreadContext(int context_id, int thread_id) { _contextId = context_id; _threadId = thread_id; flags.set(VALID_CONTEXT_ID|VALID_THREAD_ID); } /** * Set up a physical (e.g. device) request in a previously * allocated Request object. */ void setPhys(Addr _paddr, int _size, Flags _flags) { assert(_size >= 0); paddr = _paddr; size = _size; time = curTick; flags.set(VALID_PADDR|VALID_SIZE); flags.clear(VALID_VADDR|VALID_PC|VALID_EXTRA_DATA|MMAPED_IPR); flags.update(_flags, PUBLIC_FLAGS); } /** * Set up a virtual (e.g., CPU) request in a previously * allocated Request object. */ void setVirt(int _asid, Addr _vaddr, int _size, Flags _flags, Addr _pc) { assert(_size >= 0); asid = _asid; vaddr = _vaddr; size = _size; pc = _pc; time = curTick; flags.set(VALID_VADDR|VALID_SIZE|VALID_PC); flags.clear(VALID_PADDR|VALID_EXTRA_DATA|MMAPED_IPR); flags.update(_flags, PUBLIC_FLAGS); } /** * Set just the physical address. This should only be used to * record the result of a translation, and thus the vaddr must be * valid before this method is called. Otherwise, use setPhys() * to guarantee that the size and flags are also set. */ void setPaddr(Addr _paddr) { assert(flags.isSet(VALID_VADDR)); paddr = _paddr; flags.set(VALID_PADDR); } /** * Generate two requests as if this request had been split into two * pieces. The original request can't have been translated already. */ void splitOnVaddr(Addr split_addr, RequestPtr &req1, RequestPtr &req2) { assert(flags.isSet(VALID_VADDR)); assert(flags.noneSet(VALID_PADDR)); assert(split_addr > vaddr && split_addr < vaddr + size); req1 = new Request; *req1 = *this; req2 = new Request; *req2 = *this; req1->size = split_addr - vaddr; req2->vaddr = split_addr; req2->size = size - req1->size; } /** * Accessor for paddr. */ Addr getPaddr() { assert(flags.isSet(VALID_PADDR)); return paddr; } /** * Accessor for size. */ int getSize() { assert(flags.isSet(VALID_SIZE)); return size; } /** Accessor for time. */ Tick getTime() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); return time; } void setTime(Tick when) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); time = when; } /** Accessor for flags. */ Flags getFlags() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); return flags & PUBLIC_FLAGS; } Flags anyFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); return flags.isSet(_flags); } Flags allFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); return flags.allSet(_flags); } /** Accessor for flags. */ void setFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); flags.set(_flags); } void clearFlags(Flags _flags) { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); assert(_flags.noneSet(~PUBLIC_FLAGS)); flags.clear(_flags); } void clearFlags() { assert(flags.isSet(VALID_PADDR|VALID_VADDR)); flags.clear(PUBLIC_FLAGS); } /** Accessor function for vaddr.*/ Addr getVaddr() { assert(flags.isSet(VALID_VADDR)); return vaddr; } /** Accessor function for asid.*/ int getAsid() { assert(flags.isSet(VALID_VADDR)); return asid; } /** Accessor function for asi.*/ uint8_t getAsi() { assert(flags.isSet(VALID_VADDR)); return flags & ASI_BITS; } /** Accessor function for asi.*/ void setAsi(uint8_t a) { assert(flags.isSet(VALID_VADDR)); flags.update(a, ASI_BITS); } /** Accessor function for asi.*/ bool isMmapedIpr() { assert(flags.isSet(VALID_PADDR)); return flags.isSet(MMAPED_IPR); } /** Accessor function for asi.*/ void setMmapedIpr(bool r) { assert(VALID_VADDR); flags.set(MMAPED_IPR); } /** Accessor function to check if sc result is valid. */ bool extraDataValid() { return flags.isSet(VALID_EXTRA_DATA); } /** Accessor function for store conditional return value.*/ uint64_t getExtraData() const { assert(flags.isSet(VALID_EXTRA_DATA)); return extraData; } /** Accessor function for store conditional return value.*/ void setExtraData(uint64_t _extraData) { extraData = _extraData; flags.set(VALID_EXTRA_DATA); } bool hasContextId() const { return flags.isSet(VALID_CONTEXT_ID); } /** Accessor function for context ID.*/ int contextId() const { assert(flags.isSet(VALID_CONTEXT_ID)); return _contextId; } /** Accessor function for thread ID. */ int threadId() const { assert(flags.isSet(VALID_THREAD_ID)); return _threadId; } bool hasPC() const { return flags.isSet(VALID_PC); } /** Accessor function for pc.*/ Addr getPC() const { assert(flags.isSet(VALID_PC)); return pc; } /** Accessor Function to Check Cacheability. */ bool isUncacheable() const { return flags.isSet(UNCACHEABLE); } bool isInstRead() const { return flags.isSet(INST_READ); } bool isLLSC() const { return flags.isSet(LLSC); } bool isLocked() const { return flags.isSet(LOCKED); } bool isSwap() const { return flags.isSet(MEM_SWAP|MEM_SWAP_COND); } bool isCondSwap() const { return flags.isSet(MEM_SWAP_COND); } bool isMisaligned() const { if (flags.isSet(NO_ALIGN_FAULT)) return false; if ((vaddr & 0x1)) return true; if (flags.isSet(NO_HALF_WORD_ALIGN_FAULT)) return false; if ((vaddr & 0x2)) return true; return false; } }; #endif // __MEM_REQUEST_HH__ <|endoftext|>
<commit_before>#include <CQTitleBar.h> #include <QPainter> #include <QStylePainter> #include <QStyleOptionToolButton> CQTitleBar:: CQTitleBar(Qt::Orientation orient, QWidget *parent) : QWidget(parent), title_(), icon_(), orient_(orient), bgColor_(160,160,160), barColor_(120,120,120), buttons_() { setObjectName("title"); } CQTitleBar:: CQTitleBar(QWidget *parent, Qt::Orientation orient) : QWidget(parent), title_(), icon_(), orient_(orient), bgColor_(160,160,160), barColor_(120,120,120), buttons_() { setObjectName("title"); } void CQTitleBar:: setTitle(const QString &title) { title_ = title; if (isVisible()) update(); } void CQTitleBar:: setIcon(const QIcon &icon) { icon_ = icon; if (isVisible()) update(); } void CQTitleBar:: setOrientation(Qt::Orientation orient) { orient_ = orient; updateLayout(); } void CQTitleBar:: setBackgroundColor(const QColor &color) { bgColor_ = color; if (isVisible()) update(); } void CQTitleBar:: setBarColor(const QColor &color) { barColor_ = color; if (isVisible()) update(); } CQTitleBarButton * CQTitleBar:: addButton(const QIcon &icon) { CQTitleBarButton *button = new CQTitleBarButton; button->setIcon(icon); addButton(button); return button; } void CQTitleBar:: addButton(CQTitleBarButton *button) { button->setParent(this); button->setTitleBar(this); buttons_.push_back(button); updateLayout(); } void CQTitleBar:: showEvent(QShowEvent *) { updateLayout(); } void CQTitleBar:: paintEvent(QPaintEvent *) { QPainter p(this); QColor bgColor = this->backgroundColor(); p.fillRect(rect(), bgColor); QColor barColor = this->barColor(); drawTitleBarLines(&p, rect(), barColor); QIcon icon = this->icon(); QString title = this->title(); int x = 0; if (orientation() == Qt::Horizontal) { if (! icon.isNull()) { int ps = height() - 4; p.fillRect(QRect(x, 0, ps + 4, height()), bgColor); p.drawPixmap(x + 2, 2, icon.pixmap(QSize(ps,ps))); x += ps + 4; } if (! title.isEmpty()) { QFontMetrics fm(font()); int tw = fm.width(title); int th = fm.boundingRect(title).height(); p.fillRect(QRect(x, 0, tw + 8, height()), bgColor); p.setPen(palette().color(QPalette::Text)); p.drawText(x + 2, (height() - th)/2 + fm.ascent(), title); } } else { int y = height() - 1; if (! icon.isNull()) { int ps = width() - 4; p.fillRect(QRect(0, y - ps - 4, width(), ps + 4), bgColor); p.save(); p.translate(0, height()); p.rotate(-90); //p.drawPixmap(2, y - ps - 2, icon.pixmap(QSize(ps,ps))); p.drawPixmap(x + 2, 2, icon.pixmap(QSize(ps,ps))); p.restore(); y -= ps + 4; x += ps + 4; } if (! title.isEmpty()) { QFontMetrics fm(font()); int tw = fm.width(title); int th = fm.boundingRect(title).height(); p.save(); p.fillRect(QRect(0, y - tw - 8, width(), tw + 8), bgColor); p.setPen(palette().color(QPalette::Text)); p.translate(0, height()); p.rotate(-90); p.drawText(x + 2, (width() - th)/2 + fm.ascent(), title); p.restore(); } } int bw = (orientation() == Qt::Horizontal ? height() - 4 : width() - 4); int nb = 0; for (uint i = 0; i < buttons_.size(); ++i) if (buttons_[i]->isVisible()) ++nb; if (orientation() == Qt::Horizontal) p.fillRect(QRect(width() - nb*bw, 0, nb*bw, height()), bgColor); else p.fillRect(QRect(0, 0, width(), nb*bw), bgColor); } void CQTitleBar:: resizeEvent(QResizeEvent *) { updateLayout(); } void CQTitleBar:: updateLayout() { if (! isVisible()) return; QFontMetrics fm(font()); if (orientation() == Qt::Horizontal) { setFixedHeight(fm.height() + 4); setMinimumWidth(0); setMaximumWidth(QWIDGETSIZE_MAX); } else { setFixedWidth(fm.height() + 4); setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX); } //------ int bw = (orientation() == Qt::Horizontal ? height() - 4 : width() - 4); int nb = buttons_.size(); int pos = (orientation() == Qt::Horizontal ? width() : 0); for (int i = nb - 1; i >= 0; --i) { CQTitleBarButton *button = buttons_[i]; if (! button->isVisible()) continue; if (orientation() == Qt::Horizontal) { int dh = height() - button->height(); button->move(pos - bw, dh/2); pos -= bw; } else { int dw = width() - button->width(); button->move(dw/2, pos); pos += bw; } } } void CQTitleBar:: drawTitleBarLines(QPainter *p, const QRect &r, const QColor &c) { p->setPen(c); if (orientation() == Qt::Horizontal) { int left = r.left () + 2; int right = r.right() - 2; int y = r.center().y() - 3; for (int i = 0; i < 4; ++i) { int y1 = y + 2*i; p->drawLine(left, y1, right, y1); } } else { int top = r.top () + 2; int bottom = r.bottom() - 2; int x = r.center().x() - 3; for (int i = 0; i < 4; ++i) { int x1 = x + 2*i; p->drawLine(x1, top, x1, bottom); } } } QSize CQTitleBar:: sizeHint() const { QFontMetrics fm(font()); int h = fm.height() + 4; int w = 0; int nb = 0; for (uint i = 0; i < buttons_.size(); ++i) if (buttons_[i]->isVisible()) ++nb; w += nb*h; if (! icon().isNull()) w += h; if (! title().isEmpty()) w += fm.width(title()); w = std::max(w, h); if (orientation() != Qt::Horizontal) std::swap(w, h); return QSize(w, h); } QSize CQTitleBar:: minimumSizeHint() const { QFontMetrics fm(font()); int w, h; if (orientation() == Qt::Horizontal) { h = fm.height() + 4; w = h; } else { w = fm.height() + 4; h = w; } return QSize(w, h); } //------ CQTitleBarButton:: CQTitleBarButton(QWidget *parent) : QToolButton(parent), bar_(0) { setObjectName("button"); setIconSize(QSize(10,10)); setAutoRaise(true); setFocusPolicy(Qt::NoFocus); setCursor(Qt::ArrowCursor); } void CQTitleBarButton:: paintEvent(QPaintEvent *) { QStylePainter p(this); QStyleOptionToolButton opt; opt.initFrom(this); opt.iconSize = iconSize(); //default value opt.icon = icon(); if (isDown()) opt.state |= QStyle::State_Sunken; else opt.state |= QStyle::State_Raised; opt.state |= QStyle::State_AutoRaise; opt.subControls = QStyle::SC_ToolButton; if (isDown()) opt.activeSubControls = QStyle::SC_ToolButton; else opt.activeSubControls = QStyle::SC_None; opt.features = QStyleOptionToolButton::None; opt.toolButtonStyle = Qt::ToolButtonIconOnly; opt.pos = pos(); opt.font = font(); initStyleOption(&opt); if (bar_ && bar_->orientation() == Qt::Vertical) { p.translate(0, height()); p.rotate(-90); } p.drawComplexControl(QStyle::CC_ToolButton, opt); } <commit_msg>new files<commit_after>#include <CQTitleBar.h> #include <QPainter> #include <QStylePainter> #include <QStyleOptionToolButton> CQTitleBar:: CQTitleBar(Qt::Orientation orient, QWidget *parent) : QWidget(parent), title_(), icon_(), orient_(orient), bgColor_(160,160,160), barColor_(120,120,120), buttons_() { setObjectName("title"); } CQTitleBar:: CQTitleBar(QWidget *parent, Qt::Orientation orient) : QWidget(parent), title_(), icon_(), orient_(orient), bgColor_(160,160,160), barColor_(120,120,120), buttons_() { setObjectName("title"); } void CQTitleBar:: setTitle(const QString &title) { title_ = title; if (isVisible()) update(); } void CQTitleBar:: setIcon(const QIcon &icon) { icon_ = icon; if (isVisible()) update(); } void CQTitleBar:: setOrientation(Qt::Orientation orient) { orient_ = orient; updateLayout(); } void CQTitleBar:: setBackgroundColor(const QColor &color) { bgColor_ = color; if (isVisible()) update(); } void CQTitleBar:: setBarColor(const QColor &color) { barColor_ = color; if (isVisible()) update(); } CQTitleBarButton * CQTitleBar:: addButton(const QIcon &icon) { CQTitleBarButton *button = new CQTitleBarButton; button->setIcon(icon); addButton(button); return button; } void CQTitleBar:: addButton(CQTitleBarButton *button) { button->setParent(this); button->setTitleBar(this); buttons_.push_back(button); updateLayout(); } void CQTitleBar:: showEvent(QShowEvent *) { updateLayout(); } void CQTitleBar:: paintEvent(QPaintEvent *) { QPainter p(this); QColor bgColor = this->backgroundColor(); p.fillRect(rect(), bgColor); QColor barColor = this->barColor(); drawTitleBarLines(&p, rect(), barColor); QIcon icon = this->icon(); QString title = this->title(); int x = 0; if (orientation() == Qt::Horizontal) { if (! icon.isNull()) { int ps = height() - 4; p.fillRect(QRect(x, 0, ps + 4, height()), bgColor); p.drawPixmap(x + 2, 2, icon.pixmap(QSize(ps,ps))); x += ps + 4; } if (! title.isEmpty()) { QFontMetrics fm(font()); int tw = fm.width(title); int th = fm.boundingRect(title).height(); p.fillRect(QRect(x, 0, tw + 8, height()), bgColor); p.setPen(palette().color(QPalette::Text)); p.drawText(x + 2, (height() - th)/2 + fm.ascent(), title); } } else { int y = height() - 1; if (! icon.isNull()) { int ps = width() - 4; p.fillRect(QRect(0, y - ps - 4, width(), ps + 4), bgColor); p.save(); p.translate(0, height()); p.rotate(-90); //p.drawPixmap(2, y - ps - 2, icon.pixmap(QSize(ps,ps))); p.drawPixmap(x + 2, 2, icon.pixmap(QSize(ps,ps))); p.restore(); y -= ps + 4; x += ps + 4; } if (! title.isEmpty()) { QFontMetrics fm(font()); int tw = fm.width(title); int th = fm.boundingRect(title).height(); p.save(); p.fillRect(QRect(0, y - tw - 8, width(), tw + 8), bgColor); p.setPen(palette().color(QPalette::Text)); p.translate(0, height()); p.rotate(-90); p.drawText(x + 2, (width() - th)/2 + fm.ascent(), title); p.restore(); } } int bw = (orientation() == Qt::Horizontal ? height() - 4 : width() - 4); int nb = 0; for (uint i = 0; i < buttons_.size(); ++i) if (buttons_[i]->isVisible()) ++nb; if (orientation() == Qt::Horizontal) p.fillRect(QRect(width() - nb*bw, 0, nb*bw, height()), bgColor); else p.fillRect(QRect(0, 0, width(), nb*bw), bgColor); } void CQTitleBar:: resizeEvent(QResizeEvent *) { updateLayout(); } void CQTitleBar:: updateLayout() { if (! isVisible()) return; QFontMetrics fm(font()); if (orientation() == Qt::Horizontal) { setFixedHeight(fm.height() + 4); setMinimumWidth(0); setMaximumWidth(QWIDGETSIZE_MAX); } else { setFixedWidth(fm.height() + 4); setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX); } //------ int bw = (orientation() == Qt::Horizontal ? height() - 4 : width() - 4); int nb = buttons_.size(); int pos = (orientation() == Qt::Horizontal ? width() - 2 : 2); for (int i = nb - 1; i >= 0; --i) { CQTitleBarButton *button = buttons_[i]; if (! button->isVisible()) continue; if (orientation() == Qt::Horizontal) { int dh = height() - button->height(); button->move(pos - bw, dh/2); pos -= bw; } else { int dw = width() - button->width(); button->move(dw/2, pos); pos += bw; } } } void CQTitleBar:: drawTitleBarLines(QPainter *p, const QRect &r, const QColor &c) { p->setPen(c); if (orientation() == Qt::Horizontal) { int left = r.left () + 2; int right = r.right() - 2; int y = r.center().y() - 3; for (int i = 0; i < 4; ++i) { int y1 = y + 2*i; p->drawLine(left, y1, right, y1); } } else { int top = r.top () + 2; int bottom = r.bottom() - 2; int x = r.center().x() - 3; for (int i = 0; i < 4; ++i) { int x1 = x + 2*i; p->drawLine(x1, top, x1, bottom); } } } QSize CQTitleBar:: sizeHint() const { QFontMetrics fm(font()); int h = fm.height() + 4; int w = 0; int nb = 0; for (uint i = 0; i < buttons_.size(); ++i) if (buttons_[i]->isVisible()) ++nb; w += nb*h; if (! icon().isNull()) w += h; if (! title().isEmpty()) w += fm.width(title()); w = std::max(w, h); if (orientation() != Qt::Horizontal) std::swap(w, h); return QSize(w, h); } QSize CQTitleBar:: minimumSizeHint() const { QFontMetrics fm(font()); int w, h; if (orientation() == Qt::Horizontal) { h = fm.height() + 4; w = h; } else { w = fm.height() + 4; h = w; } return QSize(w, h); } //------ CQTitleBarButton:: CQTitleBarButton(QWidget *parent) : QToolButton(parent), bar_(0) { setObjectName("button"); setIconSize(QSize(10,10)); setAutoRaise(true); setFocusPolicy(Qt::NoFocus); setCursor(Qt::ArrowCursor); } void CQTitleBarButton:: paintEvent(QPaintEvent *) { QStylePainter p(this); QStyleOptionToolButton opt; opt.initFrom(this); opt.iconSize = iconSize(); //default value opt.icon = icon(); if (isDown()) opt.state |= QStyle::State_Sunken; else opt.state |= QStyle::State_Raised; opt.state |= QStyle::State_AutoRaise; opt.subControls = QStyle::SC_ToolButton; if (isDown()) opt.activeSubControls = QStyle::SC_ToolButton; else opt.activeSubControls = QStyle::SC_None; opt.features = QStyleOptionToolButton::None; opt.toolButtonStyle = Qt::ToolButtonIconOnly; opt.pos = pos(); opt.font = font(); initStyleOption(&opt); if (bar_ && bar_->orientation() == Qt::Vertical) { p.translate(0, height()); p.rotate(-90); } p.drawComplexControl(QStyle::CC_ToolButton, opt); } <|endoftext|>
<commit_before>// This file is part of the "x0" project, http://xzero.io/ // (c) 2009-2014 Christian Parpart <trapni@gmail.com> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/HttpServer.h> #include <xzero/HttpRequest.h> #include <xzero/HttpWorker.h> #include <base/ServerSocket.h> #include <base/SocketSpec.h> #include <base/Logger.h> #include <base/DebugLogger.h> #include <base/Library.h> #include <base/AnsiColor.h> #include <base/strutils.h> #include <base/sysconfig.h> #include <systemd/sd-daemon.h> #include <iostream> #include <fstream> #include <cstdarg> #include <cstdlib> #if defined(HAVE_SYS_UTSNAME_H) #include <sys/utsname.h> #endif #include <sys/resource.h> #include <sys/time.h> #include <pwd.h> #include <grp.h> #include <getopt.h> #include <stdio.h> #if 0 // !defined(XZERO_NDEBUG) #define TRACE(msg...) DEBUG("HttpServer: " msg) #else #define TRACE(msg...) \ do { \ } while (0) #endif namespace xzero { /** initializes the HTTP server object. * \param io_service an Asio io_service to use or nullptr to create our own one. * \see HttpServer::run() */ HttpServer::HttpServer(struct ::ev_loop* loop, unsigned generation) : onConnectionOpen(), onPreProcess(), onPostProcess(), requestHandler(), onRequestDone(), onConnectionClose(), onConnectionStateChanged(), onWorkerSpawn(), onWorkerUnspawn(), generation_(generation), listeners_(), loop_(loop ? loop : ev_default_loop(0)), startupTime_(ev_now(loop_)), logger_(), logLevel_(Severity::warn), colored_log_(false), workerIdPool_(0), workers_(), workerMap_(), lastWorker_(0), maxConnections(512), maxKeepAlive(TimeSpan::fromSeconds(60)), maxKeepAliveRequests(100), maxReadIdle(TimeSpan::fromSeconds(60)), maxWriteIdle(TimeSpan::fromSeconds(360)), tcpCork(false), tcpNoDelay(false), lingering(TimeSpan::Zero), tag("xzero/" LIBXZERO_VERSION), advertise(true), maxRequestUriSize(4 * 1024), maxRequestHeaderSize(1 * 1024), maxRequestHeaderCount(100), maxRequestBodySize(4 * 1024 * 1024), requestHeaderBufferSize(8 * 1024), requestBodyBufferSize(8 * 1024) { DebugLogger::get().onLogWrite = [&](const char* msg, size_t n) { LogMessage lm(Severity::trace1, "%s", msg); logger_->write(lm); }; HttpRequest::initialize(); logger_.reset(new FileLogger( STDERR_FILENO, [this]() { return static_cast<time_t>(ev_now(loop_)); })); // setting a reasonable default max-connection limit. // However, this cannot be computed as we do not know what the user // actually configures, such as fastcgi requires +1 fd, local file +1 fd, // http client connection of course +1 fd, listener sockets, etc. struct rlimit rlim; if (::getrlimit(RLIMIT_NOFILE, &rlim) == 0) maxConnections = std::max(int(rlim.rlim_cur / 3) - 5, 1); // Spawn main-thread worker createWorker(); } HttpServer::~HttpServer() { TRACE("destroying"); stop(); for (auto i : listeners_) delete i; while (!workers_.empty()) destroyWorker(workers_[workers_.size() - 1]); #ifndef __APPLE__ // explicit cleanup DebugLogger::get().reset(); #endif } void HttpServer::onNewConnection(std::unique_ptr<Socket>&& cs, ServerSocket* ss) { if (cs) { selectWorker()->enqueue(std::make_pair(std::move(cs), ss)); } else { log(Severity::error, "Accepting incoming connection failed. %s", strerror(errno)); } } // {{{ worker mgnt HttpWorker* HttpServer::createWorker() { bool isMainWorker = workers_.empty(); HttpWorker* worker = new HttpWorker(*this, isMainWorker ? loop_ : nullptr, workerIdPool_++, !isMainWorker); workers_.push_back(worker); workerMap_[worker->thread_] = worker; return worker; } /** * Selects (by round-robin) the next worker. * * \return a worker * \note This method is not thread-safe, and thus, should not be invoked within *a request handler. */ HttpWorker* HttpServer::nextWorker() { // select by RR (round-robin) // this is thread-safe since only one thread is to select a new worker // (the main thread) if (++lastWorker_ == workers_.size()) lastWorker_ = 0; return workers_[lastWorker_]; } HttpWorker* HttpServer::selectWorker() { #if 1 // defined(XZERO_WORKER_RR) return nextWorker(); #else // select by lowest connection load HttpWorker* best = workers_[0]; int value = best->connectionLoad(); for (size_t i = 1, e = workers_.size(); i != e; ++i) { HttpWorker* w = workers_[i]; int l = w->connectionLoad(); if (l < value) { value = l; best = w; } } return best; #endif } /** * @brief retrieves a pointer to the current's thread HTTP worker or \c nullptr * if none available. */ HttpWorker* HttpServer::currentWorker() const { auto i = workerMap_.find(pthread_self()); if (i != workerMap_.end()) return i->second; return nullptr; } void HttpServer::destroyWorker(HttpWorker* worker) { auto i = std::find(workers_.begin(), workers_.end(), worker); assert(i != workers_.end()); worker->stop(); if (worker != workers_.front()) worker->join(); workerMap_.erase(workerMap_.find(worker->thread_)); workers_.erase(i); delete worker; } // }}} /** calls run on the internally referenced io_service. * \note use this if you do not have your own main loop. * \note automatically starts the server if it wasn't started via \p start() * yet. * \see start(), stop() */ int HttpServer::run() { workers_.front()->run(); return 0; } /** unregisters all listeners from the underlying io_service and calls stop on * it. * \see start(), run() */ void HttpServer::stop() { for (auto listener : listeners_) listener->stop(); for (auto worker : workers_) worker->stop(); } void HttpServer::kill() { stop(); for (auto worker : workers_) worker->kill(); } void HttpServer::log(LogMessage&& msg) { if (logger_) { #if !defined(XZERO_NDEBUG) #ifndef __APPLE__ if (msg.isDebug() && msg.hasTags() && DebugLogger::get().isConfigured()) { int level = 3 - msg.severity(); // compute proper debug level Buffer text; text << msg; BufferRef tag = msg.tagAt(msg.tagCount() - 1); size_t i = tag.find('/'); if (i != tag.npos) tag = tag.ref(0, i); DebugLogger::get().logUntagged(tag.str(), level, "%s", text.c_str()); return; } #endif #endif logger_->write(msg); } } /** * sets up a TCP/IP ServerSocket on given bind_address and port. * * If there is already a ServerSocket on this bind_address:port pair * then no error will be raised. */ ServerSocket* HttpServer::setupListener(const std::string& bind_address, int port, int backlog) { return setupListener( SocketSpec::fromInet(IPAddress(bind_address), port, backlog)); } ServerSocket* HttpServer::setupUnixListener(const std::string& path, int backlog) { return setupListener(SocketSpec::fromLocal(path, backlog)); } ServerSocket* HttpServer::setupListener(const SocketSpec& _spec) { // validate backlog against system's hard limit SocketSpec spec(_spec); int somaxconn = SOMAXCONN; #if defined(__linux__) somaxconn = readFile("/proc/sys/net/core/somaxconn").toInt(); if (spec.backlog() > 0) { if (somaxconn && spec.backlog() > somaxconn) { log(Severity::error, "Listener %s configured with a backlog higher than the system " "permits (%ld > %ld). " "See /proc/sys/net/core/somaxconn for your system limits.", spec.str().c_str(), spec.backlog(), somaxconn); return nullptr; } } #endif // create a new listener ServerSocket* lp = new ServerSocket(loop_); lp->set<HttpServer, &HttpServer::onNewConnection>(this); listeners_.push_back(lp); if (spec.backlog() <= 0) lp->setBacklog(somaxconn); if (spec.multiAcceptCount() > 0) lp->setMultiAcceptCount(spec.multiAcceptCount()); if (lp->open(spec, O_NONBLOCK | O_CLOEXEC)) { log(Severity::info, "Listening on %s", spec.str().c_str()); return lp; } else { log(Severity::error, "Could not create listener %s: %s", spec.str().c_str(), lp->errorText().c_str()); return nullptr; } } void HttpServer::destroyListener(ServerSocket* listener) { for (auto i = listeners_.begin(), e = listeners_.end(); i != e; ++i) { if (*i == listener) { listeners_.erase(i); delete listener; break; } } } void HttpServer::setLogLevel(Severity s) { logLevel_ = s; logger()->setLevel(s); log(s > Severity::info ? s : Severity::info, "Logging level set to: %s", s.c_str()); } } // namespace xzero <commit_msg>libxzero: dead header cleanup<commit_after>// This file is part of the "x0" project, http://xzero.io/ // (c) 2009-2014 Christian Parpart <trapni@gmail.com> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/HttpServer.h> #include <xzero/HttpRequest.h> #include <xzero/HttpWorker.h> #include <base/ServerSocket.h> #include <base/SocketSpec.h> #include <base/Logger.h> #include <base/DebugLogger.h> #include <base/Library.h> #include <base/AnsiColor.h> #include <base/strutils.h> #include <base/sysconfig.h> #include <iostream> #include <fstream> #include <cstdarg> #include <cstdlib> #if defined(HAVE_SYS_UTSNAME_H) #include <sys/utsname.h> #endif #include <sys/resource.h> #include <sys/time.h> #include <pwd.h> #include <grp.h> #include <getopt.h> #include <stdio.h> #if 0 // !defined(XZERO_NDEBUG) #define TRACE(msg...) DEBUG("HttpServer: " msg) #else #define TRACE(msg...) \ do { \ } while (0) #endif namespace xzero { /** initializes the HTTP server object. * \param io_service an Asio io_service to use or nullptr to create our own one. * \see HttpServer::run() */ HttpServer::HttpServer(struct ::ev_loop* loop, unsigned generation) : onConnectionOpen(), onPreProcess(), onPostProcess(), requestHandler(), onRequestDone(), onConnectionClose(), onConnectionStateChanged(), onWorkerSpawn(), onWorkerUnspawn(), generation_(generation), listeners_(), loop_(loop ? loop : ev_default_loop(0)), startupTime_(ev_now(loop_)), logger_(), logLevel_(Severity::warn), colored_log_(false), workerIdPool_(0), workers_(), workerMap_(), lastWorker_(0), maxConnections(512), maxKeepAlive(TimeSpan::fromSeconds(60)), maxKeepAliveRequests(100), maxReadIdle(TimeSpan::fromSeconds(60)), maxWriteIdle(TimeSpan::fromSeconds(360)), tcpCork(false), tcpNoDelay(false), lingering(TimeSpan::Zero), tag("xzero/" LIBXZERO_VERSION), advertise(true), maxRequestUriSize(4 * 1024), maxRequestHeaderSize(1 * 1024), maxRequestHeaderCount(100), maxRequestBodySize(4 * 1024 * 1024), requestHeaderBufferSize(8 * 1024), requestBodyBufferSize(8 * 1024) { DebugLogger::get().onLogWrite = [&](const char* msg, size_t n) { LogMessage lm(Severity::trace1, "%s", msg); logger_->write(lm); }; HttpRequest::initialize(); logger_.reset(new FileLogger( STDERR_FILENO, [this]() { return static_cast<time_t>(ev_now(loop_)); })); // setting a reasonable default max-connection limit. // However, this cannot be computed as we do not know what the user // actually configures, such as fastcgi requires +1 fd, local file +1 fd, // http client connection of course +1 fd, listener sockets, etc. struct rlimit rlim; if (::getrlimit(RLIMIT_NOFILE, &rlim) == 0) maxConnections = std::max(int(rlim.rlim_cur / 3) - 5, 1); // Spawn main-thread worker createWorker(); } HttpServer::~HttpServer() { TRACE("destroying"); stop(); for (auto i : listeners_) delete i; while (!workers_.empty()) destroyWorker(workers_[workers_.size() - 1]); #ifndef __APPLE__ // explicit cleanup DebugLogger::get().reset(); #endif } void HttpServer::onNewConnection(std::unique_ptr<Socket>&& cs, ServerSocket* ss) { if (cs) { selectWorker()->enqueue(std::make_pair(std::move(cs), ss)); } else { log(Severity::error, "Accepting incoming connection failed. %s", strerror(errno)); } } // {{{ worker mgnt HttpWorker* HttpServer::createWorker() { bool isMainWorker = workers_.empty(); HttpWorker* worker = new HttpWorker(*this, isMainWorker ? loop_ : nullptr, workerIdPool_++, !isMainWorker); workers_.push_back(worker); workerMap_[worker->thread_] = worker; return worker; } /** * Selects (by round-robin) the next worker. * * \return a worker * \note This method is not thread-safe, and thus, should not be invoked within *a request handler. */ HttpWorker* HttpServer::nextWorker() { // select by RR (round-robin) // this is thread-safe since only one thread is to select a new worker // (the main thread) if (++lastWorker_ == workers_.size()) lastWorker_ = 0; return workers_[lastWorker_]; } HttpWorker* HttpServer::selectWorker() { #if 1 // defined(XZERO_WORKER_RR) return nextWorker(); #else // select by lowest connection load HttpWorker* best = workers_[0]; int value = best->connectionLoad(); for (size_t i = 1, e = workers_.size(); i != e; ++i) { HttpWorker* w = workers_[i]; int l = w->connectionLoad(); if (l < value) { value = l; best = w; } } return best; #endif } /** * @brief retrieves a pointer to the current's thread HTTP worker or \c nullptr * if none available. */ HttpWorker* HttpServer::currentWorker() const { auto i = workerMap_.find(pthread_self()); if (i != workerMap_.end()) return i->second; return nullptr; } void HttpServer::destroyWorker(HttpWorker* worker) { auto i = std::find(workers_.begin(), workers_.end(), worker); assert(i != workers_.end()); worker->stop(); if (worker != workers_.front()) worker->join(); workerMap_.erase(workerMap_.find(worker->thread_)); workers_.erase(i); delete worker; } // }}} /** calls run on the internally referenced io_service. * \note use this if you do not have your own main loop. * \note automatically starts the server if it wasn't started via \p start() * yet. * \see start(), stop() */ int HttpServer::run() { workers_.front()->run(); return 0; } /** unregisters all listeners from the underlying io_service and calls stop on * it. * \see start(), run() */ void HttpServer::stop() { for (auto listener : listeners_) listener->stop(); for (auto worker : workers_) worker->stop(); } void HttpServer::kill() { stop(); for (auto worker : workers_) worker->kill(); } void HttpServer::log(LogMessage&& msg) { if (logger_) { #if !defined(XZERO_NDEBUG) #ifndef __APPLE__ if (msg.isDebug() && msg.hasTags() && DebugLogger::get().isConfigured()) { int level = 3 - msg.severity(); // compute proper debug level Buffer text; text << msg; BufferRef tag = msg.tagAt(msg.tagCount() - 1); size_t i = tag.find('/'); if (i != tag.npos) tag = tag.ref(0, i); DebugLogger::get().logUntagged(tag.str(), level, "%s", text.c_str()); return; } #endif #endif logger_->write(msg); } } /** * sets up a TCP/IP ServerSocket on given bind_address and port. * * If there is already a ServerSocket on this bind_address:port pair * then no error will be raised. */ ServerSocket* HttpServer::setupListener(const std::string& bind_address, int port, int backlog) { return setupListener( SocketSpec::fromInet(IPAddress(bind_address), port, backlog)); } ServerSocket* HttpServer::setupUnixListener(const std::string& path, int backlog) { return setupListener(SocketSpec::fromLocal(path, backlog)); } ServerSocket* HttpServer::setupListener(const SocketSpec& _spec) { // validate backlog against system's hard limit SocketSpec spec(_spec); int somaxconn = SOMAXCONN; #if defined(__linux__) somaxconn = readFile("/proc/sys/net/core/somaxconn").toInt(); if (spec.backlog() > 0) { if (somaxconn && spec.backlog() > somaxconn) { log(Severity::error, "Listener %s configured with a backlog higher than the system " "permits (%ld > %ld). " "See /proc/sys/net/core/somaxconn for your system limits.", spec.str().c_str(), spec.backlog(), somaxconn); return nullptr; } } #endif // create a new listener ServerSocket* lp = new ServerSocket(loop_); lp->set<HttpServer, &HttpServer::onNewConnection>(this); listeners_.push_back(lp); if (spec.backlog() <= 0) lp->setBacklog(somaxconn); if (spec.multiAcceptCount() > 0) lp->setMultiAcceptCount(spec.multiAcceptCount()); if (lp->open(spec, O_NONBLOCK | O_CLOEXEC)) { log(Severity::info, "Listening on %s", spec.str().c_str()); return lp; } else { log(Severity::error, "Could not create listener %s: %s", spec.str().c_str(), lp->errorText().c_str()); return nullptr; } } void HttpServer::destroyListener(ServerSocket* listener) { for (auto i = listeners_.begin(), e = listeners_.end(); i != e; ++i) { if (*i == listener) { listeners_.erase(i); delete listener; break; } } } void HttpServer::setLogLevel(Severity s) { logLevel_ = s; logger()->setLevel(s); log(s > Severity::info ? s : Severity::info, "Logging level set to: %s", s.c_str()); } } // namespace xzero <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "IndexWriter.h" #include <fnord-fts/AnalyzerAdapter.h> using namespace fnord; namespace cm { RefPtr<IndexWriter> IndexWriter::openIndex( const String& index_path, const String& conf_path) { if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) { RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path); } /* set up feature schema */ FeatureSchema feature_schema; feature_schema.registerFeature("shop_id", 1, 1); feature_schema.registerFeature("category1", 2, 1); feature_schema.registerFeature("category2", 3, 1); feature_schema.registerFeature("category3", 4, 1); feature_schema.registerFeature("price_cents", 8, 1); feature_schema.registerFeature("title~de", 5, 2); feature_schema.registerFeature("description~de", 6, 2); feature_schema.registerFeature("size_description~de", 14, 2); feature_schema.registerFeature("material_description~de", 15, 2); feature_schema.registerFeature("basic_attributes~de", 16, 2); feature_schema.registerFeature("tags_as_text~de", 7, 2); feature_schema.registerFeature("title~pl", 18, 2); feature_schema.registerFeature("description~pl", 19, 2); feature_schema.registerFeature("size_description~pl", 20, 2); feature_schema.registerFeature("material_description~pl", 21, 2); feature_schema.registerFeature("basic_attributes~pl", 22, 2); feature_schema.registerFeature("tags_as_text~pl", 23, 2); feature_schema.registerFeature("image_filename", 24, 2); feature_schema.registerFeature("cm_clicked_terms", 31, 2); feature_schema.registerFeature("shop_name", 26, 3); feature_schema.registerFeature("shop_platform", 27, 3); feature_schema.registerFeature("shop_country", 28, 3); feature_schema.registerFeature("shop_rating_alt", 9, 3); feature_schema.registerFeature("shop_rating_alt2", 15, 3); feature_schema.registerFeature("shop_products_count", 10, 3); feature_schema.registerFeature("shop_orders_count", 11, 3); feature_schema.registerFeature("shop_rating_count", 12, 3); feature_schema.registerFeature("shop_rating_avg", 13, 3); feature_schema.registerFeature("cm_views", 29, 3); feature_schema.registerFeature("cm_clicks", 30, 3); feature_schema.registerFeature("cm_ctr", 32, 3); feature_schema.registerFeature("cm_ctr_norm", 33, 3); feature_schema.registerFeature("cm_ctr_std", 34, 3); feature_schema.registerFeature("cm_ctr_norm_std", 35, 3); /* open mdb */ auto db_path = FileUtil::joinPaths(index_path, "db"); FileUtil::mkdir_p(db_path); auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB /* open lucene */ RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path)); auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer); auto fts_path = FileUtil::joinPaths(index_path, "fts"); bool create = false; if (!FileUtil::exists(fts_path)) { FileUtil::mkdir_p(fts_path); create = true; } auto fts = fts::newLucene<fts::IndexWriter>( fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)), adapter, create, fts::IndexWriter::MaxFieldLengthLIMITED); return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts)); } IndexWriter::IndexWriter( FeatureSchema schema, RefPtr<mdb::MDB> db, std::shared_ptr<fts::IndexWriter> fts) : schema_(schema), db_(db), db_txn_(db_->startTransaction()), feature_idx_(new FeatureIndexWriter(&schema_)), fts_(fts) {} IndexWriter::~IndexWriter() { if (db_txn_.get()) { db_txn_->commit(); } fts_->close(); } void IndexWriter::updateDocument(const IndexRequest& index_request) { stat_documents_indexed_total_.incr(1); auto docid = index_request.item.docID(); feature_idx_->updateDocument(index_request, db_txn_.get()); auto doc = feature_idx_->findDocument(docid, db_txn_.get()); rebuildFTS(doc); stat_documents_indexed_success_.incr(1); } void IndexWriter::commit() { db_txn_->commit(); db_txn_ = db_->startTransaction(); fts_->commit(); } void IndexWriter::rebuildFTS(DocID docid) { auto doc = feature_idx_->findDocument(docid, db_txn_.get()); rebuildFTS(doc); } void IndexWriter::rebuildFTS(RefPtr<Document> doc) { stat_documents_indexed_fts_.incr(1); auto fts_doc = fts::newLucene<fts::Document>(); fts_doc->add( fts::newLucene<fts::Field>( L"_docid", StringUtil::convertUTF8To16(doc->docID().docid), fts::Field::STORE_YES, fts::Field::INDEX_NOT_ANALYZED_NO_NORMS)); double boost = 1.0; double cm_clicks = 0; double cm_views = 0; double cm_ctr_norm_std = 1.0; bool is_active = false; HashMap<String, String> fts_fields_anal; for (const auto& f : doc->fields()) { /* title~LANG */ if (StringUtil::beginsWith(f.first, "title~")) { is_active = true; auto k = f.first; StringUtil::replaceAll(&k, "title~","title~"); fts_fields_anal[k] += " " + f.second; } /* description~LANG */ else if (StringUtil::beginsWith(f.first, "description~")) { auto k = f.first; StringUtil::replaceAll(&k, "description~","text~"); fts_fields_anal[k] += " " + f.second; } /* size_description~LANG */ else if (StringUtil::beginsWith(f.first, "size_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "size_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* material_description~LANG */ else if (StringUtil::beginsWith(f.first, "material_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "material_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* manufacturing_description~LANG */ else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "manufacturing_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* tags_as_text~LANG */ else if (StringUtil::beginsWith(f.first, "tags_as_text~")) { fts_fields_anal["tags"] += " " + f.second; } /* shop_name */ else if (f.first == "shop_name") { fts_fields_anal["tags"] += " " + f.second; } /* cm_clicked_terms */ else if (f.first == "cm_clicked_terms") { fts_doc->add( fts::newLucene<fts::Field>( L"cm_clicked_terms", StringUtil::convertUTF8To16(f.second), fts::Field::STORE_NO, fts::Field::INDEX_ANALYZED)); } else if (f.first == "cm_ctr_norm_std") { cm_ctr_norm_std = std::stod(f.second); } else if (f.first == "cm_clicks") { cm_clicks = std::stod(f.second); } else if (f.first == "cm_views") { cm_views = std::stod(f.second); } } for (const auto& f : fts_fields_anal) { fts_doc->add( fts::newLucene<fts::Field>( StringUtil::convertUTF8To16(f.first), StringUtil::convertUTF8To16(f.second), fts::Field::STORE_NO, fts::Field::INDEX_ANALYZED)); } if (cm_views > 1000 && cm_clicks > 15) { boost = cm_ctr_norm_std; } fts_doc->setBoost(boost); fnord::logDebug( "cm.indexwriter", "Rebuilding FTS Index for docid=$0 boost=$1", doc->docID().docid, boost); auto del_term = fts::newLucene<fts::Term>( L"_docid", StringUtil::convertUTF8To16(doc->docID().docid)); if (is_active) { fts_->updateDocument(del_term, fts_doc); } else { fts_->deleteDocuments(del_term); } } void IndexWriter::rebuildFTS() { feature_idx_->listDocuments([this] (const DocID& docid) -> bool { rebuildFTS(docid); return true; }, db_txn_.get()); } RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() { return db_txn_; } void IndexWriter::exportStats(const String& prefix) { exportStat( StringUtil::format("$0/documents_indexed_total", prefix), &stat_documents_indexed_total_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_success", prefix), &stat_documents_indexed_success_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_error", prefix), &stat_documents_indexed_error_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_fts", prefix), &stat_documents_indexed_fts_, fnord::stats::ExportMode::EXPORT_DELTA); } } // namespace cm <commit_msg>debug...<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "IndexWriter.h" #include <fnord-fts/AnalyzerAdapter.h> using namespace fnord; namespace cm { RefPtr<IndexWriter> IndexWriter::openIndex( const String& index_path, const String& conf_path) { if (!FileUtil::exists(index_path) || !FileUtil::isDirectory(index_path)) { RAISEF(kIllegalArgumentError, "invalid index path: $0", index_path); } /* set up feature schema */ FeatureSchema feature_schema; feature_schema.registerFeature("shop_id", 1, 1); feature_schema.registerFeature("category1", 2, 1); feature_schema.registerFeature("category2", 3, 1); feature_schema.registerFeature("category3", 4, 1); feature_schema.registerFeature("price_cents", 8, 1); feature_schema.registerFeature("title~de", 5, 2); feature_schema.registerFeature("description~de", 6, 2); feature_schema.registerFeature("size_description~de", 14, 2); feature_schema.registerFeature("material_description~de", 15, 2); feature_schema.registerFeature("basic_attributes~de", 16, 2); feature_schema.registerFeature("tags_as_text~de", 7, 2); feature_schema.registerFeature("title~pl", 18, 2); feature_schema.registerFeature("description~pl", 19, 2); feature_schema.registerFeature("size_description~pl", 20, 2); feature_schema.registerFeature("material_description~pl", 21, 2); feature_schema.registerFeature("basic_attributes~pl", 22, 2); feature_schema.registerFeature("tags_as_text~pl", 23, 2); feature_schema.registerFeature("image_filename", 24, 2); feature_schema.registerFeature("cm_clicked_terms", 31, 2); feature_schema.registerFeature("shop_name", 26, 3); feature_schema.registerFeature("shop_platform", 27, 3); feature_schema.registerFeature("shop_country", 28, 3); feature_schema.registerFeature("shop_rating_alt", 9, 3); feature_schema.registerFeature("shop_rating_alt2", 15, 3); feature_schema.registerFeature("shop_products_count", 10, 3); feature_schema.registerFeature("shop_orders_count", 11, 3); feature_schema.registerFeature("shop_rating_count", 12, 3); feature_schema.registerFeature("shop_rating_avg", 13, 3); feature_schema.registerFeature("cm_views", 29, 3); feature_schema.registerFeature("cm_clicks", 30, 3); feature_schema.registerFeature("cm_ctr", 32, 3); feature_schema.registerFeature("cm_ctr_norm", 33, 3); feature_schema.registerFeature("cm_ctr_std", 34, 3); feature_schema.registerFeature("cm_ctr_norm_std", 35, 3); /* open mdb */ auto db_path = FileUtil::joinPaths(index_path, "db"); FileUtil::mkdir_p(db_path); auto db = mdb::MDB::open(db_path, false, 68719476736lu); // 64 GiB /* open lucene */ RefPtr<fnord::fts::Analyzer> analyzer(new fnord::fts::Analyzer(conf_path)); auto adapter = std::make_shared<fnord::fts::AnalyzerAdapter>(analyzer); auto fts_path = FileUtil::joinPaths(index_path, "fts"); bool create = false; if (!FileUtil::exists(fts_path)) { FileUtil::mkdir_p(fts_path); create = true; } auto fts = fts::newLucene<fts::IndexWriter>( fts::FSDirectory::open(StringUtil::convertUTF8To16(fts_path)), adapter, create, fts::IndexWriter::MaxFieldLengthLIMITED); return RefPtr<IndexWriter>(new IndexWriter(feature_schema, db, fts)); } IndexWriter::IndexWriter( FeatureSchema schema, RefPtr<mdb::MDB> db, std::shared_ptr<fts::IndexWriter> fts) : schema_(schema), db_(db), db_txn_(db_->startTransaction()), feature_idx_(new FeatureIndexWriter(&schema_)), fts_(fts) {} IndexWriter::~IndexWriter() { if (db_txn_.get()) { db_txn_->commit(); } fts_->close(); } void IndexWriter::updateDocument(const IndexRequest& index_request) { stat_documents_indexed_total_.incr(1); auto docid = index_request.item.docID(); feature_idx_->updateDocument(index_request, db_txn_.get()); auto doc = feature_idx_->findDocument(docid, db_txn_.get()); rebuildFTS(doc); stat_documents_indexed_success_.incr(1); } void IndexWriter::commit() { db_txn_->commit(); db_txn_ = db_->startTransaction(); fts_->commit(); } void IndexWriter::rebuildFTS(DocID docid) { auto doc = feature_idx_->findDocument(docid, db_txn_.get()); rebuildFTS(doc); } void IndexWriter::rebuildFTS(RefPtr<Document> doc) { stat_documents_indexed_fts_.incr(1); auto fts_doc = fts::newLucene<fts::Document>(); fts_doc->add( fts::newLucene<fts::Field>( L"_docid", StringUtil::convertUTF8To16(doc->docID().docid), fts::Field::STORE_YES, fts::Field::INDEX_NOT_ANALYZED_NO_NORMS)); double boost = 1.0; double cm_clicks = 0; double cm_views = 0; double cm_ctr_norm_std = 1.0; bool is_active = false; HashMap<String, String> fts_fields_anal; for (const auto& f : doc->fields()) { /* title~LANG */ if (StringUtil::beginsWith(f.first, "title~")) { is_active = true; auto k = f.first; StringUtil::replaceAll(&k, "title~","title~"); fts_fields_anal[k] += " " + f.second; } /* description~LANG */ else if (StringUtil::beginsWith(f.first, "description~")) { auto k = f.first; StringUtil::replaceAll(&k, "description~","text~"); fts_fields_anal[k] += " " + f.second; } /* size_description~LANG */ else if (StringUtil::beginsWith(f.first, "size_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "size_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* material_description~LANG */ else if (StringUtil::beginsWith(f.first, "material_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "material_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* manufacturing_description~LANG */ else if (StringUtil::beginsWith(f.first, "manufacturing_description~")) { auto k = f.first; StringUtil::replaceAll(&k, "manufacturing_description~","text~"); fts_fields_anal[k] += " " + f.second; } /* tags_as_text~LANG */ else if (StringUtil::beginsWith(f.first, "tags_as_text~")) { fts_fields_anal["tags"] += " " + f.second; } /* shop_name */ else if (f.first == "shop_name") { fts_fields_anal["tags"] += " " + f.second; } /* cm_clicked_terms */ else if (f.first == "cm_clicked_terms") { fts_doc->add( fts::newLucene<fts::Field>( L"cm_clicked_terms", StringUtil::convertUTF8To16(f.second), fts::Field::STORE_NO, fts::Field::INDEX_ANALYZED)); } else if (f.first == "cm_ctr_norm_std") { cm_ctr_norm_std = std::stod(f.second); } else if (f.first == "cm_clicks") { cm_clicks = std::stod(f.second); } else if (f.first == "cm_views") { cm_views = std::stod(f.second); } } for (const auto& f : fts_fields_anal) { fts_doc->add( fts::newLucene<fts::Field>( StringUtil::convertUTF8To16(f.first), StringUtil::convertUTF8To16(f.second), fts::Field::STORE_NO, fts::Field::INDEX_ANALYZED)); } if (cm_views > 1000 && cm_clicks > 15) { boost = cm_ctr_norm_std; } fts_doc->setBoost(boost); fnord::logDebug( "cm.indexwriter", "Rebuilding FTS Index for docid=$0 boost=$1 active=$2", doc->docID().docid, boost, is_active); auto del_term = fts::newLucene<fts::Term>( L"_docid", StringUtil::convertUTF8To16(doc->docID().docid)); if (is_active) { fts_->updateDocument(del_term, fts_doc); } else { fts_->deleteDocuments(del_term); } } void IndexWriter::rebuildFTS() { feature_idx_->listDocuments([this] (const DocID& docid) -> bool { rebuildFTS(docid); return true; }, db_txn_.get()); } RefPtr<mdb::MDBTransaction> IndexWriter::dbTransaction() { return db_txn_; } void IndexWriter::exportStats(const String& prefix) { exportStat( StringUtil::format("$0/documents_indexed_total", prefix), &stat_documents_indexed_total_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_success", prefix), &stat_documents_indexed_success_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_error", prefix), &stat_documents_indexed_error_, fnord::stats::ExportMode::EXPORT_DELTA); exportStat( StringUtil::format("$0/documents_indexed_fts", prefix), &stat_documents_indexed_fts_, fnord::stats::ExportMode::EXPORT_DELTA); } } // namespace cm <|endoftext|>
<commit_before>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <stdlib.h> #ifdef WIN32 #include <conio.h> #include <winsock2.h> #include <process.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <netdb.h> #include <unistd.h> #include <sys/times.h> #endif #include <sys/types.h> #include <fcntl.h> #include <cassert> #include <deque> #include <map> #include <iostream> #include <fstream> #include <event.h> #include <ctime> #include <vector> #include <zlib.h> #include <signal.h> #include "constants.h" #include "mineserver.h" #include "logger.h" #include "sockets.h" #include "tools.h" #include "map.h" #include "user.h" #include "chat.h" #include "worldgen/mapgen.h" #include "config.h" #include "nbt.h" #include "packets.h" #include "physics.h" #include "plugin.h" #include "furnaceManager.h" #include "screen.h" #ifdef WIN32 static bool quit = false; #endif int setnonblock(int fd) { #ifdef WIN32 u_long iMode = 1; ioctlsocket(fd, FIONBIO, &iMode); #else int flags; flags = fcntl(fd, F_GETFL); flags |= O_NONBLOCK; fcntl(fd, F_SETFL, flags); #endif return 1; } //Handle signals void sighandler(int sig_num) { Mineserver::get().stop(); } int main(int argc, char* argv[]) { signal(SIGTERM, sighandler); signal(SIGINT, sighandler); srand(time(NULL)); return Mineserver::get().run(argc, argv); } Mineserver::Mineserver() { } event_base* Mineserver::getEventBase() { return m_eventBase; } void Mineserver::updatePlayerList() { // Update the player window Screen::get()->updatePlayerList(users()); } int Mineserver::run(int argc, char *argv[]) { uint32 starttime = (uint32)time(0); uint32 tick = (uint32)time(0); // Init our Screen Screen::get()->init(VERSION); Screen::get()->log("Welcome to Mineserver v" + VERSION); updatePlayerList(); initConstants(); std::string file_config; file_config.assign(CONFIG_FILE); std::string file_commands; file_commands.assign(COMMANDS_FILE); if (argc > 1) { file_config.assign(argv[1]); } // Initialize conf Conf::get()->load(file_config); Conf::get()->load(file_commands, COMMANDS_NAME_PREFIX); // Write PID to file std::ofstream pid_out((Conf::get()->sValue("pid_file")).c_str()); if (!pid_out.fail()) { #ifdef WIN32 pid_out << _getpid(); #else pid_out << getpid(); #endif } pid_out.close(); // Load admin, banned and whitelisted users Conf::get()->loadRoles(); Conf::get()->loadBanned(); Conf::get()->loadWhitelist(); // Load MOTD Chat::get()->checkMotd(Conf::get()->sValue("motd_file")); // Set physics enable state according to config Physics::get()->enabled = (Conf::get()->bValue("liquid_physics")); // Initialize map Map::get()->init(); if (Conf::get()->bValue("map_generate_spawn")) { Screen::get()->log("Generating spawn area..."); int size = Conf::get()->iValue("map_generate_spawn_size"); bool show_progress = Conf::get()->bValue("map_generate_spawn_show_progress"); #ifdef WIN32 DWORD t_begin,t_end; #else clock_t t_begin,t_end; #endif for (int x=-size;x<=size;x++) { #ifdef WIN32 if(show_progress) { t_begin = timeGetTime(); } #else if(show_progress) { t_begin = clock(); } #endif for (int z = -size; z <= size; z++) { Map::get()->loadMap(x, z); } if(show_progress) { #ifdef WIN32 t_end = timeGetTime (); Screen::get()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos((t_end-t_begin)/(size*2+1)) + "ms per chunk"); #else t_end = clock(); Screen::get()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos(((t_end-t_begin)/(CLOCKS_PER_SEC/1000))/(size*2+1)) + "ms per chunk"); #endif } } #ifdef _DEBUG Screen::get()->log("Spawn area ready!"); #endif } // Initialize packethandler PacketHandler::get()->init(); // Load ip from config std::string ip = Conf::get()->sValue("ip"); // Load port from config int port = Conf::get()->iValue("port"); // Initialize plugins Plugin::get()->init(); #ifdef WIN32 WSADATA wsaData; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if(iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); Screen::get()->end(); return EXIT_FAILURE; } #endif struct sockaddr_in addresslisten; int reuse = 1; m_eventBase = (event_base*)event_init(); #ifdef WIN32 m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); #else m_socketlisten = socket(AF_INET, SOCK_STREAM, 0); #endif if(m_socketlisten < 0) { Screen::get()->log(LOG_ERROR, "Failed to create listen socket"); Screen::get()->end(); return 1; } memset(&addresslisten, 0, sizeof(addresslisten)); addresslisten.sin_family = AF_INET; addresslisten.sin_addr.s_addr = inet_addr(ip.c_str()); addresslisten.sin_port = htons(port); setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse)); //Bind to port if(bind(m_socketlisten, (struct sockaddr*)&addresslisten, sizeof(addresslisten)) < 0) { Screen::get()->log(LOG_ERROR, "Failed to bind"); return 1; } if(listen(m_socketlisten, 5) < 0) { Screen::get()->log(LOG_ERROR, "Failed to listen to socket"); Screen::get()->end(); return 1; } setnonblock(m_socketlisten); event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL); event_add(&m_listenEvent, NULL); /* std::cout << " _____ .__ "<< std::endl<< " / \\ |__| ____ ____ ______ ______________ __ ___________ "<< std::endl<< " / \\ / \\| |/ \\_/ __ \\ / ___// __ \\_ __ \\ \\/ // __ \\_ __ \\"<< std::endl<< "/ Y \\ | | \\ ___/ \\___ \\\\ ___/| | \\/\\ /\\ ___/| | \\/"<< std::endl<< "\\____|__ /__|___| /\\___ >____ >\\___ >__| \\_/ \\___ >__| "<< std::endl<< " \\/ \\/ \\/ \\/ \\/ \\/ "<< std::endl<< "Version " << VERSION <<" by The Mineserver Project"<< std::endl << std::endl; */ if(ip == "0.0.0.0") { // Print all local IPs char name[255]; gethostname ( name, sizeof(name)); struct hostent* hostinfo = gethostbyname(name); Screen::get()->log("Listening on: "); int ipIndex = 0; while(hostinfo && hostinfo->h_addr_list[ipIndex]) { std::string ip(inet_ntoa(*(struct in_addr*)hostinfo->h_addr_list[ipIndex++])); Screen::get()->log(" " + ip + ":" + dtos(port)); } } else { std::string myip(ip); Screen::get()->log("Listening on " + myip + ":" + dtos(port)); } //std::cout << std::endl; timeval loopTime; loopTime.tv_sec = 0; loopTime.tv_usec = 200000; //200ms m_running=true; event_base_loopexit(m_eventBase, &loopTime); // Create our Server Console user so we can issue commands User *serverUser = new User(-1, SERVER_CONSOLE_UID); serverUser->changeNick("[Server]"); while(m_running && event_base_loop(m_eventBase, 0) == 0) { // Append current command and check if user entered return if(Screen::get()->hasCommand()) { // Now handle this command as normal Chat::get()->handleMsg(serverUser, Screen::get()->getCommand().c_str()); } if(time(0)-starttime > 10) { starttime = (uint32)time(0); //Screen::get()->log("Currently " + User::all().size() + " users in!"); //If users, ping them if(User::all().size() > 0) { //0x00 package uint8 data = 0; User::all()[0]->sendAll(&data, 1); //Send server time Packet pkt; pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get()->mapTime; User::all()[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); } //Try to load release time from config int map_release_time = Conf::get()->iValue("map_release_time"); //Release chunks not used in <map_release_time> seconds /* std::vector<uint32> toRelease; for(std::map<uint32, int>::const_iterator it = Map::get()->mapLastused.begin(); it != Map::get()->mapLastused.end(); ++it) { if(Map::get()->mapLastused[it->first] <= time(0)-map_release_time) toRelease.push_back(it->first); } int x_temp, z_temp; for(unsigned i = 0; i < toRelease.size(); i++) { Map::get()->idToPos(toRelease[i], &x_temp, &z_temp); Map::get()->releaseMap(x_temp, z_temp); } */ } //Every second if(time(0)-tick > 0) { tick = (uint32)time(0); //Loop users for(unsigned int i = 0; i < User::all().size(); i++) { User::all()[i]->pushMap(); User::all()[i]->popMap(); //Minecart hacks!! if(User::all()[i]->attachedTo) { Packet pkt; pkt << PACKET_ENTITY_VELOCITY << (sint32)User::all()[i]->attachedTo << (sint16)10000 << (sint16)0 << (sint16)0; //pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)User::all()[i]->attachedTo << (sint8)100 << (sint8)0 << (sint8)0; User::all()[i]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); } } Map::get()->mapTime+=20; if(Map::get()->mapTime>=24000) Map::get()->mapTime=0; Map::get()->checkGenTrees(); // Check for Furnace activity FurnaceManager::get()->update(); } //Physics simulation every 200ms Physics::get()->update(); //Underwater check / drowning for( unsigned int i = 0; i < User::all().size(); i++ ) User::all()[i]->isUnderwater(); // event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL); // event_add(&m_listenEvent, NULL); event_base_loopexit(m_eventBase, &loopTime); } #ifdef WIN32 closesocket(m_socketlisten); #else close(m_socketlisten); #endif // Remove the PID file #ifdef WIN32 _unlink((Conf::get()->sValue("pid_file")).c_str()); #else unlink((Conf::get()->sValue("pid_file")).c_str()); #endif /* Free memory */ PacketHandler::get()->free(); Map::get()->free(); Physics::get()->free(); FurnaceManager::get()->free(); Chat::get()->free(); Conf::get()->free(); Plugin::get()->free(); Logger::get()->free(); MapGen::get()->free(); // End our NCurses session Screen::get()->end(); return EXIT_SUCCESS; } bool Mineserver::stop() { m_running=false; return true; } <commit_msg>Small coding style fix to mineserver.cpp<commit_after>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <stdlib.h> #ifdef WIN32 #include <conio.h> #include <winsock2.h> #include <process.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <netdb.h> #include <unistd.h> #include <sys/times.h> #endif #include <sys/types.h> #include <fcntl.h> #include <cassert> #include <deque> #include <map> #include <iostream> #include <fstream> #include <event.h> #include <ctime> #include <vector> #include <zlib.h> #include <signal.h> #include "constants.h" #include "mineserver.h" #include "logger.h" #include "sockets.h" #include "tools.h" #include "map.h" #include "user.h" #include "chat.h" #include "worldgen/mapgen.h" #include "config.h" #include "nbt.h" #include "packets.h" #include "physics.h" #include "plugin.h" #include "furnaceManager.h" #include "screen.h" #ifdef WIN32 static bool quit = false; #endif int setnonblock(int fd) { #ifdef WIN32 u_long iMode = 1; ioctlsocket(fd, FIONBIO, &iMode); #else int flags; flags = fcntl(fd, F_GETFL); flags |= O_NONBLOCK; fcntl(fd, F_SETFL, flags); #endif return 1; } //Handle signals void sighandler(int sig_num) { Mineserver::get().stop(); } int main(int argc, char* argv[]) { signal(SIGTERM, sighandler); signal(SIGINT, sighandler); srand(time(NULL)); return Mineserver::get().run(argc, argv); } Mineserver::Mineserver() { } event_base* Mineserver::getEventBase() { return m_eventBase; } void Mineserver::updatePlayerList() { // Update the player window Screen::get()->updatePlayerList(users()); } int Mineserver::run(int argc, char *argv[]) { uint32 starttime = (uint32)time(0); uint32 tick = (uint32)time(0); // Init our Screen Screen::get()->init(VERSION); Screen::get()->log("Welcome to Mineserver v" + VERSION); updatePlayerList(); initConstants(); std::string file_config; file_config.assign(CONFIG_FILE); std::string file_commands; file_commands.assign(COMMANDS_FILE); if (argc > 1) { file_config.assign(argv[1]); } // Initialize conf Conf::get()->load(file_config); Conf::get()->load(file_commands, COMMANDS_NAME_PREFIX); // Write PID to file std::ofstream pid_out((Conf::get()->sValue("pid_file")).c_str()); if (!pid_out.fail()) { #ifdef WIN32 pid_out << _getpid(); #else pid_out << getpid(); #endif } pid_out.close(); // Load admin, banned and whitelisted users Conf::get()->loadRoles(); Conf::get()->loadBanned(); Conf::get()->loadWhitelist(); // Load MOTD Chat::get()->checkMotd(Conf::get()->sValue("motd_file")); // Set physics enable state according to config Physics::get()->enabled = (Conf::get()->bValue("liquid_physics")); // Initialize map Map::get()->init(); if (Conf::get()->bValue("map_generate_spawn")) { Screen::get()->log("Generating spawn area..."); int size = Conf::get()->iValue("map_generate_spawn_size"); bool show_progress = Conf::get()->bValue("map_generate_spawn_show_progress"); #ifdef WIN32 DWORD t_begin,t_end; #else clock_t t_begin,t_end; #endif for (int x=-size;x<=size;x++) { #ifdef WIN32 if(show_progress) { t_begin = timeGetTime(); } #else if(show_progress) { t_begin = clock(); } #endif for (int z = -size; z <= size; z++) { Map::get()->loadMap(x, z); } if(show_progress) { #ifdef WIN32 t_end = timeGetTime (); Screen::get()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos((t_end-t_begin)/(size*2+1)) + "ms per chunk"); #else t_end = clock(); Screen::get()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos(((t_end-t_begin)/(CLOCKS_PER_SEC/1000))/(size*2+1)) + "ms per chunk"); #endif } } #ifdef _DEBUG Screen::get()->log("Spawn area ready!"); #endif } // Initialize packethandler PacketHandler::get()->init(); // Load ip from config std::string ip = Conf::get()->sValue("ip"); // Load port from config int port = Conf::get()->iValue("port"); // Initialize plugins Plugin::get()->init(); #ifdef WIN32 WSADATA wsaData; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if(iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); Screen::get()->end(); return EXIT_FAILURE; } #endif struct sockaddr_in addresslisten; int reuse = 1; m_eventBase = (event_base*)event_init(); #ifdef WIN32 m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); #else m_socketlisten = socket(AF_INET, SOCK_STREAM, 0); #endif if(m_socketlisten < 0) { Screen::get()->log(LOG_ERROR, "Failed to create listen socket"); Screen::get()->end(); return 1; } memset(&addresslisten, 0, sizeof(addresslisten)); addresslisten.sin_family = AF_INET; addresslisten.sin_addr.s_addr = inet_addr(ip.c_str()); addresslisten.sin_port = htons(port); setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse)); //Bind to port if(bind(m_socketlisten, (struct sockaddr*)&addresslisten, sizeof(addresslisten)) < 0) { Screen::get()->log(LOG_ERROR, "Failed to bind"); return 1; } if(listen(m_socketlisten, 5) < 0) { Screen::get()->log(LOG_ERROR, "Failed to listen to socket"); Screen::get()->end(); return 1; } setnonblock(m_socketlisten); event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL); event_add(&m_listenEvent, NULL); /* std::cout << " _____ .__ "<< std::endl<< " / \\ |__| ____ ____ ______ ______________ __ ___________ "<< std::endl<< " / \\ / \\| |/ \\_/ __ \\ / ___// __ \\_ __ \\ \\/ // __ \\_ __ \\"<< std::endl<< "/ Y \\ | | \\ ___/ \\___ \\\\ ___/| | \\/\\ /\\ ___/| | \\/"<< std::endl<< "\\____|__ /__|___| /\\___ >____ >\\___ >__| \\_/ \\___ >__| "<< std::endl<< " \\/ \\/ \\/ \\/ \\/ \\/ "<< std::endl<< "Version " << VERSION <<" by The Mineserver Project"<< std::endl << std::endl; */ if(ip == "0.0.0.0") { // Print all local IPs char name[255]; gethostname ( name, sizeof(name)); struct hostent* hostinfo = gethostbyname(name); Screen::get()->log("Listening on: "); int ipIndex = 0; while(hostinfo && hostinfo->h_addr_list[ipIndex]) { std::string ip(inet_ntoa(*(struct in_addr*)hostinfo->h_addr_list[ipIndex++])); Screen::get()->log(" " + ip + ":" + dtos(port)); } } else { std::string myip(ip); Screen::get()->log("Listening on " + myip + ":" + dtos(port)); } //std::cout << std::endl; timeval loopTime; loopTime.tv_sec = 0; loopTime.tv_usec = 200000; //200ms m_running=true; event_base_loopexit(m_eventBase, &loopTime); // Create our Server Console user so we can issue commands User* serverUser = new User(-1, SERVER_CONSOLE_UID); serverUser->changeNick("[Server]"); while(m_running && event_base_loop(m_eventBase, 0) == 0) { // Append current command and check if user entered return if(Screen::get()->hasCommand()) { // Now handle this command as normal Chat::get()->handleMsg(serverUser, Screen::get()->getCommand().c_str()); } if(time(0)-starttime > 10) { starttime = (uint32)time(0); //Screen::get()->log("Currently " + User::all().size() + " users in!"); //If users, ping them if(User::all().size() > 0) { //0x00 package uint8 data = 0; User::all()[0]->sendAll(&data, 1); //Send server time Packet pkt; pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Map::get()->mapTime; User::all()[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); } //Try to load release time from config int map_release_time = Conf::get()->iValue("map_release_time"); //Release chunks not used in <map_release_time> seconds /* std::vector<uint32> toRelease; for(std::map<uint32, int>::const_iterator it = Map::get()->mapLastused.begin(); it != Map::get()->mapLastused.end(); ++it) { if(Map::get()->mapLastused[it->first] <= time(0)-map_release_time) toRelease.push_back(it->first); } int x_temp, z_temp; for(unsigned i = 0; i < toRelease.size(); i++) { Map::get()->idToPos(toRelease[i], &x_temp, &z_temp); Map::get()->releaseMap(x_temp, z_temp); } */ } //Every second if(time(0)-tick > 0) { tick = (uint32)time(0); //Loop users for(unsigned int i = 0; i < User::all().size(); i++) { User::all()[i]->pushMap(); User::all()[i]->popMap(); //Minecart hacks!! if(User::all()[i]->attachedTo) { Packet pkt; pkt << PACKET_ENTITY_VELOCITY << (sint32)User::all()[i]->attachedTo << (sint16)10000 << (sint16)0 << (sint16)0; //pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)User::all()[i]->attachedTo << (sint8)100 << (sint8)0 << (sint8)0; User::all()[i]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen()); } } Map::get()->mapTime+=20; if(Map::get()->mapTime>=24000) Map::get()->mapTime=0; Map::get()->checkGenTrees(); // Check for Furnace activity FurnaceManager::get()->update(); } //Physics simulation every 200ms Physics::get()->update(); //Underwater check / drowning for( unsigned int i = 0; i < User::all().size(); i++ ) User::all()[i]->isUnderwater(); // event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL); // event_add(&m_listenEvent, NULL); event_base_loopexit(m_eventBase, &loopTime); } #ifdef WIN32 closesocket(m_socketlisten); #else close(m_socketlisten); #endif // Remove the PID file #ifdef WIN32 _unlink((Conf::get()->sValue("pid_file")).c_str()); #else unlink((Conf::get()->sValue("pid_file")).c_str()); #endif /* Free memory */ PacketHandler::get()->free(); Map::get()->free(); Physics::get()->free(); FurnaceManager::get()->free(); Chat::get()->free(); Conf::get()->free(); Plugin::get()->free(); Logger::get()->free(); MapGen::get()->free(); // End our NCurses session Screen::get()->end(); return EXIT_SUCCESS; } bool Mineserver::stop() { m_running=false; return true; } <|endoftext|>
<commit_before>#ifndef HEAPS_H #define HEAPS_H #include"objects.hpp" #include<cstring> #include<utility> #include<boost/scoped_ptr.hpp> #include<boost/noncopyable.hpp> class Generic; class ValueHolder; /*----------------------------------------------------------------------------- Semispaces -----------------------------------------------------------------------------*/ class Semispace : boost::noncopyable { private: void* mem; void* allocpt; void* lifoallocpt; size_t prev_alloc; size_t max; public: explicit Semispace(size_t); ~Semispace(); void* alloc(size_t); void dealloc(void*); void* lifo_alloc(void); void lifo_dealloc(void*); void lifo_dealloc_abort(void*); void resize(size_t); bool can_fit(size_t) const; size_t size(void) const { return max; }; size_t used(void) const { return (size_t)(((char*) allocpt) - ((char*) mem)) + (size_t) ((((char*) mem) + max) - ((char*) lifoallocpt)); }; size_t free(void) const { return (size_t)(((char*) lifoallocpt) - ((char*) allocpt)); } void clone(boost::scoped_ptr<Semispace>&, Generic*&) const; friend class Heap; }; /*----------------------------------------------------------------------------- Heaps -----------------------------------------------------------------------------*/ class Heap : boost::noncopyable { private: boost::scoped_ptr<Semispace> main; boost::scoped_ptr<ValueHolder> other_spaces; void GC(void); protected: virtual Object::ref root_object(void) const =0; public: template<class T> inline T* create(void) { /*compile-time checking that T inherits from Generic*/ Generic* _create_template_must_be_Generic_ = static_cast<Generic*>((T*) 0); size_t sz = Object::round_up_to_alignment(sizeof(T)); if(!main->can_fit(sz)) GC(); void* pt = main->alloc(sz); try { new(pt) T(); return pt; } catch(...) { main->dealloc(pt); throw; } } template<class T> inline T* create_variadic(size_t extra) { /*TODO: consider splitting Generic hierarchy into two hierarchies inheriting from Generic, one hierarchy for non-variadic types, the other hierarchy for variadic types. */ Generic* _create_variadic_template_must_be_Generic_ = static_cast<Generic*>((T*) 0); size_t sz = Object::round_up_to_alignment(sizeof(T)) + Object::round_up_to_alignment( extra * sizeof(Object::ref) ) ; if(!main->can_fit(sz)) GC(); void* pt = main->alloc(sz); try { new(pt) T(extra); return pt; } catch(...) { main->dealloc(pt); throw; } } }; #endif //HEAPS_H <commit_msg>inc/heaps.hpp: made free-size querying inline<commit_after>#ifndef HEAPS_H #define HEAPS_H #include"objects.hpp" #include<cstring> #include<utility> #include<boost/scoped_ptr.hpp> #include<boost/noncopyable.hpp> class Generic; class ValueHolder; /*----------------------------------------------------------------------------- Semispaces -----------------------------------------------------------------------------*/ class Semispace : boost::noncopyable { private: void* mem; void* allocpt; void* lifoallocpt; size_t prev_alloc; size_t max; public: explicit Semispace(size_t); ~Semispace(); void* alloc(size_t); void dealloc(void*); void* lifo_alloc(void); void lifo_dealloc(void*); void lifo_dealloc_abort(void*); void resize(size_t); bool can_fit(size_t) const; inline size_t size(void) const { return max; }; inline size_t used(void) const { return (size_t)(((char*) allocpt) - ((char*) mem)) + (size_t) ((((char*) mem) + max) - ((char*) lifoallocpt)); }; inline size_t free(void) const { return (size_t)(((char*) lifoallocpt) - ((char*) allocpt)); } void clone(boost::scoped_ptr<Semispace>&, Generic*&) const; friend class Heap; }; /*----------------------------------------------------------------------------- Heaps -----------------------------------------------------------------------------*/ class Heap : boost::noncopyable { private: boost::scoped_ptr<Semispace> main; boost::scoped_ptr<ValueHolder> other_spaces; void GC(void); protected: virtual Object::ref root_object(void) const =0; public: template<class T> inline T* create(void) { /*compile-time checking that T inherits from Generic*/ Generic* _create_template_must_be_Generic_ = static_cast<Generic*>((T*) 0); size_t sz = Object::round_up_to_alignment(sizeof(T)); if(!main->can_fit(sz)) GC(); void* pt = main->alloc(sz); try { new(pt) T(); return pt; } catch(...) { main->dealloc(pt); throw; } } template<class T> inline T* create_variadic(size_t extra) { /*TODO: consider splitting Generic hierarchy into two hierarchies inheriting from Generic, one hierarchy for non-variadic types, the other hierarchy for variadic types. */ Generic* _create_variadic_template_must_be_Generic_ = static_cast<Generic*>((T*) 0); size_t sz = Object::round_up_to_alignment(sizeof(T)) + Object::round_up_to_alignment( extra * sizeof(Object::ref) ) ; if(!main->can_fit(sz)) GC(); void* pt = main->alloc(sz); try { new(pt) T(extra); return pt; } catch(...) { main->dealloc(pt); throw; } } }; #endif //HEAPS_H <|endoftext|>
<commit_before>#include <libmesh/elem.h> #include <libmesh/cell_hex20.h> #include <libmesh/cell_hex27.h> #include <libmesh/cell_hex8.h> #include <libmesh/cell_inf_hex16.h> #include <libmesh/cell_inf_hex18.h> #include <libmesh/cell_inf_hex8.h> #include <libmesh/cell_inf_prism12.h> #include <libmesh/cell_inf_prism6.h> #include <libmesh/cell_prism15.h> #include <libmesh/cell_prism18.h> #include <libmesh/cell_prism6.h> #include <libmesh/cell_pyramid13.h> #include <libmesh/cell_pyramid14.h> #include <libmesh/cell_pyramid5.h> #include <libmesh/cell_tet10.h> #include <libmesh/cell_tet4.h> #include <libmesh/edge_edge2.h> #include <libmesh/edge_edge3.h> #include <libmesh/edge_edge4.h> #include <libmesh/edge_inf_edge2.h> #include <libmesh/face_inf_quad4.h> #include <libmesh/face_inf_quad6.h> #include <libmesh/face_quad4.h> #include <libmesh/face_quad8.h> #include <libmesh/face_quad9.h> #include <libmesh/face_tri3.h> #include <libmesh/face_tri6.h> // Ignore unused parameter warnings coming from cppunit headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <vector> #define SIDETEST \ CPPUNIT_TEST( testIsNodeOnSide ); \ CPPUNIT_TEST( testNodesOnSide ); \ CPPUNIT_TEST( testSidePtr ); \ CPPUNIT_TEST( testSidePtrFill ); \ CPPUNIT_TEST( testBuildSidePtr ); \ CPPUNIT_TEST( testBuildSidePtrFill ); \ using namespace libMesh; template <typename ElemClass, ElemType side_type, unsigned short indexbegin, unsigned short indexend> class SideTest : public CppUnit::TestCase { private: ElemClass elem; std::vector<Node> nodes; public: void setUp() { elem.set_id() = 0; nodes.resize(elem.n_nodes()); for (auto i : elem.node_index_range()) { nodes[i].set_id() = i; elem.set_node(i) = &nodes[i]; } } void tearDown() {} void testIsNodeOnSide() { for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { std::unique_ptr<Elem> side = elem.build_side_ptr(s); for (auto n : elem.node_index_range()) { const Node * node = elem.node_ptr(n); bool found_node = false; for (auto sn : side->node_index_range()) if (node == side->node_ptr(sn)) { found_node = true; break; } if (elem.is_node_on_side(n, s)) { CPPUNIT_ASSERT(found_node); } else { CPPUNIT_ASSERT(!found_node); } } } } void testNodesOnSide() { for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { std::unique_ptr<Elem> side = elem.build_side_ptr(s); std::vector<unsigned int> side_nodes = elem.nodes_on_side(s); CPPUNIT_ASSERT_EQUAL(side_nodes.size(), std::size_t(side->n_nodes())); for (auto sn : side->node_index_range()) { const Node * node = side->node_ptr(sn); bool found_node = false; for (auto si : side_nodes) if (node == elem.node_ptr(si)) { found_node = true; break; } CPPUNIT_ASSERT(found_node); } } } void testSidePtr() { for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { std::unique_ptr<Elem> side = elem.side_ptr(s); CPPUNIT_ASSERT(side->type() == Elem::first_order_equivalent_type(side_type)); } } void testSidePtrFill() { std::unique_ptr<Elem> side; for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { elem.side_ptr(side, s); CPPUNIT_ASSERT(side->type() == Elem::first_order_equivalent_type(side_type)); } } void testBuildSidePtr() { for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { std::unique_ptr<Elem> side = elem.build_side_ptr(s); CPPUNIT_ASSERT(side->type() == side_type); } } void testBuildSidePtrFill() { std::unique_ptr<Elem> side; for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { elem.build_side_ptr(side, s); std::unique_ptr<Elem> side_new = elem.build_side_ptr(s); CPPUNIT_ASSERT(side->type() == side_type); CPPUNIT_ASSERT(*side == *side_new); } } }; // THE CPPUNIT_TEST_SUITE_END macro expands to code that involves // std::auto_ptr, which in turn produces -Wdeprecated-declarations // warnings. These can be ignored in GCC as long as we wrap the // offending code in appropriate pragmas. We'll put an // ignore_warnings at the end of this file so it's the last warnings // related header that our including code sees. #include <libmesh/ignore_warnings.h> #define INSTANTIATE_SIDETEST(elemclass, sidetype, indexbegin, indexend) \ class SideTest_##elemclass##_##sidetype##_##indexbegin##_##indexend : \ public SideTest<elemclass, sidetype, indexbegin, indexend> { \ public: \ CPPUNIT_TEST_SUITE( SideTest_##elemclass##_##sidetype##_##indexbegin##_##indexend ); \ SIDETEST \ CPPUNIT_TEST_SUITE_END(); \ }; \ \ CPPUNIT_TEST_SUITE_REGISTRATION( SideTest_##elemclass##_##sidetype##_##indexbegin##_##indexend ); INSTANTIATE_SIDETEST(Hex20, QUAD8, 0, 6); INSTANTIATE_SIDETEST(Hex27, QUAD9, 0, 6); INSTANTIATE_SIDETEST(Hex8, QUAD4, 0, 6); INSTANTIATE_SIDETEST(Prism15, TRI6, 0, 1); INSTANTIATE_SIDETEST(Prism15, QUAD8, 1, 4); INSTANTIATE_SIDETEST(Prism15, TRI6, 4, 5); INSTANTIATE_SIDETEST(Prism18, TRI6, 0, 1); INSTANTIATE_SIDETEST(Prism18, QUAD9, 1, 4); INSTANTIATE_SIDETEST(Prism18, TRI6, 4, 5); INSTANTIATE_SIDETEST(Prism6, TRI3, 0, 1); INSTANTIATE_SIDETEST(Prism6, QUAD4, 1, 4); INSTANTIATE_SIDETEST(Prism6, TRI3, 4, 5); INSTANTIATE_SIDETEST(Pyramid13, TRI6, 0, 4); INSTANTIATE_SIDETEST(Pyramid13, QUAD8, 4, 5); INSTANTIATE_SIDETEST(Pyramid14, TRI6, 0, 4); INSTANTIATE_SIDETEST(Pyramid14, QUAD9, 4, 5); INSTANTIATE_SIDETEST(Pyramid5, TRI3, 0, 4); INSTANTIATE_SIDETEST(Pyramid5, QUAD4, 4, 5); INSTANTIATE_SIDETEST(Tet10, TRI6, 0, 4); INSTANTIATE_SIDETEST(Tet4, TRI3, 0, 4); INSTANTIATE_SIDETEST(Edge2, NODEELEM, 0, 2); INSTANTIATE_SIDETEST(Edge3, NODEELEM, 0, 2); INSTANTIATE_SIDETEST(Edge4, NODEELEM, 0, 2); INSTANTIATE_SIDETEST(Quad4, EDGE2, 0, 4); INSTANTIATE_SIDETEST(Quad8, EDGE3, 0, 4); INSTANTIATE_SIDETEST(Quad9, EDGE3, 0, 4); INSTANTIATE_SIDETEST(Tri3, EDGE2, 0, 3); INSTANTIATE_SIDETEST(Tri6, EDGE3, 0, 3); #ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS INSTANTIATE_SIDETEST(InfHex16, QUAD8, 0, 1); INSTANTIATE_SIDETEST(InfHex16, INFQUAD6, 1, 5); INSTANTIATE_SIDETEST(InfHex18, QUAD9, 0, 1); INSTANTIATE_SIDETEST(InfHex18, INFQUAD6, 1, 5); INSTANTIATE_SIDETEST(InfHex8, QUAD4, 0, 1); INSTANTIATE_SIDETEST(InfHex8, INFQUAD4, 1, 5); INSTANTIATE_SIDETEST(InfPrism12, TRI6, 0, 1); INSTANTIATE_SIDETEST(InfPrism12, INFQUAD6, 1, 4); INSTANTIATE_SIDETEST(InfPrism6, TRI3, 0, 1); INSTANTIATE_SIDETEST(InfPrism6, INFQUAD4, 1, 4); INSTANTIATE_SIDETEST(InfEdge2, NODEELEM, 0, 1); INSTANTIATE_SIDETEST(InfQuad4, EDGE2, 0, 1); INSTANTIATE_SIDETEST(InfQuad4, INFEDGE2, 1, 3); INSTANTIATE_SIDETEST(InfQuad6, EDGE3, 0, 1); INSTANTIATE_SIDETEST(InfQuad6, INFEDGE2, 1, 3); #endif // LIBMESH_ENABLE_INFINITE_ELEMENTS <commit_msg>Node copy constructor is deprecated.<commit_after>#include <libmesh/elem.h> #include <libmesh/cell_hex20.h> #include <libmesh/cell_hex27.h> #include <libmesh/cell_hex8.h> #include <libmesh/cell_inf_hex16.h> #include <libmesh/cell_inf_hex18.h> #include <libmesh/cell_inf_hex8.h> #include <libmesh/cell_inf_prism12.h> #include <libmesh/cell_inf_prism6.h> #include <libmesh/cell_prism15.h> #include <libmesh/cell_prism18.h> #include <libmesh/cell_prism6.h> #include <libmesh/cell_pyramid13.h> #include <libmesh/cell_pyramid14.h> #include <libmesh/cell_pyramid5.h> #include <libmesh/cell_tet10.h> #include <libmesh/cell_tet4.h> #include <libmesh/edge_edge2.h> #include <libmesh/edge_edge3.h> #include <libmesh/edge_edge4.h> #include <libmesh/edge_inf_edge2.h> #include <libmesh/face_inf_quad4.h> #include <libmesh/face_inf_quad6.h> #include <libmesh/face_quad4.h> #include <libmesh/face_quad8.h> #include <libmesh/face_quad9.h> #include <libmesh/face_tri3.h> #include <libmesh/face_tri6.h> // Ignore unused parameter warnings coming from cppunit headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <vector> #define SIDETEST \ CPPUNIT_TEST( testIsNodeOnSide ); \ CPPUNIT_TEST( testNodesOnSide ); \ CPPUNIT_TEST( testSidePtr ); \ CPPUNIT_TEST( testSidePtrFill ); \ CPPUNIT_TEST( testBuildSidePtr ); \ CPPUNIT_TEST( testBuildSidePtrFill ); \ using namespace libMesh; template <typename ElemClass, ElemType side_type, unsigned short indexbegin, unsigned short indexend> class SideTest : public CppUnit::TestCase { private: ElemClass elem; std::vector<std::unique_ptr<Node>> nodes; public: void setUp() { elem.set_id() = 0; Point dummy; for (auto i : elem.node_index_range()) { nodes.push_back(libmesh_make_unique<Node>(dummy, /*id=*/i)); elem.set_node(i) = nodes[i].get(); } } void tearDown() {} void testIsNodeOnSide() { for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { std::unique_ptr<Elem> side = elem.build_side_ptr(s); for (auto n : elem.node_index_range()) { const Node * node = elem.node_ptr(n); bool found_node = false; for (auto sn : side->node_index_range()) if (node == side->node_ptr(sn)) { found_node = true; break; } if (elem.is_node_on_side(n, s)) { CPPUNIT_ASSERT(found_node); } else { CPPUNIT_ASSERT(!found_node); } } } } void testNodesOnSide() { for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { std::unique_ptr<Elem> side = elem.build_side_ptr(s); std::vector<unsigned int> side_nodes = elem.nodes_on_side(s); CPPUNIT_ASSERT_EQUAL(side_nodes.size(), std::size_t(side->n_nodes())); for (auto sn : side->node_index_range()) { const Node * node = side->node_ptr(sn); bool found_node = false; for (auto si : side_nodes) if (node == elem.node_ptr(si)) { found_node = true; break; } CPPUNIT_ASSERT(found_node); } } } void testSidePtr() { for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { std::unique_ptr<Elem> side = elem.side_ptr(s); CPPUNIT_ASSERT(side->type() == Elem::first_order_equivalent_type(side_type)); } } void testSidePtrFill() { std::unique_ptr<Elem> side; for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { elem.side_ptr(side, s); CPPUNIT_ASSERT(side->type() == Elem::first_order_equivalent_type(side_type)); } } void testBuildSidePtr() { for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { std::unique_ptr<Elem> side = elem.build_side_ptr(s); CPPUNIT_ASSERT(side->type() == side_type); } } void testBuildSidePtrFill() { std::unique_ptr<Elem> side; for (auto s : IntRange<unsigned short>(indexbegin, indexend)) { elem.build_side_ptr(side, s); std::unique_ptr<Elem> side_new = elem.build_side_ptr(s); CPPUNIT_ASSERT(side->type() == side_type); CPPUNIT_ASSERT(*side == *side_new); } } }; // THE CPPUNIT_TEST_SUITE_END macro expands to code that involves // std::auto_ptr, which in turn produces -Wdeprecated-declarations // warnings. These can be ignored in GCC as long as we wrap the // offending code in appropriate pragmas. We'll put an // ignore_warnings at the end of this file so it's the last warnings // related header that our including code sees. #include <libmesh/ignore_warnings.h> #define INSTANTIATE_SIDETEST(elemclass, sidetype, indexbegin, indexend) \ class SideTest_##elemclass##_##sidetype##_##indexbegin##_##indexend : \ public SideTest<elemclass, sidetype, indexbegin, indexend> { \ public: \ CPPUNIT_TEST_SUITE( SideTest_##elemclass##_##sidetype##_##indexbegin##_##indexend ); \ SIDETEST \ CPPUNIT_TEST_SUITE_END(); \ }; \ \ CPPUNIT_TEST_SUITE_REGISTRATION( SideTest_##elemclass##_##sidetype##_##indexbegin##_##indexend ); INSTANTIATE_SIDETEST(Hex20, QUAD8, 0, 6); INSTANTIATE_SIDETEST(Hex27, QUAD9, 0, 6); INSTANTIATE_SIDETEST(Hex8, QUAD4, 0, 6); INSTANTIATE_SIDETEST(Prism15, TRI6, 0, 1); INSTANTIATE_SIDETEST(Prism15, QUAD8, 1, 4); INSTANTIATE_SIDETEST(Prism15, TRI6, 4, 5); INSTANTIATE_SIDETEST(Prism18, TRI6, 0, 1); INSTANTIATE_SIDETEST(Prism18, QUAD9, 1, 4); INSTANTIATE_SIDETEST(Prism18, TRI6, 4, 5); INSTANTIATE_SIDETEST(Prism6, TRI3, 0, 1); INSTANTIATE_SIDETEST(Prism6, QUAD4, 1, 4); INSTANTIATE_SIDETEST(Prism6, TRI3, 4, 5); INSTANTIATE_SIDETEST(Pyramid13, TRI6, 0, 4); INSTANTIATE_SIDETEST(Pyramid13, QUAD8, 4, 5); INSTANTIATE_SIDETEST(Pyramid14, TRI6, 0, 4); INSTANTIATE_SIDETEST(Pyramid14, QUAD9, 4, 5); INSTANTIATE_SIDETEST(Pyramid5, TRI3, 0, 4); INSTANTIATE_SIDETEST(Pyramid5, QUAD4, 4, 5); INSTANTIATE_SIDETEST(Tet10, TRI6, 0, 4); INSTANTIATE_SIDETEST(Tet4, TRI3, 0, 4); INSTANTIATE_SIDETEST(Edge2, NODEELEM, 0, 2); INSTANTIATE_SIDETEST(Edge3, NODEELEM, 0, 2); INSTANTIATE_SIDETEST(Edge4, NODEELEM, 0, 2); INSTANTIATE_SIDETEST(Quad4, EDGE2, 0, 4); INSTANTIATE_SIDETEST(Quad8, EDGE3, 0, 4); INSTANTIATE_SIDETEST(Quad9, EDGE3, 0, 4); INSTANTIATE_SIDETEST(Tri3, EDGE2, 0, 3); INSTANTIATE_SIDETEST(Tri6, EDGE3, 0, 3); #ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS INSTANTIATE_SIDETEST(InfHex16, QUAD8, 0, 1); INSTANTIATE_SIDETEST(InfHex16, INFQUAD6, 1, 5); INSTANTIATE_SIDETEST(InfHex18, QUAD9, 0, 1); INSTANTIATE_SIDETEST(InfHex18, INFQUAD6, 1, 5); INSTANTIATE_SIDETEST(InfHex8, QUAD4, 0, 1); INSTANTIATE_SIDETEST(InfHex8, INFQUAD4, 1, 5); INSTANTIATE_SIDETEST(InfPrism12, TRI6, 0, 1); INSTANTIATE_SIDETEST(InfPrism12, INFQUAD6, 1, 4); INSTANTIATE_SIDETEST(InfPrism6, TRI3, 0, 1); INSTANTIATE_SIDETEST(InfPrism6, INFQUAD4, 1, 4); INSTANTIATE_SIDETEST(InfEdge2, NODEELEM, 0, 1); INSTANTIATE_SIDETEST(InfQuad4, EDGE2, 0, 1); INSTANTIATE_SIDETEST(InfQuad4, INFEDGE2, 1, 3); INSTANTIATE_SIDETEST(InfQuad6, EDGE3, 0, 1); INSTANTIATE_SIDETEST(InfQuad6, INFEDGE2, 1, 3); #endif // LIBMESH_ENABLE_INFINITE_ELEMENTS <|endoftext|>
<commit_before>// ----------------------------------------------------------------- // libpion: a C++ framework for building lightweight HTTP interfaces // ----------------------------------------------------------------- // Copyright (C) 2007 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Distributed under the Boost Software License, Version 1.0. // See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt // #include <boost/bind.hpp> #include <libpion/PionEngine.hpp> #ifdef PION_WIN32 // for Windows shutdown crash work-around #include <boost/thread/xtime.hpp> #endif namespace pion { // begin namespace pion // static members of PionEngine const unsigned int PionEngine::DEFAULT_NUM_THREADS = 8; PionEngine * PionEngine::m_instance_ptr = NULL; boost::once_flag PionEngine::m_instance_flag = BOOST_ONCE_INIT; // PionEngine member functions void PionEngine::createInstance(void) { static PionEngine pion_instance; m_instance_ptr = &pion_instance; } void PionEngine::startup(void) { // check for errors if (m_is_running) throw AlreadyStartedException(); if (m_servers.empty()) throw NoServersException(); // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); PION_LOG_INFO(m_logger, "Starting up"); // schedule async tasks to listen for each server for (TCPServerMap::iterator i = m_servers.begin(); i!=m_servers.end(); ++i) { i->second->start(); } // start multiple threads to handle async tasks for (unsigned int n = 0; n < m_num_threads; ++n) { boost::shared_ptr<boost::thread> new_thread(new boost::thread( boost::bind(&PionEngine::run, this) )); m_thread_pool.push_back(new_thread); } m_is_running = true; } void PionEngine::shutdown(void) { // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); if (m_is_running) { PION_LOG_INFO(m_logger, "Shutting down"); // stop listening for new connections for (TCPServerMap::iterator i = m_servers.begin(); i!=m_servers.end(); ++i) { i->second->stop(); } // Stop the service to make sure no more events are pending m_asio_service.stop(); if (! m_thread_pool.empty()) { PION_LOG_DEBUG(m_logger, "Waiting for threads to shutdown"); // wait until all threads in the pool have stopped // make sure we do not call join() for the current thread, // since this may yield "undefined behavior" boost::thread current_thread; for (PionThreadPool::iterator i = m_thread_pool.begin(); i != m_thread_pool.end(); ++i) { if (**i != current_thread) (*i)->join(); } // clear the thread pool (also deletes thread objects) m_thread_pool.clear(); } // Reset all of the registered servers m_servers.clear(); #ifdef PION_WIN32 // pause for 1 extra second to work-around shutdown crash on Windows // which seems related to static objects used in the ASIO library boost::xtime stop_time; boost::xtime_get(&stop_time, boost::TIME_UTC); stop_time.sec++; boost::thread::sleep(stop_time); #endif PION_LOG_INFO(m_logger, "Pion has shutdown"); m_is_running = false; m_engine_has_stopped.notify_all(); } else { // Make sure that the servers and thread pool is empty m_servers.clear(); m_thread_pool.clear(); // Make sure anyone waiting on shutdown gets notified // even if the server did not startup successfully m_engine_has_stopped.notify_all(); } } void PionEngine::join(void) { boost::mutex::scoped_lock engine_lock(m_mutex); if (m_is_running) { // sleep until engine_has_stopped condition is signaled m_engine_has_stopped.wait(engine_lock); } } void PionEngine::run(void) { try { // handle I/O events managed by the service m_asio_service.run(); } catch (std::exception& e) { PION_LOG_FATAL(m_logger, "Caught exception in pool thread: " << e.what()); } } bool PionEngine::addServer(TCPServerPtr tcp_server) { // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); // attempt to insert tcp_server into the server map std::pair<TCPServerMap::iterator, bool> result = m_servers.insert( std::make_pair(tcp_server->getPort(), tcp_server) ); return result.second; } HTTPServerPtr PionEngine::addHTTPServer(const unsigned int tcp_port) { HTTPServerPtr http_server(HTTPServer::create(tcp_port)); // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); // attempt to insert http_server into the server map std::pair<TCPServerMap::iterator, bool> result = m_servers.insert( std::make_pair(tcp_port, http_server) ); if (! result.second) http_server.reset(); return http_server; } TCPServerPtr PionEngine::getServer(const unsigned int tcp_port) { // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); // check if a server already exists TCPServerMap::iterator i = m_servers.find(tcp_port); return (i==m_servers.end() ? TCPServerPtr() : i->second); } } // end namespace pion <commit_msg>http://trac.atomiclabs.com/libpion/ticket/30<commit_after>// ----------------------------------------------------------------- // libpion: a C++ framework for building lightweight HTTP interfaces // ----------------------------------------------------------------- // Copyright (C) 2007 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Distributed under the Boost Software License, Version 1.0. // See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt // #include <boost/bind.hpp> #include <libpion/PionEngine.hpp> #ifdef PION_WIN32 // for Windows shutdown crash work-around #include <boost/thread/xtime.hpp> #endif namespace pion { // begin namespace pion // static members of PionEngine const unsigned int PionEngine::DEFAULT_NUM_THREADS = 8; PionEngine * PionEngine::m_instance_ptr = NULL; boost::once_flag PionEngine::m_instance_flag = BOOST_ONCE_INIT; // PionEngine member functions void PionEngine::createInstance(void) { static PionEngine pion_instance; m_instance_ptr = &pion_instance; } void PionEngine::startup(void) { // check for errors if (m_is_running) throw AlreadyStartedException(); if (m_servers.empty()) throw NoServersException(); // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); PION_LOG_INFO(m_logger, "Starting up"); // schedule async tasks to listen for each server for (TCPServerMap::iterator i = m_servers.begin(); i!=m_servers.end(); ++i) { i->second->start(); } // start multiple threads to handle async tasks for (unsigned int n = 0; n < m_num_threads; ++n) { boost::shared_ptr<boost::thread> new_thread(new boost::thread( boost::bind(&PionEngine::run, this) )); m_thread_pool.push_back(new_thread); } m_is_running = true; } void PionEngine::shutdown(void) { // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); if (m_is_running) { PION_LOG_INFO(m_logger, "Shutting down"); // stop listening for new connections for (TCPServerMap::iterator i = m_servers.begin(); i!=m_servers.end(); ++i) { i->second->stop(); } // Stop the service to make sure no more events are pending m_asio_service.stop(); if (! m_thread_pool.empty()) { PION_LOG_DEBUG(m_logger, "Waiting for threads to shutdown"); // wait until all threads in the pool have stopped // make sure we do not call join() for the current thread, // since this may yield "undefined behavior" boost::thread current_thread; for (PionThreadPool::iterator i = m_thread_pool.begin(); i != m_thread_pool.end(); ++i) { if (**i != current_thread) (*i)->join(); } // clear the thread pool (also deletes thread objects) m_thread_pool.clear(); } // Reset all of the registered servers m_servers.clear(); #ifdef PION_WIN32 // pause for 1 extra second to work-around shutdown crash on Windows // which seems related to static objects used in the ASIO library boost::xtime stop_time; boost::xtime_get(&stop_time, boost::TIME_UTC); stop_time.sec++; boost::thread::sleep(stop_time); #endif PION_LOG_INFO(m_logger, "Pion has shutdown"); m_is_running = false; m_engine_has_stopped.notify_all(); } else { // Stop the service to make sure for certain that no events are pending m_asio_service.stop(); // Make sure that the servers and thread pool is empty m_servers.clear(); m_thread_pool.clear(); // Make sure anyone waiting on shutdown gets notified // even if the server did not startup successfully m_engine_has_stopped.notify_all(); } } void PionEngine::join(void) { boost::mutex::scoped_lock engine_lock(m_mutex); if (m_is_running) { // sleep until engine_has_stopped condition is signaled m_engine_has_stopped.wait(engine_lock); } } void PionEngine::run(void) { try { // handle I/O events managed by the service m_asio_service.run(); } catch (std::exception& e) { PION_LOG_FATAL(m_logger, "Caught exception in pool thread: " << e.what()); } } bool PionEngine::addServer(TCPServerPtr tcp_server) { // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); // attempt to insert tcp_server into the server map std::pair<TCPServerMap::iterator, bool> result = m_servers.insert( std::make_pair(tcp_server->getPort(), tcp_server) ); return result.second; } HTTPServerPtr PionEngine::addHTTPServer(const unsigned int tcp_port) { HTTPServerPtr http_server(HTTPServer::create(tcp_port)); // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); // attempt to insert http_server into the server map std::pair<TCPServerMap::iterator, bool> result = m_servers.insert( std::make_pair(tcp_port, http_server) ); if (! result.second) http_server.reset(); return http_server; } TCPServerPtr PionEngine::getServer(const unsigned int tcp_port) { // lock mutex for thread safety boost::mutex::scoped_lock engine_lock(m_mutex); // check if a server already exists TCPServerMap::iterator i = m_servers.find(tcp_port); return (i==m_servers.end() ? TCPServerPtr() : i->second); } } // end namespace pion <|endoftext|>
<commit_before>#include <stdlib.h> #include <errno.h> #include <QtWidgets> #include "p6vxapp.h" #ifndef NOJOYSTICK //SDL使用時にビルドを通すのに必要 #undef main #endif /////////////////////////////////////////////////////////// // メイン /////////////////////////////////////////////////////////// int main( int argc, char *argv[] ) { #ifdef PANDORA //VALGRIND実行時用の環境変数 setenv("DISPLAY", ":0.0", 1); //GlibのOSと開発環境のバージョン不一致に対する暫定対応 //setenv("QT_NO_GLIB", "0", 1); //EGLFS対応 setenv("EGLFS_X11_SIZE", "800x480", 1); setenv("EGLFS_X11_FULLSCREEN", "1", 1); setenv("QT_QPA_EGLFS_DEPTH", "16", 1); setenv("QT_QPA_EGLFS_PHYSICAL_WIDTH", "200", 1); setenv("QT_QPA_EGLFS_PHYSICAL_HEIGHT", "150", 1); #endif //X11の場合用 QCoreApplication::setAttribute(Qt::AA_X11InitThreads); P6VXApp app(argc, argv); QCommandLineParser parser; QCommandLineOption safeModeOption(QStringList() << "s" << "safemode", "Safe Mode"); parser.addOption(safeModeOption); parser.process(app); bool safeMode = parser.isSet(safeModeOption); app.enableSafeMode(safeMode); #ifdef ANDROID app.setCustomRomPath(CUSTOMROMPATH); #endif QLocale locale; QString lang = locale.uiLanguages()[0]; QTranslator myappTranslator; //表示言語が日本語でない場合は英語リソースを読み込む if(lang != "ja-JP" && lang != "ja"){ qDebug() << "LANG = " << lang; myappTranslator.load(":/translation/PC6001VX_en"); app.installTranslator(&myappTranslator); } //イベントループが始まったらp6vxapp::startup()を実行 QMetaObject::invokeMethod(&app, "startup", Qt::QueuedConnection); //イベントループを開始 app.exec(); return true; } <commit_msg>アプリの終了コードが1(true)を返すようになっていたので修正<commit_after>#include <stdlib.h> #include <errno.h> #include <QtWidgets> #include "p6vxapp.h" #ifndef NOJOYSTICK //SDL使用時にビルドを通すのに必要 #undef main #endif /////////////////////////////////////////////////////////// // メイン /////////////////////////////////////////////////////////// int main( int argc, char *argv[] ) { #ifdef PANDORA //VALGRIND実行時用の環境変数 setenv("DISPLAY", ":0.0", 1); //GlibのOSと開発環境のバージョン不一致に対する暫定対応 //setenv("QT_NO_GLIB", "0", 1); //EGLFS対応 setenv("EGLFS_X11_SIZE", "800x480", 1); setenv("EGLFS_X11_FULLSCREEN", "1", 1); setenv("QT_QPA_EGLFS_DEPTH", "16", 1); setenv("QT_QPA_EGLFS_PHYSICAL_WIDTH", "200", 1); setenv("QT_QPA_EGLFS_PHYSICAL_HEIGHT", "150", 1); #endif //X11の場合用 QCoreApplication::setAttribute(Qt::AA_X11InitThreads); P6VXApp app(argc, argv); QCommandLineParser parser; QCommandLineOption safeModeOption(QStringList() << "s" << "safemode", "Safe Mode"); parser.addOption(safeModeOption); parser.process(app); bool safeMode = parser.isSet(safeModeOption); app.enableSafeMode(safeMode); #ifdef ANDROID app.setCustomRomPath(CUSTOMROMPATH); #endif QLocale locale; QString lang = locale.uiLanguages()[0]; QTranslator myappTranslator; //表示言語が日本語でない場合は英語リソースを読み込む if(lang != "ja-JP" && lang != "ja"){ qDebug() << "LANG = " << lang; myappTranslator.load(":/translation/PC6001VX_en"); app.installTranslator(&myappTranslator); } //イベントループが始まったらp6vxapp::startup()を実行 QMetaObject::invokeMethod(&app, "startup", Qt::QueuedConnection); //イベントループを開始 return app.exec(); } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCScheduleModule.cpp // @Author : LvSheng.Huang // @Date : 2016-12-05 // @Module : NFCScheduleModule // // ------------------------------------------------------------------------- #include "NFCScheduleModule.h" void NFCScheduleElement::DoHeartBeatEvent() { if (self.IsNull()) { MODULE_SCHEDULE_FUNCTOR_PTR cb; bool bRet = this->mxModuleFunctor.First(cb); while (bRet) { cb.get()->operator()(mstrScheduleName, mfIntervalTime, mnRemainCount); bRet = this->mxModuleFunctor.Next(cb); } } else { OBJECT_SCHEDULE_FUNCTOR_PTR cb; bool bRet = this->mxObjectFunctor.First(cb); while (bRet) { cb.get()->operator()(self, mstrScheduleName, mfIntervalTime, mnRemainCount); bRet = this->mxObjectFunctor.Next(cb); } } } NFCScheduleModule::NFCScheduleModule(NFIPluginManager* p) { pPluginManager = p; } NFCScheduleModule::~NFCScheduleModule() { mObjectScheduleMap.ClearAll(); } bool NFCScheduleModule::Init() { return true; } bool NFCScheduleModule::Execute() { //execute every schedule NF_SHARE_PTR<NFMapEx <std::string, NFCScheduleElement >> xObjectSchedule = mObjectScheduleMap.First(); while (xObjectSchedule) { std::string str; NF_SHARE_PTR<NFCScheduleElement> pSchedule = xObjectSchedule->First(); while (pSchedule) { NFINT64 nNow = NFGetTime(); if (nNow > pSchedule->mnNextTriggerTime) { if (pSchedule->mnRemainCount > 0 || pSchedule->mbForever == true) { pSchedule->mnRemainCount--; pSchedule->DoHeartBeatEvent(); if (pSchedule->mnRemainCount <= 0 && pSchedule->mbForever == false) { mObjectRemoveList.insert(std::map<NFGUID, std::string>::value_type(pSchedule->self, pSchedule->mstrScheduleName)); } else { NFINT64 nNextCostTime = NFINT64(pSchedule->mfIntervalTime * 1000) * (pSchedule->mnAllCount - pSchedule->mnRemainCount); pSchedule->mnNextTriggerTime = pSchedule->mnStartTime + nNextCostTime; } } } pSchedule = xObjectSchedule->Next(); } xObjectSchedule = mObjectScheduleMap.Next(); } //remove schedule for (std::map<NFGUID, std::string>::iterator it = mObjectRemoveList.begin(); it != mObjectRemoveList.end(); ++it) { NFGUID self = it->first; std::string scheduleName = it->second; auto findIter = mObjectScheduleMap.GetElement(self); if (NULL != findIter) { findIter->RemoveElement(scheduleName); if (findIter->Count() == 0) { mObjectScheduleMap.RemoveElement(self); } } } mObjectRemoveList.clear(); //add schedule for (std::list<NFCScheduleElement>::iterator iter = mObjectAddList.begin(); iter != mObjectAddList.end(); ++iter) { NF_SHARE_PTR< NFMapEx <std::string, NFCScheduleElement >> xObjectScheduleMap = mObjectScheduleMap.GetElement(iter->self); if (NULL == xObjectScheduleMap) { xObjectScheduleMap = NF_SHARE_PTR< NFMapEx <std::string, NFCScheduleElement >>(NF_NEW NFMapEx <std::string, NFCScheduleElement >()); mObjectScheduleMap.AddElement(iter->self, xObjectScheduleMap); } NF_SHARE_PTR<NFCScheduleElement> xScheduleElement = xObjectScheduleMap->GetElement(iter->mstrScheduleName); if (NULL == xScheduleElement) { xScheduleElement = NF_SHARE_PTR<NFCScheduleElement>(NF_NEW NFCScheduleElement()); *xScheduleElement = *iter; xObjectScheduleMap->AddElement(iter->mstrScheduleName, xScheduleElement); } } mObjectAddList.clear(); //////////////////////////////////////////// //execute every schedule NF_SHARE_PTR< NFCScheduleElement > xModuleSchedule = mModuleScheduleMap.First(); while (xModuleSchedule) { NFINT64 nNow = NFGetTime(); if (nNow > xModuleSchedule->mnNextTriggerTime) { if (xModuleSchedule->mnRemainCount > 0 || xModuleSchedule->mbForever == true) { xModuleSchedule->mnRemainCount--; xModuleSchedule->DoHeartBeatEvent(); if (xModuleSchedule->mnRemainCount <= 0 && xModuleSchedule->mbForever == false) { mModuleRemoveList.push_back(xModuleSchedule->mstrScheduleName); } else { NFINT64 nNextCostTime = NFINT64(xModuleSchedule->mfIntervalTime * 1000) * (xModuleSchedule->mnAllCount - xModuleSchedule->mnRemainCount); xModuleSchedule->mnNextTriggerTime = xModuleSchedule->mnStartTime + nNextCostTime; } } } xModuleSchedule = mModuleScheduleMap.Next(); } //remove schedule for (std::list<std::string>::iterator it = mModuleRemoveList.begin(); it != mModuleRemoveList.end(); ++it) { const std::string& strSheduleName = *it;; auto findIter = mModuleScheduleMap.GetElement(strSheduleName); if (NULL != findIter) { mModuleScheduleMap.RemoveElement(strSheduleName); } } mModuleRemoveList.clear(); //add schedule for (std::list<NFCScheduleElement>::iterator iter = mModuleAddList.begin(); iter != mModuleAddList.end(); ++iter) { NF_SHARE_PTR< NFCScheduleElement > xModuleScheduleMap = mModuleScheduleMap.GetElement(iter->mstrScheduleName); if (NULL == xModuleScheduleMap) { xModuleScheduleMap = NF_SHARE_PTR< NFCScheduleElement >(NF_NEW NFCScheduleElement()); mModuleScheduleMap.AddElement(iter->mstrScheduleName, xModuleScheduleMap); } *xModuleScheduleMap = *iter; } mModuleAddList.clear(); return true; } bool NFCScheduleModule::AddSchedule(const std::string & strScheduleName, const MODULE_SCHEDULE_FUNCTOR_PTR & cb, const float fTime, const int nCount) { NFCScheduleElement xSchedule; xSchedule.mstrScheduleName = strScheduleName; xSchedule.mfIntervalTime = fTime; xSchedule.mnNextTriggerTime = NFGetTime() + (NFINT64)(fTime * 1000); xSchedule.mnStartTime = NFGetTime(); xSchedule.mnRemainCount = nCount; xSchedule.mnAllCount = nCount; xSchedule.self = NFGUID(); if (nCount < 0) { xSchedule.mbForever = true; } xSchedule.mxModuleFunctor.Add(cb); mModuleAddList.push_back(xSchedule); return true; } bool NFCScheduleModule::AddSchedule(const std::string & strScheduleName, const MODULE_SCHEDULE_FUNCTOR_PTR & cb, const int nCount, const NFDateTime & date) { return false; } bool NFCScheduleModule::RemoveSchedule(const std::string & strScheduleName) { mModuleRemoveList.push_back(strScheduleName); return true; } bool NFCScheduleModule::ExistSchedule(const std::string & strScheduleName) { return mModuleScheduleMap.ExistElement(strScheduleName); } bool NFCScheduleModule::AddSchedule(const NFGUID self, const std::string& strScheduleName, const OBJECT_SCHEDULE_FUNCTOR_PTR& cb, const float fTime, const int nCount) { NFCScheduleElement xSchedule; xSchedule.mstrScheduleName = strScheduleName; xSchedule.mfIntervalTime = fTime; xSchedule.mnNextTriggerTime = NFGetTime() + (NFINT64)(fTime * 1000); xSchedule.mnStartTime = NFGetTime(); xSchedule.mnRemainCount = nCount; xSchedule.mnAllCount = nCount; xSchedule.self = self; if (nCount < 0) { xSchedule.mbForever = true; } xSchedule.mxObjectFunctor.Add(cb); mObjectAddList.push_back(xSchedule); return true; } bool NFCScheduleModule::AddSchedule(const NFGUID self, const std::string & strScheduleName, const OBJECT_SCHEDULE_FUNCTOR_PTR & cb, const int nCount, const NFDateTime & date) { return false; } bool NFCScheduleModule::RemoveSchedule(const NFGUID self) { return mObjectScheduleMap.RemoveElement(self); } bool NFCScheduleModule::RemoveSchedule(const NFGUID self, const std::string& strScheduleName) { mObjectRemoveList.insert(std::map<NFGUID, std::string>::value_type(self, strScheduleName)); return true; } bool NFCScheduleModule::ExistSchedule(const NFGUID self, const std::string& strScheduleName) { NF_SHARE_PTR< NFMapEx <std::string, NFCScheduleElement >> xObjectScheduleMap = mObjectScheduleMap.GetElement(self); if (NULL == xObjectScheduleMap) { return false; } return xObjectScheduleMap->ExistElement(strScheduleName); } <commit_msg>as a schedule manager, it should has a check when it try to remove a schedule<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCScheduleModule.cpp // @Author : LvSheng.Huang // @Date : 2016-12-05 // @Module : NFCScheduleModule // // ------------------------------------------------------------------------- #include "NFCScheduleModule.h" void NFCScheduleElement::DoHeartBeatEvent() { if (self.IsNull()) { MODULE_SCHEDULE_FUNCTOR_PTR cb; bool bRet = this->mxModuleFunctor.First(cb); while (bRet) { cb.get()->operator()(mstrScheduleName, mfIntervalTime, mnRemainCount); bRet = this->mxModuleFunctor.Next(cb); } } else { OBJECT_SCHEDULE_FUNCTOR_PTR cb; bool bRet = this->mxObjectFunctor.First(cb); while (bRet) { cb.get()->operator()(self, mstrScheduleName, mfIntervalTime, mnRemainCount); bRet = this->mxObjectFunctor.Next(cb); } } } NFCScheduleModule::NFCScheduleModule(NFIPluginManager* p) { pPluginManager = p; } NFCScheduleModule::~NFCScheduleModule() { mObjectScheduleMap.ClearAll(); } bool NFCScheduleModule::Init() { return true; } bool NFCScheduleModule::Execute() { //execute every schedule NF_SHARE_PTR<NFMapEx <std::string, NFCScheduleElement >> xObjectSchedule = mObjectScheduleMap.First(); while (xObjectSchedule) { std::string str; NF_SHARE_PTR<NFCScheduleElement> pSchedule = xObjectSchedule->First(); while (pSchedule) { NFINT64 nNow = NFGetTime(); if (nNow > pSchedule->mnNextTriggerTime) { std::map<NFGUID, std::string>::iterator itRet = mObjectRemoveList.find(pSchedule->self); if (itRet == mObjectRemoveList.end()) { if (itRet->second != pSchedule->mstrScheduleName) { if (pSchedule->mnRemainCount > 0 || pSchedule->mbForever == true) { pSchedule->mnRemainCount--; pSchedule->DoHeartBeatEvent(); if (pSchedule->mnRemainCount <= 0 && pSchedule->mbForever == false) { mObjectRemoveList.insert(std::map<NFGUID, std::string>::value_type(pSchedule->self, pSchedule->mstrScheduleName)); } else { NFINT64 nNextCostTime = NFINT64(pSchedule->mfIntervalTime * 1000) * (pSchedule->mnAllCount - pSchedule->mnRemainCount); pSchedule->mnNextTriggerTime = pSchedule->mnStartTime + nNextCostTime; } } } } } pSchedule = xObjectSchedule->Next(); } xObjectSchedule = mObjectScheduleMap.Next(); } //remove schedule for (std::map<NFGUID, std::string>::iterator it = mObjectRemoveList.begin(); it != mObjectRemoveList.end(); ++it) { NFGUID self = it->first; std::string scheduleName = it->second; auto findIter = mObjectScheduleMap.GetElement(self); if (NULL != findIter) { findIter->RemoveElement(scheduleName); if (findIter->Count() == 0) { mObjectScheduleMap.RemoveElement(self); } } } mObjectRemoveList.clear(); //add schedule for (std::list<NFCScheduleElement>::iterator iter = mObjectAddList.begin(); iter != mObjectAddList.end(); ++iter) { NF_SHARE_PTR< NFMapEx <std::string, NFCScheduleElement >> xObjectScheduleMap = mObjectScheduleMap.GetElement(iter->self); if (NULL == xObjectScheduleMap) { xObjectScheduleMap = NF_SHARE_PTR< NFMapEx <std::string, NFCScheduleElement >>(NF_NEW NFMapEx <std::string, NFCScheduleElement >()); mObjectScheduleMap.AddElement(iter->self, xObjectScheduleMap); } NF_SHARE_PTR<NFCScheduleElement> xScheduleElement = xObjectScheduleMap->GetElement(iter->mstrScheduleName); if (NULL == xScheduleElement) { xScheduleElement = NF_SHARE_PTR<NFCScheduleElement>(NF_NEW NFCScheduleElement()); *xScheduleElement = *iter; xObjectScheduleMap->AddElement(iter->mstrScheduleName, xScheduleElement); } } mObjectAddList.clear(); //////////////////////////////////////////// //execute every schedule NF_SHARE_PTR< NFCScheduleElement > xModuleSchedule = mModuleScheduleMap.First(); while (xModuleSchedule) { NFINT64 nNow = NFGetTime(); if (nNow > xModuleSchedule->mnNextTriggerTime) { if (xModuleSchedule->mnRemainCount > 0 || xModuleSchedule->mbForever == true) { xModuleSchedule->mnRemainCount--; xModuleSchedule->DoHeartBeatEvent(); if (xModuleSchedule->mnRemainCount <= 0 && xModuleSchedule->mbForever == false) { mModuleRemoveList.push_back(xModuleSchedule->mstrScheduleName); } else { NFINT64 nNextCostTime = NFINT64(xModuleSchedule->mfIntervalTime * 1000) * (xModuleSchedule->mnAllCount - xModuleSchedule->mnRemainCount); xModuleSchedule->mnNextTriggerTime = xModuleSchedule->mnStartTime + nNextCostTime; } } } xModuleSchedule = mModuleScheduleMap.Next(); } //remove schedule for (std::list<std::string>::iterator it = mModuleRemoveList.begin(); it != mModuleRemoveList.end(); ++it) { const std::string& strSheduleName = *it;; auto findIter = mModuleScheduleMap.GetElement(strSheduleName); if (NULL != findIter) { mModuleScheduleMap.RemoveElement(strSheduleName); } } mModuleRemoveList.clear(); //add schedule for (std::list<NFCScheduleElement>::iterator iter = mModuleAddList.begin(); iter != mModuleAddList.end(); ++iter) { NF_SHARE_PTR< NFCScheduleElement > xModuleScheduleMap = mModuleScheduleMap.GetElement(iter->mstrScheduleName); if (NULL == xModuleScheduleMap) { xModuleScheduleMap = NF_SHARE_PTR< NFCScheduleElement >(NF_NEW NFCScheduleElement()); mModuleScheduleMap.AddElement(iter->mstrScheduleName, xModuleScheduleMap); } *xModuleScheduleMap = *iter; } mModuleAddList.clear(); return true; } bool NFCScheduleModule::AddSchedule(const std::string & strScheduleName, const MODULE_SCHEDULE_FUNCTOR_PTR & cb, const float fTime, const int nCount) { NFCScheduleElement xSchedule; xSchedule.mstrScheduleName = strScheduleName; xSchedule.mfIntervalTime = fTime; xSchedule.mnNextTriggerTime = NFGetTime() + (NFINT64)(fTime * 1000); xSchedule.mnStartTime = NFGetTime(); xSchedule.mnRemainCount = nCount; xSchedule.mnAllCount = nCount; xSchedule.self = NFGUID(); if (nCount < 0) { xSchedule.mbForever = true; } xSchedule.mxModuleFunctor.Add(cb); mModuleAddList.push_back(xSchedule); return true; } bool NFCScheduleModule::AddSchedule(const std::string & strScheduleName, const MODULE_SCHEDULE_FUNCTOR_PTR & cb, const int nCount, const NFDateTime & date) { return false; } bool NFCScheduleModule::RemoveSchedule(const std::string & strScheduleName) { mModuleRemoveList.push_back(strScheduleName); return true; } bool NFCScheduleModule::ExistSchedule(const std::string & strScheduleName) { return mModuleScheduleMap.ExistElement(strScheduleName); } bool NFCScheduleModule::AddSchedule(const NFGUID self, const std::string& strScheduleName, const OBJECT_SCHEDULE_FUNCTOR_PTR& cb, const float fTime, const int nCount) { NFCScheduleElement xSchedule; xSchedule.mstrScheduleName = strScheduleName; xSchedule.mfIntervalTime = fTime; xSchedule.mnNextTriggerTime = NFGetTime() + (NFINT64)(fTime * 1000); xSchedule.mnStartTime = NFGetTime(); xSchedule.mnRemainCount = nCount; xSchedule.mnAllCount = nCount; xSchedule.self = self; if (nCount < 0) { xSchedule.mbForever = true; } xSchedule.mxObjectFunctor.Add(cb); mObjectAddList.push_back(xSchedule); return true; } bool NFCScheduleModule::AddSchedule(const NFGUID self, const std::string & strScheduleName, const OBJECT_SCHEDULE_FUNCTOR_PTR & cb, const int nCount, const NFDateTime & date) { return false; } bool NFCScheduleModule::RemoveSchedule(const NFGUID self) { return mObjectScheduleMap.RemoveElement(self); } bool NFCScheduleModule::RemoveSchedule(const NFGUID self, const std::string& strScheduleName) { mObjectRemoveList.insert(std::map<NFGUID, std::string>::value_type(self, strScheduleName)); return true; } bool NFCScheduleModule::ExistSchedule(const NFGUID self, const std::string& strScheduleName) { NF_SHARE_PTR< NFMapEx <std::string, NFCScheduleElement >> xObjectScheduleMap = mObjectScheduleMap.GetElement(self); if (NULL == xObjectScheduleMap) { return false; } return xObjectScheduleMap->ExistElement(strScheduleName); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2014-2015 Nathan Miller <Nathan.A.Mill[at]gmail.com> * * Balázs Bámer * * * * This file is part of the FreeCAD CAx development system. * * * * 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., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #include <ShapeFix_Wire.hxx> #include <ShapeExtend_WireData.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <TopoDS.hxx> #include <TopoDS_Wire.hxx> #include <BRepBuilderAPI_Copy.hxx> #include <GeomFill_BezierCurves.hxx> #include <Geom_BoundedSurface.hxx> #include <BRepBuilderAPI_MakeFace.hxx> #endif #include <Base/Exception.h> #include <Base/Tools.h> #include "FeatureBSurf.h" using namespace Surface; PROPERTY_SOURCE(Surface::BSurf, Part::Feature) const char* BSurf::FillTypeEnums[] = {"Invalid", "Sretched", "Coons", "Curved", NULL}; BSurf::BSurf(): Feature() { ADD_PROPERTY_TYPE(FillType, ((long)0), "Surface", App::Prop_None, "Boundary of the surface"); ADD_PROPERTY_TYPE(BoundaryList, (0,"Dummy"), "Surface", App::Prop_None, "Boundary of the surface"); FillType.setEnums(FillTypeEnums); } //Check if any components of the surface have been modified short BSurf::mustExecute() const { if (BoundaryList.isTouched() || FillType.isTouched()) { return 1; } return 0; } GeomFill_FillingStyle BSurf::getFillingStyle() { //Identify filling style int ftype = FillType.getValue(); if(ftype==StretchStyle) {return GeomFill_StretchStyle;} else if(ftype==CoonsStyle) {return GeomFill_CoonsStyle;} else if(ftype==CurvedStyle) {return GeomFill_CurvedStyle;} else {Standard_Failure::Raise("Filling style must be 1 (Stretch), 2 (Coons), or 3 (Curved).");} } void BSurf::getWire(TopoDS_Wire& aWire) { Handle(ShapeFix_Wire) aShFW = new ShapeFix_Wire; Handle(ShapeExtend_WireData) aWD = new ShapeExtend_WireData; int boundaryListSize = BoundaryList.getSize(); if(boundaryListSize > 4 || boundaryListSize < 2) { Standard_Failure::Raise("Only 2-4 curves are allowed"); return; } for(int i = 0; i < boundaryListSize; i++) { Part::TopoShape ts; //Curve TopoShape TopoDS_Shape sub; //Curve TopoDS_Shape TopoDS_Edge etmp; //Curve TopoDS_Edge //Get Edge App::PropertyLinkSubList::SubSet set = BoundaryList[i]; if(set.obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { ts = static_cast<Part::Feature*>(set.obj)->Shape.getShape(); //we want only the subshape which is linked sub = ts.getSubShape(set.sub); // make a copy of the shape and the underlying geometry to avoid to affect the input shapes BRepBuilderAPI_Copy copy(sub); sub = copy.Shape(); if(sub.ShapeType() == TopAbs_EDGE) { //Check Shape type and assign edge etmp = TopoDS::Edge(sub); } else { Standard_Failure::Raise("Curves must be type TopoDS_Edge"); return; //Raise exception } aWD->Add(etmp); } else{Standard_Failure::Raise("Curve not from Part::Feature");return;} } //Reorder the curves and fix the wire if required aShFW->Load(aWD); //Load in the wire aShFW->FixReorder(); //Fix the order of the edges if required aShFW->ClosedWireMode() = Standard_True; //Enables closed wire mode aShFW->FixConnected(); //Fix connection between wires aShFW->FixSelfIntersection(); //Fix Self Intersection aShFW->Perform(); //Perform the fixes aWire = aShFW->Wire(); //Healed Wire if(aWire.IsNull()){Standard_Failure::Raise("Wire unable to be constructed");return;} } void BSurf::createFace(const Handle_Geom_BoundedSurface &aSurface) { BRepBuilderAPI_MakeFace aFaceBuilder; Standard_Real u1, u2, v1, v2; // transfer surface bounds to face aSurface->Bounds(u1, u2, v1, v2); aFaceBuilder.Init(aSurface, u1, u2, v1, v2, Precision::Confusion()); TopoDS_Face aFace = aFaceBuilder.Face(); if(!aFaceBuilder.IsDone()) { Standard_Failure::Raise("Face unable to be constructed");} if (aFace.IsNull()) { Standard_Failure::Raise("Resulting Face is null"); } this->Shape.setValue(aFace); } void BSurf::correcteInvalidFillType() { int ftype = FillType.getValue(); if(ftype == InvalidStyle) { FillType.setValue(StretchStyle); } } <commit_msg>Surface properties are hidden<commit_after>/*************************************************************************** * Copyright (c) 2014-2015 Nathan Miller <Nathan.A.Mill[at]gmail.com> * * Balázs Bámer * * * * This file is part of the FreeCAD CAx development system. * * * * 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., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #include <ShapeFix_Wire.hxx> #include <ShapeExtend_WireData.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <TopoDS.hxx> #include <TopoDS_Wire.hxx> #include <BRepBuilderAPI_Copy.hxx> #include <GeomFill_BezierCurves.hxx> #include <Geom_BoundedSurface.hxx> #include <BRepBuilderAPI_MakeFace.hxx> #endif #include <Base/Exception.h> #include <Base/Tools.h> #include "FeatureBSurf.h" using namespace Surface; PROPERTY_SOURCE(Surface::BSurf, Part::Feature) const char* BSurf::FillTypeEnums[] = {"Invalid", "Sretched", "Coons", "Curved", NULL}; BSurf::BSurf(): Feature() { ADD_PROPERTY_TYPE(FillType, ((long)0), "Surface", App::Prop_Hidden, "Boundary of the surface"); ADD_PROPERTY_TYPE(BoundaryList, (0,"Dummy"), "Surface", App::Prop_Hidden, "Boundary of the surface"); FillType.setEnums(FillTypeEnums); } //Check if any components of the surface have been modified short BSurf::mustExecute() const { if (BoundaryList.isTouched() || FillType.isTouched()) { return 1; } return 0; } GeomFill_FillingStyle BSurf::getFillingStyle() { //Identify filling style int ftype = FillType.getValue(); if(ftype==StretchStyle) {return GeomFill_StretchStyle;} else if(ftype==CoonsStyle) {return GeomFill_CoonsStyle;} else if(ftype==CurvedStyle) {return GeomFill_CurvedStyle;} else {Standard_Failure::Raise("Filling style must be 1 (Stretch), 2 (Coons), or 3 (Curved).");} } void BSurf::getWire(TopoDS_Wire& aWire) { Handle(ShapeFix_Wire) aShFW = new ShapeFix_Wire; Handle(ShapeExtend_WireData) aWD = new ShapeExtend_WireData; int boundaryListSize = BoundaryList.getSize(); if(boundaryListSize > 4 || boundaryListSize < 2) { Standard_Failure::Raise("Only 2-4 curves are allowed"); return; } for(int i = 0; i < boundaryListSize; i++) { Part::TopoShape ts; //Curve TopoShape TopoDS_Shape sub; //Curve TopoDS_Shape TopoDS_Edge etmp; //Curve TopoDS_Edge //Get Edge App::PropertyLinkSubList::SubSet set = BoundaryList[i]; if(set.obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { ts = static_cast<Part::Feature*>(set.obj)->Shape.getShape(); //we want only the subshape which is linked sub = ts.getSubShape(set.sub); // make a copy of the shape and the underlying geometry to avoid to affect the input shapes BRepBuilderAPI_Copy copy(sub); sub = copy.Shape(); if(sub.ShapeType() == TopAbs_EDGE) { //Check Shape type and assign edge etmp = TopoDS::Edge(sub); } else { Standard_Failure::Raise("Curves must be type TopoDS_Edge"); return; //Raise exception } aWD->Add(etmp); } else{Standard_Failure::Raise("Curve not from Part::Feature");return;} } //Reorder the curves and fix the wire if required aShFW->Load(aWD); //Load in the wire aShFW->FixReorder(); //Fix the order of the edges if required aShFW->ClosedWireMode() = Standard_True; //Enables closed wire mode aShFW->FixConnected(); //Fix connection between wires aShFW->FixSelfIntersection(); //Fix Self Intersection aShFW->Perform(); //Perform the fixes aWire = aShFW->Wire(); //Healed Wire if(aWire.IsNull()){Standard_Failure::Raise("Wire unable to be constructed");return;} } void BSurf::createFace(const Handle_Geom_BoundedSurface &aSurface) { BRepBuilderAPI_MakeFace aFaceBuilder; Standard_Real u1, u2, v1, v2; // transfer surface bounds to face aSurface->Bounds(u1, u2, v1, v2); aFaceBuilder.Init(aSurface, u1, u2, v1, v2, Precision::Confusion()); TopoDS_Face aFace = aFaceBuilder.Face(); if(!aFaceBuilder.IsDone()) { Standard_Failure::Raise("Face unable to be constructed");} if (aFace.IsNull()) { Standard_Failure::Raise("Resulting Face is null"); } this->Shape.setValue(aFace); } void BSurf::correcteInvalidFillType() { int ftype = FillType.getValue(); if(ftype == InvalidStyle) { FillType.setValue(StretchStyle); } } <|endoftext|>
<commit_before>#include "../test.h" #include <cuda_runtime_api.h> #include <memory> float calculateCosts(); TEST(Test_CostFunctionCalculator, TryFunctionPointsComposition) { EXPECT_EQ(3.0f, calculateCosts()); } <commit_msg>Add test for CostFunctionCalculator.<commit_after>#include "../test.h" #include <cuda_runtime_api.h> #include <memory> #include <thrust/device_vector.h> #include "../cuda_array_mapper.h" #include "../../src/placement/cost_function_calculator.h" float calculateCosts(); TEST(Test_CostFunctionCalculator, TryFunctionPointsComposition) { EXPECT_EQ(3.0f, calculateCosts()); } TEST(Test_CostFunctionCalculator, TestForFirstLabelWithoutConstraints) { const int side = 16; std::vector<float> constraintImageValues(side * side, 0.0f); cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc(32, 0, 0, 0, cudaChannelFormatKindFloat); auto constraintImage = std::make_shared<CudaArrayMapper<float>>( side, side, constraintImageValues, channelDesc); Placement::CostFunctionCalculator calculator(constraintImage); calculator.resize(side, side); calculator.setTextureSize(side, side); thrust::host_vector<float> occupancy; for (int y = 0; y < side; ++y) { for (int x = 0; x < side; ++x) { occupancy.push_back(y >= 4 && y < 12 && x >= 4 && x < 12 ? 1.0f : 0.0f); } } thrust::device_vector<float> occupancyDevice = occupancy; int labelId = 0; int anchorX = 8; int anchorY = 6; int labelWidthInPixel = 3; int labelHeightInPixel = 3; auto result = calculator.calculateForLabel(occupancyDevice, labelId, anchorX, anchorY, labelWidthInPixel, labelHeightInPixel); EXPECT_EQ(9.0f, std::get<0>(result)); EXPECT_EQ(6.0f, std::get<1>(result)); } <|endoftext|>
<commit_before>// -*- C++ -*- //===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <regex> // template <class charT> struct regex_traits; // charT translate_nocase(charT c) const; // REQUIRES: locale.en_US.UTF-8 // XFAIL: with_system_cxx_lib=macosx10.7 // XFAIL: with_system_cxx_lib=macosx10.8 #include <regex> #include <cassert> #include "test_macros.h" #include "platform_support.h" int main() { { std::regex_traits<char> t; assert(t.translate_nocase(' ') == ' '); assert(t.translate_nocase('A') == 'a'); assert(t.translate_nocase('\x07') == '\x07'); assert(t.translate_nocase('.') == '.'); assert(t.translate_nocase('a') == 'a'); assert(t.translate_nocase('1') == '1'); assert(t.translate_nocase('\xDA') == '\xDA'); assert(t.translate_nocase('\xFA') == '\xFA'); t.imbue(std::locale(LOCALE_en_US_UTF_8)); assert(t.translate_nocase(' ') == ' '); assert(t.translate_nocase('A') == 'a'); assert(t.translate_nocase('\x07') == '\x07'); assert(t.translate_nocase('.') == '.'); assert(t.translate_nocase('a') == 'a'); assert(t.translate_nocase('1') == '1'); } { std::regex_traits<wchar_t> t; assert(t.translate_nocase(L' ') == L' '); assert(t.translate_nocase(L'A') == L'a'); assert(t.translate_nocase(L'\x07') == L'\x07'); assert(t.translate_nocase(L'.') == L'.'); assert(t.translate_nocase(L'a') == L'a'); assert(t.translate_nocase(L'1') == L'1'); assert(t.translate_nocase(L'\xDA') == L'\xDA'); assert(t.translate_nocase(L'\xFA') == L'\xFA'); t.imbue(std::locale(LOCALE_en_US_UTF_8)); assert(t.translate_nocase(L' ') == L' '); assert(t.translate_nocase(L'A') == L'a'); assert(t.translate_nocase(L'\x07') == L'\x07'); assert(t.translate_nocase(L'.') == L'.'); assert(t.translate_nocase(L'a') == L'a'); assert(t.translate_nocase(L'1') == L'1'); assert(t.translate_nocase(L'\xDA') == L'\xFA'); assert(t.translate_nocase(L'\xFA') == L'\xFA'); } } <commit_msg>[libcxx] Remove XFAILs for older macOS versions<commit_after>// -*- C++ -*- //===----------------------------------------------------------------------===// // // 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. // //===----------------------------------------------------------------------===// // <regex> // template <class charT> struct regex_traits; // charT translate_nocase(charT c) const; // REQUIRES: locale.en_US.UTF-8 #include <regex> #include <cassert> #include "test_macros.h" #include "platform_support.h" int main() { { std::regex_traits<char> t; assert(t.translate_nocase(' ') == ' '); assert(t.translate_nocase('A') == 'a'); assert(t.translate_nocase('\x07') == '\x07'); assert(t.translate_nocase('.') == '.'); assert(t.translate_nocase('a') == 'a'); assert(t.translate_nocase('1') == '1'); assert(t.translate_nocase('\xDA') == '\xDA'); assert(t.translate_nocase('\xFA') == '\xFA'); t.imbue(std::locale(LOCALE_en_US_UTF_8)); assert(t.translate_nocase(' ') == ' '); assert(t.translate_nocase('A') == 'a'); assert(t.translate_nocase('\x07') == '\x07'); assert(t.translate_nocase('.') == '.'); assert(t.translate_nocase('a') == 'a'); assert(t.translate_nocase('1') == '1'); } { std::regex_traits<wchar_t> t; assert(t.translate_nocase(L' ') == L' '); assert(t.translate_nocase(L'A') == L'a'); assert(t.translate_nocase(L'\x07') == L'\x07'); assert(t.translate_nocase(L'.') == L'.'); assert(t.translate_nocase(L'a') == L'a'); assert(t.translate_nocase(L'1') == L'1'); assert(t.translate_nocase(L'\xDA') == L'\xDA'); assert(t.translate_nocase(L'\xFA') == L'\xFA'); t.imbue(std::locale(LOCALE_en_US_UTF_8)); assert(t.translate_nocase(L' ') == L' '); assert(t.translate_nocase(L'A') == L'a'); assert(t.translate_nocase(L'\x07') == L'\x07'); assert(t.translate_nocase(L'.') == L'.'); assert(t.translate_nocase(L'a') == L'a'); assert(t.translate_nocase(L'1') == L'1'); assert(t.translate_nocase(L'\xDA') == L'\xFA'); assert(t.translate_nocase(L'\xFA') == L'\xFA'); } } <|endoftext|>
<commit_before>#include <cc1101.hpp> template <typename cc1101> class Radio : public cc1101 { static void setup_common(); public: static void setup_for_rx(); static void setup_for_tx(); }; template <typename cc1101> inline void Radio<cc1101>::setup_common() { // reset cc1101::select(); cc1101::wcmd(CC1101::SRES); cc1101::release(); cc1101::select(); // disable GDO[0,2] pins cc1101::set(CC1101::IOCFG2, 0x2f); cc1101::set(CC1101::IOCFG0, 0x2f); // fix packet length cc1101::set(CC1101::PKTLEN, 16); // packet automation cc1101::set(CC1101::PKTCTRL0, 0x44); // frequency configuration cc1101::set(CC1101::FREQ2, 0x10); cc1101::set(CC1101::FREQ1, 0xa7); cc1101::set(CC1101::FREQ0, 0xe1); // modem configuration cc1101::set(CC1101::MDMCFG4, 0x4d); cc1101::set(CC1101::MDMCFG3, 0x3b); cc1101::set(CC1101::MDMCFG2, 0x73); cc1101::set(CC1101::MDMCFG1, 0xa2); cc1101::set(CC1101::DEVIATN, 0x40); // calibrate cc1101::wcmd(CC1101::SCAL); while ((cc1101::status(CC1101::MARCSTATE) & 0x1f) != 1) ; } template <typename cc1101> inline void Radio<cc1101>::setup_for_rx() { setup_common(); // packet automation cc1101::set(CC1101::PKTCTRL1, 0x2c); // main radio control state machine configuration cc1101::set(CC1101::MCSM1, 0x3c); cc1101::set(CC1101::MCSM0, 0x34); cc1101::release(); } template <typename cc1101> inline void Radio<cc1101>::setup_for_tx() { setup_common(); // main radio control state machine configuration cc1101::set(CC1101::MCSM0, 0x38); // PATABLE cc1101::set(CC1101::PATABLE, 0xc0); cc1101::release(); } <commit_msg>radio tuned<commit_after>#include <cc1101.hpp> template <typename cc1101> class Radio : public cc1101 { static void setup_common(); public: static void setup_for_rx(); static void setup_for_tx(); }; template <typename cc1101> inline void Radio<cc1101>::setup_common() { // reset cc1101::select(); cc1101::wcmd(CC1101::SRES); cc1101::release(); cc1101::select(); // disable GDO[0,2] pins cc1101::set(CC1101::IOCFG2, 0x2f); cc1101::set(CC1101::IOCFG0, 0x2f); // fix packet length cc1101::set(CC1101::PKTLEN, 16); // packet automation cc1101::set(CC1101::PKTCTRL0, 0x44); // frequency configuration cc1101::set(CC1101::FREQ2, 0x10); cc1101::set(CC1101::FREQ1, 0xa7); cc1101::set(CC1101::FREQ0, 0xe1); // modem configuration cc1101::set(CC1101::MDMCFG4, 0x8b); cc1101::set(CC1101::MDMCFG3, 0x83); cc1101::set(CC1101::MDMCFG2, 0x73); cc1101::set(CC1101::MDMCFG1, 0xa2); cc1101::set(CC1101::DEVIATN, 0x40); // calibrate cc1101::wcmd(CC1101::SCAL); while ((cc1101::status(CC1101::MARCSTATE) & 0x1f) != 1) ; } template <typename cc1101> inline void Radio<cc1101>::setup_for_rx() { setup_common(); // packet automation cc1101::set(CC1101::PKTCTRL1, 0x2c); // main radio control state machine configuration cc1101::set(CC1101::MCSM1, 0x3c); cc1101::set(CC1101::MCSM0, 0x34); cc1101::release(); } template <typename cc1101> inline void Radio<cc1101>::setup_for_tx() { setup_common(); // main radio control state machine configuration cc1101::set(CC1101::MCSM0, 0x38); // PATABLE cc1101::set(CC1101::PATABLE, 0xc0); cc1101::release(); } <|endoftext|>
<commit_before>/*********************************************************************************************************************** * TextRenderer.cpp * * Created on: Jan 12, 2011 * Author: Dimitar Asenov **********************************************************************************************************************/ #include "items/TextRenderer.h" #include "items/ItemWithNode.h" #include "Scene.h" #include "VisualizationException.h" #include "shapes/Shape.h" #include <QtGui/QPainter> #include <QtGui/QFontMetrics> namespace Visualization { ITEM_COMMON_DEFINITIONS(TextRenderer) const int MIN_TEXT_WIDTH = 10; int TextRenderer::selectionBegin = 0; int TextRenderer::selectionEnd = 0; int TextRenderer::selectionXBegin = 0; int TextRenderer::selectionXEnd = 0; int TextRenderer::caretX = 0; TextRenderer::TextRenderer(Item* parent, const StyleType *style, const QString& text) : Item(parent, style), text_(text), editable(true) { } bool TextRenderer::setText(const QString& newText) { text_ = newText; this->setUpdateNeeded(); return true; } QString TextRenderer::selectedText() { if (this->hasFocus()) { int xstart = selectionBegin; int xend = selectionEnd; if ( xstart > xend ) { xstart = selectionEnd; xend = selectionBegin; } return text_.mid(xstart, xend - xstart); } else return QString(); } void TextRenderer::determineChildren() { } void TextRenderer::updateGeometry(int, int) { text_ = currentText(); QFontMetrics qfm(style()->font()); QRectF bound; if (text_.isEmpty()) bound.setRect(0, 0, MIN_TEXT_WIDTH, qfm.height()); else { bound = qfm.boundingRect(text_); if (bound.width() < qfm.width(text_)) bound.setWidth(qfm.width(text_)); if (bound.height() < qfm.height()) bound.setHeight(qfm.height()); } if (this->hasShape()) { this->getShape()->setInnerSize(bound.width(), bound.height()); xOffset = -bound.left() + this->getShape()->contentLeft(); yOffset = -bound.top() + this->getShape()->contentTop(); } else { xOffset = -bound.left(); yOffset = -bound.top(); this->setSize(bound.size()); } // Correct underline, otherwise it is drawn in the middle of two pixels and appears fat and transparent. if (style()->font().underline() && qfm.lineWidth() % 2) { xOffset += 0.5; yOffset += 0.5; } if ( this->hasFocus() ) { int xstart = selectionBegin; int xend = selectionEnd; if ( selectionBegin > selectionEnd ) { xstart = selectionEnd; xend = selectionBegin; } selectionXBegin = qfm.width(text_, xstart); selectionXEnd = qfm.width(text_, xend); caretX = (selectionBegin > selectionEnd) ? selectionXBegin : selectionXEnd; } } void TextRenderer::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Item::paint(painter, option, widget); int numSelected = this->scene()->selectedItems().size(); if ( !this->hasFocus() || numSelected > 1 || (numSelected == 1 && !this->isSelected())) { painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawText(QPointF(xOffset, yOffset), text_); } else { if ( selectionXBegin == selectionXEnd || numSelected == 1 ) { // No text is selected, draw all text at once using normal style painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawText(QPointF(xOffset, yOffset), text_); } else { // Some text is selected, draw it differently than non-selected text. int xstart = selectionBegin; int xend = selectionEnd; if ( xstart > xend ) { xstart = selectionEnd; xend = selectionBegin; } // Draw selection background painter->setPen(Qt::NoPen); painter->setBrush(style()->selectionBackground()); painter->drawRect(xOffset + selectionXBegin, 0, selectionXEnd - selectionXBegin, this->height()); painter->setBrush(Qt::NoBrush); // Draw selected text painter->setPen(style()->selectionPen()); painter->setFont(style()->selectionFont()); painter->drawText(QPointF(xOffset + selectionXBegin, yOffset), text_.mid(xstart, xend - xstart)); // Draw non-selected text painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawText(xOffset, yOffset, text_.left(xstart)); painter->drawText(QPointF(xOffset + selectionXEnd, yOffset), text_.mid(xend)); } // Draw caret if ( (selectionXBegin == selectionXEnd && editable) || numSelected == 0) { painter->setPen(style()->caretPen()); painter->drawLine(xOffset + caretX, 1, xOffset + caretX, this->height() - 1); } } } void TextRenderer::selectAll() { selectionBegin = 0; selectionEnd = text_.length(); if (!this->hasFocus()) this->setFocus(); this->setUpdateNeeded(); } void TextRenderer::setSelectedCharacters(int first, int last) { selectionBegin = first; selectionEnd = last; if (!this->hasFocus()) this->setFocus(); this->setUpdateNeeded(); } void TextRenderer::setSelectedByDrag(int xBegin, int xEnd) { selectionBegin = 0; selectionEnd = 0; QFontMetrics qfm(style()->font()); int width = 0; for (int i = 1; i <= text_.length(); ++i) { int new_width = qfm.width(text_, i); if ( xBegin > (new_width + width + 1) / 2 ) selectionBegin++; if ( xEnd > (new_width + width + 1) / 2 ) selectionEnd++; width = new_width; } this->setFocus(); this->setUpdateNeeded(); } } <commit_msg>FIXED: Adjusted the way TextRenderer works to improve the visualization of editable text that does not represent nodes.<commit_after>/*********************************************************************************************************************** * TextRenderer.cpp * * Created on: Jan 12, 2011 * Author: Dimitar Asenov **********************************************************************************************************************/ #include "items/TextRenderer.h" #include "items/ItemWithNode.h" #include "Scene.h" #include "VisualizationException.h" #include "shapes/Shape.h" #include <QtGui/QPainter> #include <QtGui/QFontMetrics> namespace Visualization { ITEM_COMMON_DEFINITIONS(TextRenderer) const int MIN_TEXT_WIDTH = 10; int TextRenderer::selectionBegin = 0; int TextRenderer::selectionEnd = 0; int TextRenderer::selectionXBegin = 0; int TextRenderer::selectionXEnd = 0; int TextRenderer::caretX = 0; TextRenderer::TextRenderer(Item* parent, const StyleType *style, const QString& text) : Item(parent, style), text_(text), editable(true) { } bool TextRenderer::setText(const QString& newText) { text_ = newText; this->setUpdateNeeded(); return true; } QString TextRenderer::selectedText() { if (this->hasFocus()) { int xstart = selectionBegin; int xend = selectionEnd; if ( xstart > xend ) { xstart = selectionEnd; xend = selectionBegin; } return text_.mid(xstart, xend - xstart); } else return QString(); } void TextRenderer::determineChildren() { } void TextRenderer::updateGeometry(int, int) { text_ = currentText(); QFontMetrics qfm(style()->font()); QRectF bound; if (text_.isEmpty()) bound.setRect(0, 0, MIN_TEXT_WIDTH, qfm.height()); else { bound = qfm.boundingRect(text_); if (bound.width() < qfm.width(text_)) bound.setWidth(qfm.width(text_)); if (bound.height() < qfm.height()) bound.setHeight(qfm.height()); } if (this->hasShape()) { this->getShape()->setInnerSize(bound.width(), bound.height()); xOffset = -bound.left() + this->getShape()->contentLeft(); yOffset = -bound.top() + this->getShape()->contentTop(); } else { xOffset = -bound.left(); yOffset = -bound.top(); this->setSize(bound.size()); } // Correct underline, otherwise it is drawn in the middle of two pixels and appears fat and transparent. if (style()->font().underline() && qfm.lineWidth() % 2) { xOffset += 0.5; yOffset += 0.5; } if ( this->hasFocus() ) { int xstart = selectionBegin; int xend = selectionEnd; if ( selectionBegin > selectionEnd ) { xstart = selectionEnd; xend = selectionBegin; } selectionXBegin = qfm.width(text_, xstart); selectionXEnd = qfm.width(text_, xend); caretX = (selectionBegin > selectionEnd) ? selectionXBegin : selectionXEnd; } } void TextRenderer::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Item::paint(painter, option, widget); //int numSelected = this->scene()->selectedItems().size(); if ( !this->hasFocus() /*|| numSelected > 1 || (numSelected == 1 && !this->isSelected())*/) { painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawText(QPointF(xOffset, yOffset), text_); } else { if ( selectionXBegin == selectionXEnd /*|| numSelected == 1*/ ) { // No text is selected, draw all text at once using normal style painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawText(QPointF(xOffset, yOffset), text_); } else { // Some text is selected, draw it differently than non-selected text. int xstart = selectionBegin; int xend = selectionEnd; if ( xstart > xend ) { xstart = selectionEnd; xend = selectionBegin; } // Draw selection background painter->setPen(Qt::NoPen); painter->setBrush(style()->selectionBackground()); painter->drawRect(xOffset + selectionXBegin, 0, selectionXEnd - selectionXBegin, this->height()); painter->setBrush(Qt::NoBrush); // Draw selected text painter->setPen(style()->selectionPen()); painter->setFont(style()->selectionFont()); painter->drawText(QPointF(xOffset + selectionXBegin, yOffset), text_.mid(xstart, xend - xstart)); // Draw non-selected text painter->setPen(style()->pen()); painter->setFont(style()->font()); painter->drawText(xOffset, yOffset, text_.left(xstart)); painter->drawText(QPointF(xOffset + selectionXEnd, yOffset), text_.mid(xend)); } // Draw caret if ( (/*selectionXBegin == selectionXEnd &&*/ editable) /*|| numSelected == 0*/) { painter->setPen(style()->caretPen()); painter->drawLine(xOffset + caretX, 1, xOffset + caretX, this->height() - 1); } } } void TextRenderer::selectAll() { selectionBegin = 0; selectionEnd = text_.length(); if (!this->hasFocus()) this->setFocus(); this->setUpdateNeeded(); } void TextRenderer::setSelectedCharacters(int first, int last) { selectionBegin = first; selectionEnd = last; if (!this->hasFocus()) this->setFocus(); this->setUpdateNeeded(); } void TextRenderer::setSelectedByDrag(int xBegin, int xEnd) { selectionBegin = 0; selectionEnd = 0; QFontMetrics qfm(style()->font()); int width = 0; for (int i = 1; i <= text_.length(); ++i) { int new_width = qfm.width(text_, i); if ( xBegin > (new_width + width + 1) / 2 ) selectionBegin++; if ( xEnd > (new_width + width + 1) / 2 ) selectionEnd++; width = new_width; } this->setFocus(); this->setUpdateNeeded(); } } <|endoftext|>
<commit_before>//===-- sancov.cc --------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a command-line tool for reading and analyzing sanitizer // coverage. //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/DebugInfo/Symbolize/Symbolize.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/LineIterator.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/raw_ostream.h" #include <set> #include <stdio.h> #include <vector> using namespace llvm; namespace { // --------- COMMAND LINE FLAGS --------- enum ActionType { PrintAction, CoveredFunctionsAction }; cl::opt<ActionType> Action( cl::desc("Action (required)"), cl::Required, cl::values(clEnumValN(PrintAction, "print", "Print coverage addresses"), clEnumValN(CoveredFunctionsAction, "covered_functions", "Print all covered funcions."), clEnumValEnd)); static cl::list<std::string> ClInputFiles(cl::Positional, cl::OneOrMore, cl::desc("<filenames...>")); static cl::opt<std::string> ClBinaryName("obj", cl::Required, cl::desc("Path to object file to be symbolized")); static cl::opt<bool> ClDemangle("demangle", cl::init(true), cl::desc("Print demangled function name.")); // --------- FORMAT SPECIFICATION --------- struct FileHeader { uint32_t Bitness; uint32_t Magic; }; static const uint32_t BinCoverageMagic = 0xC0BFFFFF; static const uint32_t Bitness32 = 0xFFFFFF32; static const uint32_t Bitness64 = 0xFFFFFF64; // --------- template <typename T> static void FailIfError(const ErrorOr<T> &E) { if (E) return; auto Error = E.getError(); errs() << "Error: " << Error.message() << "(" << Error.value() << ")\n"; exit(-2); } template <typename T> static void readInts(const char *Start, const char *End, std::vector<uint64_t> *V) { const T *S = reinterpret_cast<const T *>(Start); const T *E = reinterpret_cast<const T *>(End); V->reserve(E - S); std::copy(S, E, std::back_inserter(*V)); } static std::string CommonPrefix(std::string A, std::string B) { if (A.size() > B.size()) return std::string(B.begin(), std::mismatch(B.begin(), B.end(), A.begin()).first); else return std::string(A.begin(), std::mismatch(A.begin(), A.end(), B.begin()).first); } class CoverageData { public: // Read single file coverage data. static ErrorOr<std::unique_ptr<CoverageData>> read(std::string FileName) { ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(FileName); if (!BufOrErr) return BufOrErr.getError(); std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get()); if (Buf->getBufferSize() < 8) { errs() << "File too small (<8): " << Buf->getBufferSize(); return make_error_code(errc::illegal_byte_sequence); } const FileHeader *Header = reinterpret_cast<const FileHeader *>(Buf->getBufferStart()); if (Header->Magic != BinCoverageMagic) { errs() << "Wrong magic: " << Header->Magic; return make_error_code(errc::illegal_byte_sequence); } auto Addrs = make_unique<std::vector<uint64_t>>(); switch (Header->Bitness) { case Bitness64: readInts<uint64_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), Addrs.get()); break; case Bitness32: readInts<uint32_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), Addrs.get()); break; default: errs() << "Unsupported bitness: " << Header->Bitness; return make_error_code(errc::illegal_byte_sequence); } return std::unique_ptr<CoverageData>(new CoverageData(std::move(Addrs))); } // Merge multiple coverage data together. static std::unique_ptr<CoverageData> merge(const std::vector<std::unique_ptr<CoverageData>> &Covs) { std::set<uint64_t> Addrs; for (const auto &Cov : Covs) Addrs.insert(Cov->Addrs->begin(), Cov->Addrs->end()); auto AddrsVector = make_unique<std::vector<uint64_t>>( Addrs.begin(), Addrs.end()); return std::unique_ptr<CoverageData>( new CoverageData(std::move(AddrsVector))); } // Read list of files and merges their coverage info. static ErrorOr<std::unique_ptr<CoverageData>> readAndMerge(const std::vector<std::string> &FileNames) { std::vector<std::unique_ptr<CoverageData>> Covs; for (const auto &FileName : FileNames) { auto Cov = read(FileName); if (!Cov) return Cov.getError(); Covs.push_back(std::move(Cov.get())); } return merge(Covs); } // Print coverage addresses. void printAddrs(raw_ostream &out) { for (auto Addr : *Addrs) { out << "0x"; out.write_hex(Addr); out << "\n"; } } // Print list of covered functions. // Line format: <file_name>:<line> <function_name> void printCoveredFunctions(raw_ostream &out) { if (Addrs->empty()) return; symbolize::LLVMSymbolizer::Options SymbolizerOptions; SymbolizerOptions.Demangle = ClDemangle; symbolize::LLVMSymbolizer Symbolizer; struct FileLoc { std::string FileName; uint32_t Line; bool operator<(const FileLoc &Rhs) const { return std::tie(FileName, Line) < std::tie(Rhs.FileName, Rhs.Line); } }; // FileLoc -> FunctionName std::map<FileLoc, std::string> Fns; // Fill in Fns map. for (auto Addr : *Addrs) { auto InliningInfo = Symbolizer.symbolizeInlinedCode(ClBinaryName, Addr); FailIfError(InliningInfo); for (uint32_t i = 0; i < InliningInfo->getNumberOfFrames(); ++i) { auto FrameInfo = InliningInfo->getFrame(i); SmallString<256> FileName(FrameInfo.FileName); sys::path::remove_dots(FileName, /* remove_dot_dot */ true); FileLoc Loc = { FileName.str(), FrameInfo.Line }; Fns[Loc] = FrameInfo.FunctionName; } } // Compute file names common prefix. std::string FilePrefix = Fns.begin()->first.FileName; for (const auto &P : Fns) FilePrefix = CommonPrefix(FilePrefix, P.first.FileName); // Print first function occurence in a file. { std::string LastFileName; std::set<std::string> ProcessedFunctions; for (const auto &P : Fns) { std::string FileName = P.first.FileName; std::string FunctionName = P.second; uint32_t Line = P.first.Line; if (LastFileName != FileName) ProcessedFunctions.clear(); LastFileName = FileName; if (!ProcessedFunctions.insert(FunctionName).second) continue; out << FileName.substr(FilePrefix.size()) << ":" << Line << " " << FunctionName << "\n"; } } } private: explicit CoverageData(std::unique_ptr<std::vector<uint64_t>> Addrs) : Addrs(std::move(Addrs)) {} std::unique_ptr<std::vector<uint64_t>> Addrs; }; } // namespace int main(int argc, char **argv) { // Print stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "Sanitizer Coverage Processing Tool"); auto CovData = CoverageData::readAndMerge(ClInputFiles); FailIfError(CovData); switch (Action) { case PrintAction: { CovData.get()->printAddrs(outs()); return 0; } case CoveredFunctionsAction: { CovData.get()->printCoveredFunctions(outs()); return 0; } } } <commit_msg>Adding qualifier for make_unique.<commit_after>//===-- sancov.cc --------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a command-line tool for reading and analyzing sanitizer // coverage. //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/DebugInfo/Symbolize/Symbolize.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/LineIterator.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/raw_ostream.h" #include <set> #include <stdio.h> #include <vector> using namespace llvm; namespace { // --------- COMMAND LINE FLAGS --------- enum ActionType { PrintAction, CoveredFunctionsAction }; cl::opt<ActionType> Action( cl::desc("Action (required)"), cl::Required, cl::values(clEnumValN(PrintAction, "print", "Print coverage addresses"), clEnumValN(CoveredFunctionsAction, "covered_functions", "Print all covered funcions."), clEnumValEnd)); static cl::list<std::string> ClInputFiles(cl::Positional, cl::OneOrMore, cl::desc("<filenames...>")); static cl::opt<std::string> ClBinaryName("obj", cl::Required, cl::desc("Path to object file to be symbolized")); static cl::opt<bool> ClDemangle("demangle", cl::init(true), cl::desc("Print demangled function name.")); // --------- FORMAT SPECIFICATION --------- struct FileHeader { uint32_t Bitness; uint32_t Magic; }; static const uint32_t BinCoverageMagic = 0xC0BFFFFF; static const uint32_t Bitness32 = 0xFFFFFF32; static const uint32_t Bitness64 = 0xFFFFFF64; // --------- template <typename T> static void FailIfError(const ErrorOr<T> &E) { if (E) return; auto Error = E.getError(); errs() << "Error: " << Error.message() << "(" << Error.value() << ")\n"; exit(-2); } template <typename T> static void readInts(const char *Start, const char *End, std::vector<uint64_t> *V) { const T *S = reinterpret_cast<const T *>(Start); const T *E = reinterpret_cast<const T *>(End); V->reserve(E - S); std::copy(S, E, std::back_inserter(*V)); } static std::string CommonPrefix(std::string A, std::string B) { if (A.size() > B.size()) return std::string(B.begin(), std::mismatch(B.begin(), B.end(), A.begin()).first); else return std::string(A.begin(), std::mismatch(A.begin(), A.end(), B.begin()).first); } class CoverageData { public: // Read single file coverage data. static ErrorOr<std::unique_ptr<CoverageData>> read(std::string FileName) { ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(FileName); if (!BufOrErr) return BufOrErr.getError(); std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get()); if (Buf->getBufferSize() < 8) { errs() << "File too small (<8): " << Buf->getBufferSize(); return make_error_code(errc::illegal_byte_sequence); } const FileHeader *Header = reinterpret_cast<const FileHeader *>(Buf->getBufferStart()); if (Header->Magic != BinCoverageMagic) { errs() << "Wrong magic: " << Header->Magic; return make_error_code(errc::illegal_byte_sequence); } auto Addrs = llvm::make_unique<std::vector<uint64_t>>(); switch (Header->Bitness) { case Bitness64: readInts<uint64_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), Addrs.get()); break; case Bitness32: readInts<uint32_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), Addrs.get()); break; default: errs() << "Unsupported bitness: " << Header->Bitness; return make_error_code(errc::illegal_byte_sequence); } return std::unique_ptr<CoverageData>(new CoverageData(std::move(Addrs))); } // Merge multiple coverage data together. static std::unique_ptr<CoverageData> merge(const std::vector<std::unique_ptr<CoverageData>> &Covs) { std::set<uint64_t> Addrs; for (const auto &Cov : Covs) Addrs.insert(Cov->Addrs->begin(), Cov->Addrs->end()); auto AddrsVector = llvm::make_unique<std::vector<uint64_t>>( Addrs.begin(), Addrs.end()); return std::unique_ptr<CoverageData>( new CoverageData(std::move(AddrsVector))); } // Read list of files and merges their coverage info. static ErrorOr<std::unique_ptr<CoverageData>> readAndMerge(const std::vector<std::string> &FileNames) { std::vector<std::unique_ptr<CoverageData>> Covs; for (const auto &FileName : FileNames) { auto Cov = read(FileName); if (!Cov) return Cov.getError(); Covs.push_back(std::move(Cov.get())); } return merge(Covs); } // Print coverage addresses. void printAddrs(raw_ostream &out) { for (auto Addr : *Addrs) { out << "0x"; out.write_hex(Addr); out << "\n"; } } // Print list of covered functions. // Line format: <file_name>:<line> <function_name> void printCoveredFunctions(raw_ostream &out) { if (Addrs->empty()) return; symbolize::LLVMSymbolizer::Options SymbolizerOptions; SymbolizerOptions.Demangle = ClDemangle; symbolize::LLVMSymbolizer Symbolizer; struct FileLoc { std::string FileName; uint32_t Line; bool operator<(const FileLoc &Rhs) const { return std::tie(FileName, Line) < std::tie(Rhs.FileName, Rhs.Line); } }; // FileLoc -> FunctionName std::map<FileLoc, std::string> Fns; // Fill in Fns map. for (auto Addr : *Addrs) { auto InliningInfo = Symbolizer.symbolizeInlinedCode(ClBinaryName, Addr); FailIfError(InliningInfo); for (uint32_t i = 0; i < InliningInfo->getNumberOfFrames(); ++i) { auto FrameInfo = InliningInfo->getFrame(i); SmallString<256> FileName(FrameInfo.FileName); sys::path::remove_dots(FileName, /* remove_dot_dot */ true); FileLoc Loc = { FileName.str(), FrameInfo.Line }; Fns[Loc] = FrameInfo.FunctionName; } } // Compute file names common prefix. std::string FilePrefix = Fns.begin()->first.FileName; for (const auto &P : Fns) FilePrefix = CommonPrefix(FilePrefix, P.first.FileName); // Print first function occurence in a file. { std::string LastFileName; std::set<std::string> ProcessedFunctions; for (const auto &P : Fns) { std::string FileName = P.first.FileName; std::string FunctionName = P.second; uint32_t Line = P.first.Line; if (LastFileName != FileName) ProcessedFunctions.clear(); LastFileName = FileName; if (!ProcessedFunctions.insert(FunctionName).second) continue; out << FileName.substr(FilePrefix.size()) << ":" << Line << " " << FunctionName << "\n"; } } } private: explicit CoverageData(std::unique_ptr<std::vector<uint64_t>> Addrs) : Addrs(std::move(Addrs)) {} std::unique_ptr<std::vector<uint64_t>> Addrs; }; } // namespace int main(int argc, char **argv) { // Print stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "Sanitizer Coverage Processing Tool"); auto CovData = CoverageData::readAndMerge(ClInputFiles); FailIfError(CovData); switch (Action) { case PrintAction: { CovData.get()->printAddrs(outs()); return 0; } case CoveredFunctionsAction: { CovData.get()->printCoveredFunctions(outs()); return 0; } } } <|endoftext|>
<commit_before>#include <cctype> #include <cstdlib> #include <fstream> #include <iostream> #include <map> #include <sstream> #include <string> #include <unordered_map> #include "src/ext/cpputil/include/command_line/command_line.h" #include "src/ext/cpputil/include/io/filterstream.h" #include "src/ext/cpputil/include/io/indent.h" #include "src/ext/cpputil/include/system/terminal.h" using namespace cpputil; using namespace std; auto& h1 = Heading::create("I/O options:"); auto& in = ValueArg<string>::create("i") .alternate("in") .usage("<path/to/bin>") .description("Binary file to extract code from") .default_val("./a.out"); auto& out = ValueArg<string>::create("o") .alternate("out") .usage("<path/to/dir>") .description("Directory to write results to") .default_val("out"); typedef map<string, string> line_map; typedef unordered_map<string, size_t> label_map; bool exists(const string& file) { Terminal term; term << "ls " << file << endl; return term.result() == 0; } bool objdump(const string& file) { Terminal term; term << "objdump -d -Msuffix " << file << " > /tmp/stoke.$USER.objdump" << endl; return term.result() == 0; } bool mkdir() { Terminal term; term << "mkdir -p " << out.value() << endl; return term.result() == 0; } void strip_header(ifstream& ifs) { string s; getline(ifs, s); getline(ifs, s); getline(ifs, s); getline(ifs, s); } bool ignore_section_header(ifstream& ifs, string& s) { // Section headers begin with the word 'Displaying' if ( s[0] == 'D' ) { getline(ifs, s); return true; } return false; } string fxn_name(ifstream& ifs, string& s) { // Function names are enclosed in angle brackets const auto begin = s.find_first_of('<') + 1; const auto len = s.find_last_of('>') - begin; return s.substr(begin, len); } line_map index_lines(ifstream& ifs, string& s) { line_map lines; while ( getline(ifs, s) ) { // Functions are terminated by empty lines if ( s.empty() ) { break; } // Address is located between beginning of line and first : auto addr_begin = 0; for ( ; isspace(s[addr_begin]); ++addr_begin); const auto addr_len = s.find_first_of(':') - addr_begin; const auto addr = s.substr(addr_begin, addr_len); // Instructions begin after second tab; blank lines have only one const auto first_tab = s.find_first_of('\t'); const auto second_tab = s.find_first_of('\t', first_tab+1); if ( second_tab == string::npos ) { continue; } const auto instr_begin = second_tab + 1; // Instruction are terminated by eol, # or < auto comment = s.find_last_of('#'); comment = comment == string::npos ? s.length() : comment; auto annot = s.find_last_of('<'); annot = annot == string::npos ? s.length() : annot; const auto instr_end = min(comment, annot); const auto instr_len = (instr_end == string::npos ? s.length() : instr_end) - instr_begin; const auto instr = s.substr(instr_begin, instr_len); // Insert this line lines[addr] = instr; } return lines; } label_map replace_label_uses(line_map& lines) { label_map labels; for ( auto& l : lines ) { const auto& instr = l.second; // Opcodes are followed by at least one space; ignore instructions with no operands auto ops_begin = instr.find_first_of(' '); for ( ; isspace(instr[ops_begin]); ops_begin++ ); if ( ops_begin == instr.length() ) { continue; } // Operands are terminated by whitespace const auto ops_end = instr.find_first_of(' ', ops_begin+1); const auto ops_len = (ops_end == string::npos ? instr.length() : ops_end) - ops_begin; const auto ops = instr.substr(ops_begin, ops_len); // Replace any argument which is strictly hex digits auto skip = false; for ( auto c : ops ) { if ( !isxdigit(c) ) { skip = true; } } if ( !skip ) { const auto itr = labels.insert(make_pair(ops, labels.size())).first; ostringstream oss; oss << instr.substr(0, ops_begin) << ".LABEL_" << itr->second; l.second = oss.str(); } } return labels; } void emit_fxn(const string& fxn, const line_map& lines, const label_map& labels) { ofstream ofs(out.value() + "/" + fxn + ".s"); ofilterstream<Indent> os(ofs); os.filter().indent(); os << ".text" << endl; os << ".globl " << fxn << endl; os << ".type " << fxn << ", @function" << endl; os.filter().unindent(); os << fxn << ":" << endl; os.filter().indent(); for ( const auto& l : lines ) { const auto itr = labels.find(l.first); if ( itr != labels.end() ) { os.filter().unindent(); os << ".LABEL_" << itr->second << ":" << endl; os.filter().indent(); } os << l.second << endl; } os << ".size " << fxn << ", .-" << fxn << endl; } int main(int argc, char** argv) { CommandLineConfig::strict_with_convenience(argc, argv); if (!exists(in)) { cout << "Unable to read binary file " << in.value() << "!" << endl; return 1; } else if (!mkdir()) { cout << "Unable to create output directory " << out.value() << "!" << endl; return 1; } else if (!objdump(in)) { cout << "Unable to extract object code from binary file " << in.value() << "!" << endl; return 1; } ifstream ifs(string("/tmp/stoke.") + getenv("USER") + ".objdump"); string s; strip_header(ifs); while ( getline(ifs, s) ) { if ( ignore_section_header(ifs, s) ) { continue; } const auto fxn = fxn_name(ifs, s); auto lines = index_lines(ifs, s); const auto labels = replace_label_uses(lines); emit_fxn(fxn, lines, labels); } return 0; } <commit_msg>Awesome. Extract is fast now.<commit_after>#include <cctype> #include <cstdlib> #include <fstream> #include <iostream> #include <map> #include <sstream> #include <string> #include <unordered_map> #include "src/ext/cpputil/include/command_line/command_line.h" #include "src/ext/cpputil/include/io/filterstream.h" #include "src/ext/cpputil/include/io/indent.h" #include "src/ext/cpputil/include/system/terminal.h" using namespace cpputil; using namespace std; auto& h1 = Heading::create("I/O options:"); auto& in = ValueArg<string>::create("i") .alternate("in") .usage("<path/to/bin>") .description("Binary file to extract code from") .default_val("./a.out"); auto& out = ValueArg<string>::create("o") .alternate("out") .usage("<path/to/dir>") .description("Directory to write results to") .default_val("out"); typedef map<string, string> line_map; typedef unordered_map<string, size_t> label_map; bool exists(const string& file) { Terminal term; term << "ls " << file << " >> /dev/null" << endl; return term.result() == 0; } bool objdump(const string& file) { Terminal term; term << "objdump -d -Msuffix " << file << " > /tmp/stoke.$USER.objdump >> /dev/null" << endl; return term.result() == 0; } bool mkdir() { Terminal term; term << "mkdir -p " << out.value() << " >> /dev/null" << endl; return term.result() == 0; } void strip_header(ifstream& ifs) { string s; getline(ifs, s); getline(ifs, s); getline(ifs, s); getline(ifs, s); } bool ignore_section_header(ifstream& ifs, string& s) { // Section headers begin with the word 'Displaying' if ( s[0] == 'D' ) { getline(ifs, s); return true; } return false; } string fxn_name(ifstream& ifs, string& s) { // Function names are enclosed in angle brackets const auto begin = s.find_first_of('<') + 1; const auto len = s.find_last_of('>') - begin; return s.substr(begin, len); } line_map index_lines(ifstream& ifs, string& s) { line_map lines; while ( getline(ifs, s) ) { // Functions are terminated by empty lines if ( s.empty() ) { break; } // Address is located between beginning of line and first : auto addr_begin = 0; for ( ; isspace(s[addr_begin]); ++addr_begin); const auto addr_len = s.find_first_of(':') - addr_begin; const auto addr = s.substr(addr_begin, addr_len); // Instructions begin after second tab; blank lines have only one const auto first_tab = s.find_first_of('\t'); const auto second_tab = s.find_first_of('\t', first_tab+1); if ( second_tab == string::npos ) { continue; } const auto instr_begin = second_tab + 1; // Instruction are terminated by eol, # or < auto comment = s.find_last_of('#'); comment = comment == string::npos ? s.length() : comment; auto annot = s.find_last_of('<'); annot = annot == string::npos ? s.length() : annot; const auto instr_end = min(comment, annot); const auto instr_len = (instr_end == string::npos ? s.length() : instr_end) - instr_begin; const auto instr = s.substr(instr_begin, instr_len); // Insert this line lines[addr] = instr; } return lines; } label_map replace_label_uses(line_map& lines) { label_map labels; for ( auto& l : lines ) { const auto& instr = l.second; // Opcodes are followed by at least one space; ignore instructions with no operands auto ops_begin = instr.find_first_of(' '); if ( ops_begin == string::npos ) { continue; } for ( ; isspace(instr[ops_begin]); ops_begin++ ); if ( ops_begin == instr.length() ) { continue; } // Operands are terminated by whitespace const auto ops_end = instr.find_first_of(' ', ops_begin+1); const auto ops_len = (ops_end == string::npos ? instr.length() : ops_end) - ops_begin; const auto ops = instr.substr(ops_begin, ops_len); // Replace any argument which is strictly hex digits auto skip = false; for ( auto c : ops ) { if ( !isxdigit(c) ) { skip = true; } } if ( !skip ) { const auto itr = labels.insert(make_pair(ops, labels.size())).first; ostringstream oss; oss << instr.substr(0, ops_begin) << ".LABEL_" << itr->second; l.second = oss.str(); } } return labels; } void emit_fxn(const string& fxn, const line_map& lines, const label_map& labels) { ofstream ofs(out.value() + "/" + fxn + ".s"); ofilterstream<Indent> os(ofs); os.filter().indent(); os << ".text" << endl; os << ".globl " << fxn << endl; os << ".type " << fxn << ", @function" << endl; os.filter().unindent(); os << fxn << ":" << endl; os.filter().indent(); for ( const auto& l : lines ) { const auto itr = labels.find(l.first); if ( itr != labels.end() ) { os.filter().unindent(); os << ".LABEL_" << itr->second << ":" << endl; os.filter().indent(); } os << l.second << endl; } os << ".size " << fxn << ", .-" << fxn << endl; } int main(int argc, char** argv) { CommandLineConfig::strict_with_convenience(argc, argv); if (!exists(in)) { cout << "Unable to read binary file " << in.value() << "!" << endl; return 1; } else if (!mkdir()) { cout << "Unable to create output directory " << out.value() << "!" << endl; return 1; } else if (!objdump(in)) { cout << "Unable to extract object code from binary file " << in.value() << "!" << endl; return 1; } ifstream ifs(string("/tmp/stoke.") + getenv("USER") + ".objdump"); string s; strip_header(ifs); while ( getline(ifs, s) ) { if ( ignore_section_header(ifs, s) ) { continue; } const auto fxn = fxn_name(ifs, s); auto lines = index_lines(ifs, s); const auto labels = replace_label_uses(lines); emit_fxn(fxn, lines, labels); } return 0; } <|endoftext|>
<commit_before> #define TEST_CASE #include <boost/test/included/unit_test.hpp> #define TCP_SESSION_H namespace l7vs{ class tcp_session{ public: enum TCP_PROCESS_TYPE_TAG{ LOCAL_PROC = 0, MESSAGE_PROC }; tcp_session(); ~tcp_session(); }; } #include "../../../src/tcp_thread_message.cpp" using namespace boost::unit_test_framework; //--test case-- void construcor_test(){ BOOST_MESSAGE( "----- construcor test start -----" ); l7vs::tcp_thread_message test; BOOST_MESSAGE( "----- construcor test end -----" ); } test_suite* init_unit_test_suite( int argc, char* argv[] ){ test_suite* ts = BOOST_TEST_SUITE( "l7vs::tcp_thread_message class test" ); ts->add( BOOST_TEST_CASE( &construcor_test ) ); framework::master_test_suite().add( ts ); return NULL; } <commit_msg>インクルード先を修正<commit_after> #define TEST_CASE #include <boost/test/included/unit_test.hpp> #define TCP_SESSION_H namespace l7vs{ class tcp_session{ public: enum TCP_PROCESS_TYPE_TAG{ LOCAL_PROC = 0, MESSAGE_PROC }; tcp_session(); ~tcp_session(); }; } //#include "../../../src/tcp_thread_message.cpp" #include "../../../include/tcp_thread_message.h" using namespace boost::unit_test_framework; //--test case-- void construcor_test(){ BOOST_MESSAGE( "----- construcor test start -----" ); l7vs::tcp_thread_message test; BOOST_MESSAGE( "----- construcor test end -----" ); } test_suite* init_unit_test_suite( int argc, char* argv[] ){ test_suite* ts = BOOST_TEST_SUITE( "l7vs::tcp_thread_message class test" ); ts->add( BOOST_TEST_CASE( &construcor_test ) ); framework::master_test_suite().add( ts ); return NULL; } <|endoftext|>
<commit_before>#include "Maze.h" Model *model = new Model(); Status *status = new Status(); void Maze::Timer(int value) { ALint state; glutTimerFunc(status->timer, Timer, 0); alGetSourcei(status->source, AL_SOURCE_STATE, &state); if (status->tecla_o) { if (state != AL_PLAYING) alSourcePlay(status->source); else{ if (state==AL_PLAYING) alSourceStop(status->source); } } glutPostRedisplay(); } void Maze::Launch(int argc, char **argv){ glutInit(&argc, argv); /* need both double buffering and z buffer */ glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutCreateWindow("OpenGL"); glutReshapeFunc(Graphics::myReshape); glutDisplayFunc(Graphics::display); glutKeyboardFunc(Keyboard::keyboard); glutSpecialFunc(Keyboard::Special); glutMouseFunc(Mouse::mouse); glutTimerFunc(status->timer, Timer, 0); GLfloat LuzAmbiente[] = { 0.5, 0.5, 0.5, 0.0 }; Graphics::createTextures(model->texID); glClearColor(0.0, 0.0, 0.0, 0.0); glEnable(GL_SMOOTH); /*enable smooth shading */ glEnable(GL_LIGHTING); /* enable lighting */ glEnable(GL_DEPTH_TEST); /* enable z buffer */ glEnable(GL_NORMALIZE); glEnable(GL_TEXTURE_2D); glDepthFunc(GL_LESS); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LuzAmbiente); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, status->lightViewer); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); model->quad = gluNewQuadric(); gluQuadricDrawStyle(model->quad, GLU_FILL); gluQuadricNormals(model->quad, GLU_OUTSIDE); leGrafo(); Keyboard::help(); glutMainLoop(); } <commit_msg>Update Maze.cpp to include MainCharacter #25<commit_after>#include "Maze.h" #include "MainCharacter.h" Model *model = new Model(); Status *status = new Status(); MainCharacter *character = new MainCharacter(); void Maze::Timer(int value) { ALint state; glutTimerFunc(status->timer, Timer, 0); alGetSourcei(status->source, AL_SOURCE_STATE, &state); if (status->tecla_o) { if (state != AL_PLAYING) alSourcePlay(status->source); else{ if (state==AL_PLAYING) alSourceStop(status->source); } } glutPostRedisplay(); } void Maze::Launch(int argc, char **argv){ glutInit(&argc, argv); /* need both double buffering and z buffer */ glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(640, 480); glutCreateWindow("OpenGL"); glutReshapeFunc(Graphics::myReshape); glutDisplayFunc(Graphics::display); glutKeyboardFunc(Keyboard::keyboard); glutSpecialFunc(Keyboard::Special); glutMouseFunc(Mouse::mouse); glutTimerFunc(status->timer, Timer, 0); GLfloat LuzAmbiente[] = { 0.5, 0.5, 0.5, 0.0 }; Graphics::createTextures(model->texID); glClearColor(0.0, 0.0, 0.0, 0.0); glEnable(GL_SMOOTH); /*enable smooth shading */ glEnable(GL_LIGHTING); /* enable lighting */ glEnable(GL_DEPTH_TEST); /* enable z buffer */ glEnable(GL_NORMALIZE); glEnable(GL_TEXTURE_2D); glDepthFunc(GL_LESS); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, LuzAmbiente); glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, status->lightViewer); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); model->quad = gluNewQuadric(); gluQuadricDrawStyle(model->quad, GLU_FILL); gluQuadricNormals(model->quad, GLU_OUTSIDE); leGrafo(); Keyboard::help(); glutMainLoop(); } <|endoftext|>
<commit_before>#include "CalculatorTopTwo.h" #include <algorithm> #include <cassert> namespace tilegen { namespace alpha { void CalculatorTopTwo::updateAlphasAux(const Weights& weights) { initialiseIndexedWeights(weights); std::sort(mIndexedWeights.begin(), mIndexedWeights.end(), std::greater<IndexedWeight>()); const IndexedWeight& winner = mIndexedWeights[0]; const IndexedWeight& runner_up = mIndexedWeights[1]; const IndexedWeight& base = mIndexedWeights[2]; double winner_margin = winner.first - runner_up.first; double runner_up_margin = runner_up.first - base.first; double margin_sum = winner_margin + runner_up_margin; assert(winner_margin >= 0.); assert(runner_up_margin >= 0.); assert(margin_sum >= 0.); if (margin_sum <= 255 * std::numeric_limits<double>::epsilon()) { getAlpha(winner.second) = 128; getAlpha(runner_up.second) = 127; return; } else { double runner_up_scaled = pow(runner_up_margin / margin_sum, power); sf::Uint8 runner_up_share = std::max(0, std::min(255, int((255. * runner_up_scaled) / (1. + runner_up_scaled)))); getAlpha(winner.second) = 255 - runner_up_share; getAlpha(runner_up.second) = runner_up_share; } } void CalculatorTopTwo::initialiseIndexedWeights(const Weights& weights) { size_t count = 0; mIndexedWeights.resize(weights.size()); std::transform(weights.cbegin(), weights.cend(), mIndexedWeights.begin(), [&count](double x) { return std::make_pair(x, count++); }); } } // namespace alpha } // namespace tilegen <commit_msg>Remove winner_margin variable<commit_after>#include "CalculatorTopTwo.h" #include <algorithm> #include <cassert> namespace tilegen { namespace alpha { void CalculatorTopTwo::updateAlphasAux(const Weights& weights) { initialiseIndexedWeights(weights); std::sort(mIndexedWeights.begin(), mIndexedWeights.end(), std::greater<IndexedWeight>()); const IndexedWeight& winner = mIndexedWeights[0]; const IndexedWeight& runner_up = mIndexedWeights[1]; const IndexedWeight& base = mIndexedWeights[2]; double runner_up_margin = runner_up.first - base.first; double margin_sum = winner.first - base.first; assert(runner_up_margin >= 0.); assert(margin_sum >= 0.); assert(margin_sum >= runner_up_margin); if (margin_sum <= 255 * std::numeric_limits<double>::epsilon()) { getAlpha(winner.second) = 128; getAlpha(runner_up.second) = 127; return; } else { double runner_up_scaled = pow(runner_up_margin / margin_sum, power); sf::Uint8 runner_up_share = std::max(0, std::min(255, int((255. * runner_up_scaled) / (1. + runner_up_scaled)))); getAlpha(winner.second) = 255 - runner_up_share; getAlpha(runner_up.second) = runner_up_share; } } void CalculatorTopTwo::initialiseIndexedWeights(const Weights& weights) { size_t count = 0; mIndexedWeights.resize(weights.size()); std::transform(weights.cbegin(), weights.cend(), mIndexedWeights.begin(), [&count](double x) { return std::make_pair(x, count++); }); } } // namespace alpha } // namespace tilegen <|endoftext|>
<commit_before>/* * Manager.cpp * * Created on: 23 Oct 2015 * Author: hieu */ #include <boost/foreach.hpp> #include <vector> #include <sstream> #include "Manager.h" #include "SearchNormal.h" #include "SearchNormalBatch.h" #include "CubePruning/Search.h" #include "../System.h" #include "../TargetPhrases.h" #include "../TargetPhrase.h" #include "../InputPaths.h" #include "../InputPath.h" #include "../Sentence.h" #include "../TranslationModel/PhraseTable.h" #include "../legacy/Range.h" using namespace std; namespace Moses2 { Manager::Manager(System &sys, const TranslationTask &task, const std::string &inputStr, long translationId) :system(sys) ,task(task) ,m_inputStr(inputStr) ,m_translationId(translationId) {} Manager::~Manager() { delete m_search; delete m_estimatedScores; GetPool().Reset(); GetHypoRecycle().Reset(); } void Manager::Init() { // init pools etc m_pool = &system.GetManagerPool(); m_hypoRecycle = &system.GetHypoRecycler(); m_initPhrase = new (GetPool().Allocate<TargetPhrase>()) TargetPhrase(GetPool(), system, 0); // create input phrase obj FactorCollection &vocab = system.GetVocab(); m_input = Sentence::CreateFromString(GetPool(), vocab, system, m_inputStr, m_translationId); m_inputPaths.Init(*m_input, system); const std::vector<const PhraseTable*> &pts = system.mappings; for (size_t i = 0; i < pts.size(); ++i) { const PhraseTable &pt = *pts[i]; //cerr << "Looking up from " << pt.GetName() << endl; pt.Lookup(*this, m_inputPaths); } //m_inputPaths.DeleteUnusedPaths(); CalcFutureScore(); m_bitmaps.Init(m_input->GetSize(), vector<bool>(0)); switch (system.searchAlgorithm) { case Normal: m_search = new SearchNormal(*this); break; case NormalBatch: m_search = new SearchNormalBatch(*this); break; case CubePruning: m_search = new NSCubePruning::Search(*this); break; default: cerr << "Unknown search algorithm" << endl; abort(); } } void Manager::Decode() { Init(); m_search->Decode(); OutputBest(); } void Manager::CalcFutureScore() { size_t size = m_input->GetSize(); m_estimatedScores = new SquareMatrix(size); m_estimatedScores->InitTriangle(-numeric_limits<SCORE>::infinity()); // walk all the translation options and record the cheapest option for each span BOOST_FOREACH(const InputPath &path, m_inputPaths) { const Range &range = path.range; const std::vector<const TargetPhrases*> &allTps = path.targetPhrases; SCORE bestScore = -numeric_limits<SCORE>::infinity(); BOOST_FOREACH(const TargetPhrases *tps, allTps) { if (tps) { BOOST_FOREACH(const TargetPhrase *tp, *tps) { SCORE score = tp->GetFutureScore(); if (score > bestScore) { bestScore = score; } } } } m_estimatedScores->SetScore(range.GetStartPos(), range.GetEndPos(), bestScore); } // now fill all the cells in the strictly upper triangle // there is no way to modify the diagonal now, in the case // where no translation option covers a single-word span, // we leave the +inf in the matrix // like in chart parsing we want each cell to contain the highest score // of the full-span trOpt or the sum of scores of joining two smaller spans for(size_t colstart = 1; colstart < size ; colstart++) { for(size_t diagshift = 0; diagshift < size-colstart ; diagshift++) { size_t sPos = diagshift; size_t ePos = colstart+diagshift; for(size_t joinAt = sPos; joinAt < ePos ; joinAt++) { float joinedScore = m_estimatedScores->GetScore(sPos, joinAt) + m_estimatedScores->GetScore(joinAt+1, ePos); // uncomment to see the cell filling scheme // TRACE_ERR("[" << sPos << "," << ePos << "] <-? [" // << sPos << "," << joinAt << "]+[" // << joinAt+1 << "," << ePos << "] (colstart: " // << colstart << ", diagshift: " << diagshift << ")" // << endl); if (joinedScore > m_estimatedScores->GetScore(sPos, ePos)) m_estimatedScores->SetScore(sPos, ePos, joinedScore); } } } //cerr << "Square matrix:" << endl; //cerr << *m_estimatedScores << endl; } void Manager::OutputBest() const { stringstream out; const Hypothesis *bestHypo = m_search->GetBestHypothesis(); if (bestHypo) { if (system.outputHypoScore) { out << bestHypo->GetScores().GetTotalScore() << " "; } bestHypo->OutputToStream(out); //cerr << "BEST TRANSLATION: " << *bestHypo; } else { if (system.outputHypoScore) { out << "0 "; } //cerr << "NO TRANSLATION"; } out << "\n"; system.bestCollector.Write(m_input->GetTranslationId(), out.str()); //cerr << endl; } } <commit_msg>output warning if no translation<commit_after>/* * Manager.cpp * * Created on: 23 Oct 2015 * Author: hieu */ #include <boost/foreach.hpp> #include <vector> #include <sstream> #include "Manager.h" #include "SearchNormal.h" #include "SearchNormalBatch.h" #include "CubePruning/Search.h" #include "../System.h" #include "../TargetPhrases.h" #include "../TargetPhrase.h" #include "../InputPaths.h" #include "../InputPath.h" #include "../Sentence.h" #include "../TranslationModel/PhraseTable.h" #include "../legacy/Range.h" using namespace std; namespace Moses2 { Manager::Manager(System &sys, const TranslationTask &task, const std::string &inputStr, long translationId) :system(sys) ,task(task) ,m_inputStr(inputStr) ,m_translationId(translationId) {} Manager::~Manager() { delete m_search; delete m_estimatedScores; GetPool().Reset(); GetHypoRecycle().Reset(); } void Manager::Init() { // init pools etc m_pool = &system.GetManagerPool(); m_hypoRecycle = &system.GetHypoRecycler(); m_initPhrase = new (GetPool().Allocate<TargetPhrase>()) TargetPhrase(GetPool(), system, 0); // create input phrase obj FactorCollection &vocab = system.GetVocab(); m_input = Sentence::CreateFromString(GetPool(), vocab, system, m_inputStr, m_translationId); m_inputPaths.Init(*m_input, system); const std::vector<const PhraseTable*> &pts = system.mappings; for (size_t i = 0; i < pts.size(); ++i) { const PhraseTable &pt = *pts[i]; //cerr << "Looking up from " << pt.GetName() << endl; pt.Lookup(*this, m_inputPaths); } //m_inputPaths.DeleteUnusedPaths(); CalcFutureScore(); m_bitmaps.Init(m_input->GetSize(), vector<bool>(0)); switch (system.searchAlgorithm) { case Normal: m_search = new SearchNormal(*this); break; case NormalBatch: m_search = new SearchNormalBatch(*this); break; case CubePruning: m_search = new NSCubePruning::Search(*this); break; default: cerr << "Unknown search algorithm" << endl; abort(); } } void Manager::Decode() { Init(); m_search->Decode(); OutputBest(); } void Manager::CalcFutureScore() { size_t size = m_input->GetSize(); m_estimatedScores = new SquareMatrix(size); m_estimatedScores->InitTriangle(-numeric_limits<SCORE>::infinity()); // walk all the translation options and record the cheapest option for each span BOOST_FOREACH(const InputPath &path, m_inputPaths) { const Range &range = path.range; const std::vector<const TargetPhrases*> &allTps = path.targetPhrases; SCORE bestScore = -numeric_limits<SCORE>::infinity(); BOOST_FOREACH(const TargetPhrases *tps, allTps) { if (tps) { BOOST_FOREACH(const TargetPhrase *tp, *tps) { SCORE score = tp->GetFutureScore(); if (score > bestScore) { bestScore = score; } } } } m_estimatedScores->SetScore(range.GetStartPos(), range.GetEndPos(), bestScore); } // now fill all the cells in the strictly upper triangle // there is no way to modify the diagonal now, in the case // where no translation option covers a single-word span, // we leave the +inf in the matrix // like in chart parsing we want each cell to contain the highest score // of the full-span trOpt or the sum of scores of joining two smaller spans for(size_t colstart = 1; colstart < size ; colstart++) { for(size_t diagshift = 0; diagshift < size-colstart ; diagshift++) { size_t sPos = diagshift; size_t ePos = colstart+diagshift; for(size_t joinAt = sPos; joinAt < ePos ; joinAt++) { float joinedScore = m_estimatedScores->GetScore(sPos, joinAt) + m_estimatedScores->GetScore(joinAt+1, ePos); // uncomment to see the cell filling scheme // TRACE_ERR("[" << sPos << "," << ePos << "] <-? [" // << sPos << "," << joinAt << "]+[" // << joinAt+1 << "," << ePos << "] (colstart: " // << colstart << ", diagshift: " << diagshift << ")" // << endl); if (joinedScore > m_estimatedScores->GetScore(sPos, ePos)) m_estimatedScores->SetScore(sPos, ePos, joinedScore); } } } //cerr << "Square matrix:" << endl; //cerr << *m_estimatedScores << endl; } void Manager::OutputBest() const { stringstream out; const Hypothesis *bestHypo = m_search->GetBestHypothesis(); if (bestHypo) { if (system.outputHypoScore) { out << bestHypo->GetScores().GetTotalScore() << " "; } bestHypo->OutputToStream(out); //cerr << "BEST TRANSLATION: " << *bestHypo; } else { if (system.outputHypoScore) { out << "0 "; } cerr << "NO TRANSLATION " << m_input->GetTranslationId() << endl; } out << "\n"; system.bestCollector.Write(m_input->GetTranslationId(), out.str()); //cerr << endl; } } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com> ** ** This file is part of duicontrolpanel. ** ** ** This program is free software { } you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QObject> #include <QGraphicsSceneMouseEvent> #include <category.h> #include <memorycategory.h> #include <filecategory.h> #include "ut_category.h" void Ut_Category::init() { QStringList compIds; compIds << "CompId1" << "CompId2" << "Uncategorized"; memCat = new MemoryCategory ("Name", "TitleId", "ParentId", "SubtitleId", "Subtitle", "IconId", 1, compIds ); invalidMemCat = new MemoryCategory (""); fileCat = new FileCategory ("xxx"); } void Ut_Category::cleanup() { delete memCat; delete fileCat; delete invalidMemCat; } void Ut_Category::initTestCase() { } void Ut_Category::cleanupTestCase() { } void Ut_Category::testConstructor() { } void Ut_Category::testParentId() { QCOMPARE (memCat->parentId(), QString("ParentId")); QCOMPARE (invalidMemCat->parentId(), QString("")); QCOMPARE (fileCat->parentId(), QString()); } void Ut_Category::testName() { // name QCOMPARE (memCat->name(), QString("Name")); QCOMPARE (invalidMemCat->name(), QString("")); QCOMPARE (fileCat->name(), QString()); } void Ut_Category::testTitle() { // title QCOMPARE (memCat->title(), QString("!! Name")); QCOMPARE (invalidMemCat->title(), QString("!! ")); QCOMPARE (fileCat->title(), QString("!! ")); // titleId QCOMPARE (memCat->titleId(), QString("TitleId")); QCOMPARE (invalidMemCat->titleId(), QString()); QCOMPARE (fileCat->titleId(), QString()); } void Ut_Category::testSubtitle() { // title QCOMPARE (memCat->subtitle(), QString("!! Subtitle")); QCOMPARE (invalidMemCat->subtitle(), QString("!! ")); QCOMPARE (fileCat->subtitle(), QString("!! ")); // subtitleId QCOMPARE (memCat->subtitleId(), QString("SubtitleId")); QCOMPARE (invalidMemCat->subtitleId(), QString()); QCOMPARE (fileCat->subtitleId(), QString()); } void Ut_Category::testIcon() { QCOMPARE (memCat->iconId(), QString("IconId")); QCOMPARE (invalidMemCat->iconId(), QString()); QCOMPARE (fileCat->iconId(), QString()); } void Ut_Category::testOrder() { QCOMPARE (memCat->order(), 1); // if order is unspecified, the category must be put last: QCOMPARE (invalidMemCat->order(), 0); QCOMPARE (fileCat->order(), 999999); // orderlessthen QVERIFY (!Category::orderLessThan(memCat, invalidMemCat)); QVERIFY (Category::orderLessThan(memCat, fileCat)); QVERIFY (!Category::orderLessThan(memCat, memCat)); } void Ut_Category::testReferenceIds() { QStringList result; result << "TitleId" << "Name" << "CompId1" << "CompId2" << "Uncategorized"; QCOMPARE (memCat->referenceIds(), result); } void Ut_Category::testIdMatch() { QVERIFY (memCat->idMatch ("TitleId")); QVERIFY (memCat->idMatch ("CompId2")); QVERIFY (memCat->idMatch ("Name")); QVERIFY (!memCat->idMatch ("!! Name")); QVERIFY (!memCat->idMatch ("CompId1x")); } void Ut_Category::testIsValid() { QVERIFY (memCat->isValid()); QVERIFY (!invalidMemCat->isValid()); QVERIFY (!fileCat->isValid()); } void Ut_Category::testChildren() { MemoryCategory cat1 ("test1"); MemoryCategory cat2 ("test2"); // the children has to be sorted by order cat1.addChild (fileCat); cat1.addChild (invalidMemCat); cat1.addChild (memCat); QCOMPARE (cat1.children().count(), 3); QCOMPARE (cat1.children().at(0), invalidMemCat); // has 0 order QCOMPARE (cat1.children().at(1), memCat); // has 1 order QCOMPARE (cat1.children().at(2), fileCat); // has 9999999 // try it with another sequence cat2.addChild (invalidMemCat); cat2.addChild (memCat); cat2.addChild (fileCat); QCOMPARE (cat2.children().count(), 3); QCOMPARE (cat2.children().at(0), invalidMemCat); // has 0 order QCOMPARE (cat2.children().at(1), memCat); // has 1 order QCOMPARE (cat2.children().at(2), fileCat); // has 9999999 } void Ut_Category::testContainsUncategorized() { QVERIFY (memCat->containsUncategorized()); QVERIFY (!invalidMemCat->containsUncategorized()); QVERIFY (!fileCat->containsUncategorized()); } QTEST_APPLESS_MAIN(Ut_Category) <commit_msg>Fixes a unittest in ut_category<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com> ** ** This file is part of duicontrolpanel. ** ** ** This program is free software { } you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QObject> #include <QGraphicsSceneMouseEvent> #include <category.h> #include <memorycategory.h> #include <filecategory.h> #include "ut_category.h" void Ut_Category::init() { QStringList compIds; compIds << "CompId1" << "CompId2" << "Uncategorized"; memCat = new MemoryCategory ("Name", "TitleId", "ParentId", "SubtitleId", "Subtitle", "IconId", 1, compIds ); invalidMemCat = new MemoryCategory (""); fileCat = new FileCategory ("xxx"); } void Ut_Category::cleanup() { delete memCat; delete fileCat; delete invalidMemCat; } void Ut_Category::initTestCase() { } void Ut_Category::cleanupTestCase() { } void Ut_Category::testConstructor() { } void Ut_Category::testParentId() { QCOMPARE (memCat->parentId(), QString("ParentId")); QCOMPARE (invalidMemCat->parentId(), QString("")); QCOMPARE (fileCat->parentId(), QString()); } void Ut_Category::testName() { // name QCOMPARE (memCat->name(), QString("Name")); QCOMPARE (invalidMemCat->name(), QString("")); QCOMPARE (fileCat->name(), QString()); } void Ut_Category::testTitle() { // title QCOMPARE (memCat->title(), QString("!! Name")); QCOMPARE (invalidMemCat->title(), QString("!! ")); QCOMPARE (fileCat->title(), QString("!! ")); // titleId QCOMPARE (memCat->titleId(), QString("TitleId")); QCOMPARE (invalidMemCat->titleId(), QString()); QCOMPARE (fileCat->titleId(), QString()); } void Ut_Category::testSubtitle() { // title QCOMPARE (memCat->subtitle(), QString("!! Subtitle")); QCOMPARE (invalidMemCat->subtitle(), QString("")); QCOMPARE (fileCat->subtitle(), QString("")); // subtitleId QCOMPARE (memCat->subtitleId(), QString("SubtitleId")); QCOMPARE (invalidMemCat->subtitleId(), QString()); QCOMPARE (fileCat->subtitleId(), QString()); } void Ut_Category::testIcon() { QCOMPARE (memCat->iconId(), QString("IconId")); QCOMPARE (invalidMemCat->iconId(), QString()); QCOMPARE (fileCat->iconId(), QString()); } void Ut_Category::testOrder() { QCOMPARE (memCat->order(), 1); // if order is unspecified, the category must be put last: QCOMPARE (invalidMemCat->order(), 0); QCOMPARE (fileCat->order(), 999999); // orderlessthen QVERIFY (!Category::orderLessThan(memCat, invalidMemCat)); QVERIFY (Category::orderLessThan(memCat, fileCat)); QVERIFY (!Category::orderLessThan(memCat, memCat)); } void Ut_Category::testReferenceIds() { QStringList result; result << "TitleId" << "Name" << "CompId1" << "CompId2" << "Uncategorized"; QCOMPARE (memCat->referenceIds(), result); } void Ut_Category::testIdMatch() { QVERIFY (memCat->idMatch ("TitleId")); QVERIFY (memCat->idMatch ("CompId2")); QVERIFY (memCat->idMatch ("Name")); QVERIFY (!memCat->idMatch ("!! Name")); QVERIFY (!memCat->idMatch ("CompId1x")); } void Ut_Category::testIsValid() { QVERIFY (memCat->isValid()); QVERIFY (!invalidMemCat->isValid()); QVERIFY (!fileCat->isValid()); } void Ut_Category::testChildren() { MemoryCategory cat1 ("test1"); MemoryCategory cat2 ("test2"); // the children has to be sorted by order cat1.addChild (fileCat); cat1.addChild (invalidMemCat); cat1.addChild (memCat); QCOMPARE (cat1.children().count(), 3); QCOMPARE (cat1.children().at(0), invalidMemCat); // has 0 order QCOMPARE (cat1.children().at(1), memCat); // has 1 order QCOMPARE (cat1.children().at(2), fileCat); // has 9999999 // try it with another sequence cat2.addChild (invalidMemCat); cat2.addChild (memCat); cat2.addChild (fileCat); QCOMPARE (cat2.children().count(), 3); QCOMPARE (cat2.children().at(0), invalidMemCat); // has 0 order QCOMPARE (cat2.children().at(1), memCat); // has 1 order QCOMPARE (cat2.children().at(2), fileCat); // has 9999999 } void Ut_Category::testContainsUncategorized() { QVERIFY (memCat->containsUncategorized()); QVERIFY (!invalidMemCat->containsUncategorized()); QVERIFY (!fileCat->containsUncategorized()); } QTEST_APPLESS_MAIN(Ut_Category) <|endoftext|>
<commit_before>/** * @copyright Copyright 2018 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetParamManager.cpp */ #include "./JPetParamGetterAscii/JPetParamGetterAscii.h" #include "./JPetOptionsTools/JPetOptionsTools.h" #include <boost/property_tree/xml_parser.hpp> #include "JPetParamManager.h" #include <TFile.h> std::shared_ptr<JPetParamManager> JPetParamManager::generateParamManager( const std::map<std::string, boost::any>& options) { using namespace jpet_options_tools; if (isLocalDB(options)) { std::set<ParamObjectType> expectMissing; if (FileTypeChecker::getInputFileType(options) == FileTypeChecker::kScope) { expectMissing.insert(ParamObjectType::kTRB); expectMissing.insert(ParamObjectType::kFEB); expectMissing.insert(ParamObjectType::kFrame); expectMissing.insert(ParamObjectType::kLayer); expectMissing.insert(ParamObjectType::kTOMBChannel); } return std::make_shared<JPetParamManager>(new JPetParamGetterAscii(getLocalDB(options)), expectMissing); } else { ERROR("No local database file found."); return std::make_shared<JPetParamManager>(); } } JPetParamManager::~JPetParamManager() { if (fBank) { delete fBank; fBank = 0; } if (fParamGetter) { delete fParamGetter; fParamGetter = 0; } } std::map<int, JPetTRB*>& JPetParamManager::getTRBs(const int runId) { return getTRBFactory(runId).getTRBs(); } JPetTRBFactory& JPetParamManager::getTRBFactory(const int runId) { if (fTRBFactories.count(runId) == 0) { fTRBFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId)); } return fTRBFactories.at(runId); } std::map<int, JPetFEB*>& JPetParamManager::getFEBs(const int runId) { return getFEBFactory(runId).getFEBs(); } JPetFEBFactory& JPetParamManager::getFEBFactory(const int runId) { if (fFEBFactories.count(runId) == 0) { fFEBFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getTRBFactory(runId))); } return fFEBFactories.at(runId); } std::map<int, JPetFrame*>& JPetParamManager::getFrames(const int runId) { return getFrameFactory(runId).getFrames(); } JPetFrameFactory& JPetParamManager::getFrameFactory(const int runId) { if (fFrameFactories.count(runId) == 0) { fFrameFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId)); } return fFrameFactories.at(runId); } std::map<int, JPetLayer*>& JPetParamManager::getLayers(const int runId) { return getLayerFactory(runId).getLayers(); } JPetLayerFactory& JPetParamManager::getLayerFactory(const int runId) { if (fLayerFactories.count(runId) == 0) { fLayerFactories.emplace( std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getFrameFactory(runId)) ); } return fLayerFactories.at(runId); } std::map<int, JPetBarrelSlot*>& JPetParamManager::getBarrelSlots(const int runId) { return getBarrelSlotFactory(runId).getBarrelSlots(); } JPetBarrelSlotFactory& JPetParamManager::getBarrelSlotFactory(const int runId) { if (fBarrelSlotFactories.count(runId) == 0) { fBarrelSlotFactories.emplace( std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getLayerFactory(runId)) ); } fBarrelSlotFactories.at(runId); return fBarrelSlotFactories.at(runId); } std::map<int, JPetScin*>& JPetParamManager::getScins(const int runId) { return getScinFactory(runId).getScins(); } JPetScinFactory& JPetParamManager::getScinFactory(const int runId) { if (fScinFactories.count(runId) == 0) { fScinFactories.emplace( std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getBarrelSlotFactory(runId)) ); } return fScinFactories.at(runId); } std::map<int, JPetPM*>& JPetParamManager::getPMs(const int runId) { return getPMFactory(runId).getPMs(); } JPetPMFactory& JPetParamManager::getPMFactory(const int runId) { if (fPMFactories.count(runId) == 0) { fPMFactories.emplace( std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple( *fParamGetter, runId, getFEBFactory(runId), getScinFactory(runId), getBarrelSlotFactory(runId) ) ); } return fPMFactories.at(runId); } std::map<int, JPetTOMBChannel*>& JPetParamManager::getTOMBChannels(const int runId) { return getTOMBChannelFactory(runId).getTOMBChannels(); } JPetTOMBChannelFactory& JPetParamManager::getTOMBChannelFactory(const int runId) { if (fTOMBChannelFactories.count(runId) == 0) { fTOMBChannelFactories.emplace( std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple( *fParamGetter, runId, getFEBFactory(runId), getTRBFactory(runId), getPMFactory(runId) ) ); } return fTOMBChannelFactories.at(runId); } void JPetParamManager::fillParameterBank(const int run) { if (fBank) { delete fBank; fBank = 0; } fBank = new JPetParamBank(); if (!fExpectMissing.count(ParamObjectType::kTRB)) { for (auto& trbp : getTRBs(run)) { auto& trb = *trbp.second; fBank->addTRB(trb); } } if (!fExpectMissing.count(ParamObjectType::kFEB)) { for (auto& febp : getFEBs(run)) { auto& feb = *febp.second; fBank->addFEB(feb); fBank->getFEB(feb.getID()).setTRB(fBank->getTRB(feb.getTRB().getID())); } } if (!fExpectMissing.count(ParamObjectType::kFrame)) { for (auto& framep : getFrames(run)) { auto& frame = *framep.second; fBank->addFrame(frame); } } if (!fExpectMissing.count(ParamObjectType::kLayer)) { for (auto& layerp : getLayers(run)) { auto& layer = *layerp.second; fBank->addLayer(layer); fBank->getLayer(layer.getID()).setFrame(fBank->getFrame(layer.getFrame().getID())); } } if (!fExpectMissing.count(ParamObjectType::kBarrelSlot)) { for (auto& barrelSlotp : getBarrelSlots(run)) { auto& barrelSlot = *barrelSlotp.second; fBank->addBarrelSlot(barrelSlot); if (barrelSlot.hasLayer()) { fBank->getBarrelSlot(barrelSlot.getID()).setLayer(fBank->getLayer(barrelSlot.getLayer().getID())); } } } if (!fExpectMissing.count(ParamObjectType::kScintillator)) { for (auto& scinp : getScins(run)) { auto& scin = *scinp.second; fBank->addScintillator(scin); fBank->getScintillator(scin.getID()).setBarrelSlot( fBank->getBarrelSlot(scin.getBarrelSlot().getID()) ); } } if (!fExpectMissing.count(ParamObjectType::kPM)) { for (auto& pmp : getPMs(run)) { auto& pm = *pmp.second; fBank->addPM(pm); if (pm.hasFEB()) { fBank->getPM(pm.getID()).setFEB(fBank->getFEB(pm.getFEB().getID())); } fBank->getPM(pm.getID()).setScin(fBank->getScintillator(pm.getScin().getID())); fBank->getPM(pm.getID()).setBarrelSlot( fBank->getBarrelSlot(pm.getBarrelSlot().getID()) ); } } if (!fExpectMissing.count(ParamObjectType::kTOMBChannel)) { for (auto& tombChannelp : getTOMBChannels(run)) { auto& tombChannel = *tombChannelp.second; fBank->addTOMBChannel(tombChannel); fBank->getTOMBChannel(tombChannel.getChannel()).setFEB( fBank->getFEB(tombChannel.getFEB().getID()) ); fBank->getTOMBChannel(tombChannel.getChannel()).setTRB( fBank->getTRB(tombChannel.getTRB().getID()) ); fBank->getTOMBChannel(tombChannel.getChannel()).setPM( fBank->getPM(tombChannel.getPM().getID()) ); } } } bool JPetParamManager::readParametersFromFile(JPetReader* reader) { assert(reader); if (!reader->isOpen()) { ERROR("Cannot read parameters from file. The provided JPetReader is closed."); return false; } fBank = static_cast<JPetParamBank*>(reader->getObjectFromFile("ParamBank")); if (!fBank) return false; return true; } bool JPetParamManager::saveParametersToFile(JPetWriter* writer) { assert(writer); if (!writer->isOpen()) { ERROR("Could not write parameters to file. The provided JPetWriter is closed."); return false; } writer->writeObject(fBank, "ParamBank"); return true; } bool JPetParamManager::readParametersFromFile(std::string filename) { TFile file(filename.c_str(), "READ"); if (!file.IsOpen()) { ERROR("Could not read from file."); return false; } fBank = static_cast<JPetParamBank*>(file.Get("ParamBank")); if (!fBank) return false; return true; } const JPetParamBank& JPetParamManager::getParamBank() const { DEBUG("getParamBank() from JPetParamManager"); static JPetParamBank DummyResult(true); if (fBank) return *fBank; else return DummyResult; } bool JPetParamManager::saveParametersToFile(std::string filename) { TFile file(filename.c_str(), "UPDATE"); if (!file.IsOpen()) { ERROR("Could not write to file."); return false; } file.cd(); assert(fBank); file.WriteObject(fBank, "ParamBank;1"); return true; } void JPetParamManager::clearParameters() { assert(fBank); fBank->clear(); } void JPetParamManager::createXMLFile(const std::string& channelDataFileName, int channelOffset, int numberOfChannels) { using boost::property_tree::ptree; ptree pt; std::string debug = "OFF"; std::string dataSourceType = "TRB3_S"; std::string dataSourceTrbNetAddress = "8000"; std::string dataSourceHubAddress = "8000"; std::string dataSourceReferenceChannel = "0"; std::string dataSourceCorrectionFile = "raw"; pt.put("READOUT.DEBUG", debug); pt.put("READOUT.DATA_SOURCE.TYPE", dataSourceType); pt.put("READOUT.DATA_SOURCE.TRBNET_ADDRESS", dataSourceTrbNetAddress); pt.put("READOUT.DATA_SOURCE.HUB_ADDRESS", dataSourceHubAddress); pt.put("READOUT.DATA_SOURCE.REFERENCE_CHANNEL", dataSourceReferenceChannel); pt.put("READOUT.DATA_SOURCE.CORRECTION_FILE", dataSourceCorrectionFile); ptree& externalNode = pt.add("READOUT.DATA_SOURCE.MODULES", ""); ptree& internalNode = externalNode.add("MODULE", ""); internalNode.put("TYPE", "LATTICE_TDC"); internalNode.put("TRBNET_ADDRESS", "e000"); internalNode.put("NUMBER_OF_CHANNELS", numberOfChannels); internalNode.put("CHANNEL_OFFSET", channelOffset); internalNode.put("RESOLUTION", "100"); internalNode.put("MEASUREMENT_TYPE", "TDC"); write_xml(channelDataFileName, pt); } void JPetParamManager::getTOMBDataAndCreateXMLFile(const int p_run_id) { fillParameterBank(p_run_id); int TOMBChannelsSize = fBank->getTOMBChannelsSize(); int channelOffset = 0; int numberOfChannels = 0; if (TOMBChannelsSize) { for (int i = 0; i < TOMBChannelsSize; ++i) { if (i == 0) { std::string description = fBank->getTOMBChannel(i).getDescription(); channelOffset = JPetParamGetter::getTOMBChannelFromDescription(description); } ++numberOfChannels; } createXMLFile("conf.xml", channelOffset, numberOfChannels); return; } ERROR("TOMBChannelsSize is equal to zero."); } <commit_msg>Revert changing JPetManager<commit_after>/** * @copyright Copyright 2018 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetManager.cpp */ #include "./JPetGeantParser/JPetGeantParser.h" #include "./JPetManager.h" #include <cassert> #include <string> #include <exception> #include <TThread.h> #include "./JPetTaskChainExecutor/JPetTaskChainExecutor.h" #include "./JPetCommonTools/JPetCommonTools.h" #include "./JPetCmdParser/JPetCmdParser.h" #include "./JPetOptionsGenerator/JPetOptionsGenerator.h" #include "./GeantParser/JPetGeantParser/JPetGeantParser.h" #include "./JPetLoggerInclude.h" using namespace jpet_options_tools; JPetManager::JPetManager() { } JPetManager& JPetManager::getManager() { static JPetManager instance; return instance; } void JPetManager::run(int argc, const char** argv) { bool isOk = true; std::map<std::string, boost::any> allValidatedOptions; std::tie(isOk, allValidatedOptions) = parseCmdLine(argc, argv); if (!isOk) { ERROR("While parsing command line arguments"); std::cerr << "Error has occurred while parsing command line! Check the log!" << std::endl; throw std::invalid_argument("Error in parsing command line arguments"); /// temporary change to check if the examples are working } registerDefaultTasks(); auto chainOfTasks = fTaskFactory.createTaskGeneratorChain(allValidatedOptions); JPetOptionsGenerator optionsGenerator; auto options = optionsGenerator.generateOptionsForTasks(allValidatedOptions, chainOfTasks.size()); INFO( "======== Starting processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" ); std::vector<TThread*> threads; auto inputDataSeq = 0; /// For every input option, new TaskChainExecutor is created, which creates the chain of previously /// registered tasks. The inputDataSeq is the identifier of given chain. for (auto opt : options) { auto executor = jpet_common_tools::make_unique<JPetTaskChainExecutor>(chainOfTasks, inputDataSeq, opt.second); if (areThreadsEnabled()) { auto thr = executor->run(); if (thr) { threads.push_back(thr); } else { ERROR("thread pointer is null"); } } else { if (!executor->process()) { ERROR("While running process"); std::cerr << "Stopping program, error has occurred while calling executor->process! Check the log!" << std::endl; throw std::runtime_error("Error in executor->process"); } } inputDataSeq++; } if (areThreadsEnabled()) { for (auto thread : threads) { assert(thread); thread->Join(); } } INFO( "======== Finished processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" ); } std::pair<bool, std::map<std::string, boost::any> > JPetManager::parseCmdLine(int argc, const char** argv) { std::map<std::string, boost::any> allValidatedOptions; try { JPetOptionsGenerator optionsGenerator; JPetCmdParser parser; auto optionsFromCmdLine = parser.parseCmdLineArgs(argc, argv); allValidatedOptions = optionsGenerator.generateAndValidateOptions(optionsFromCmdLine); } catch (std::exception& e) { ERROR(e.what()); return std::make_pair(false, std::map<std::string, boost::any> {}); } return std::make_pair(true, allValidatedOptions); } void JPetManager::useTask(const std::string& name, const std::string& inputFileType, const std::string& outputFileType, int numTimes) { if (!fTaskFactory.addTaskInfo(name, inputFileType, outputFileType, numTimes)) { std::cerr << "Error has occurred while calling useTask! Check the log!" << std::endl; throw std::runtime_error("error in addTaskInfo"); } } bool JPetManager::areThreadsEnabled() const { return fThreadsEnabled; } void JPetManager::setThreadsEnabled(bool enable) { fThreadsEnabled = enable; } /// @brief Adds any built-in tasks based on JPetTaskIO to the map of taska generators to facilitate their later generation on demand /// /// Any built-in tasks which are handled by JPetTaskIO the same way as user-defined tasks (rather than using a dedicated task wrapper as is the case for JPetUnzipAndUpackTask or JPetParamBankHandlerTask) can be easily added to the chain of tasks using the same mehanics as exposed to the user for adding users' tasks prvided that the built-in tasks are registered in the map of tasks generators in advance. This provate method is intended to register all such tasks in advance of creation of the task generator chain. void JPetManager::registerDefaultTasks() { registerTask<JPetGeantParser>("JPetGeantParser"); } <|endoftext|>
<commit_before><commit_msg>Planning : update eval_jac_g in open space planner<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL #define SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL #include <sofa/core/behavior/ForceField.inl> #include "RestShapeSpringsForceField.h" #include <sofa/helper/system/config.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/defaulttype/RigidTypes.h> #include <sofa/helper/gl/template.h> #include <assert.h> #include <iostream> namespace sofa { namespace component { namespace forcefield { template<class DataTypes> RestShapeSpringsForceField<DataTypes>::RestShapeSpringsForceField() : points(initData(&points, "points", "points controlled by the rest shape springs")) , stiffness(initData(&stiffness, "stiffness", "stiffness values between the actual position and the rest shape position")) , angularStiffness(initData(&angularStiffness, "angularStiffness", "angularStiffness assigned when controlling the rotation of the points")) , external_rest_shape(initData(&external_rest_shape, "external_rest_shape", "rest_shape can be defined by the position of an external Mechanical State")) , external_points(initData(&external_points, "external_points", "points from the external Mechancial State that define the rest shape springs")) , recompute_indices(initData(&recompute_indices, false, "recompute_indices", "Recompute indices (should be false for BBOX)")) , restMState(NULL) // , pp_0(NULL) { } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::init() { core::behavior::ForceField<DataTypes>::init(); if (stiffness.getValue().empty()) { std::cout << "RestShapeSpringsForceField : No stiffness is defined, assuming equal stiffness on each node, k = 100.0 " << std::endl; VecReal stiffs; stiffs.push_back(100.0); stiffness.setValue(stiffs); } const std::string path = external_rest_shape.getValue(); restMState = NULL; if (path.size() > 0) { this->getContext()->get(restMState ,path); } if (!restMState) { useRestMState = false; if (path.size() > 0) { std::cout << "RestShapeSpringsForceField : " << external_rest_shape.getValue() << "not found\n"; } } else { useRestMState = true; // std::cout << "RestShapeSpringsForceField : Mechanical state named " << restMState->getName() << " found for RestShapeSpringFF named " << this->getName() << std::endl; } this->k = stiffness.getValue(); recomputeIndices(); } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::recomputeIndices() { m_indices.clear(); m_ext_indices.clear(); for (unsigned int i = 0; i < points.getValue().size(); i++) m_indices.push_back(points.getValue()[i]); for (unsigned int i = 0; i < external_points.getValue().size(); i++) m_ext_indices.push_back(external_points.getValue()[i]); if (m_indices.size()==0) { // std::cout << "in RestShapeSpringsForceField no point are defined, default case: points = all points " << std::endl; for (unsigned int i = 0; i < (unsigned)this->mstate->getSize(); i++) { m_indices.push_back(i); } } if (m_ext_indices.size()==0) { // std::cout << "in RestShapeSpringsForceField no external_points are defined, default case: points = all points " << std::endl; if (useRestMState) { for (unsigned int i = 0; i < (unsigned)restMState->getSize(); i++) { m_ext_indices.push_back(i); } } else { for (unsigned int i = 0; i < (unsigned)this->mstate->getSize(); i++) { m_ext_indices.push_back(i); } } } if (m_indices.size() > m_ext_indices.size()) { std::cerr << "Error : the dimention of the source and the targeted points are different " << std::endl; m_indices.clear(); } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addForce(const core::MechanicalParams* /* mparams */ /* PARAMS FIRST */, DataVecDeriv& f, const DataVecCoord& x, const DataVecDeriv& /* v */) { sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > f1 = f; sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p1 = x; sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p0 = *(useRestMState ? restMState->read(core::VecCoordId::position()) : this->mstate->read(core::VecCoordId::restPosition())); f1.resize(p1.size()); if (recompute_indices.getValue()) { recomputeIndices(); } Springs_dir.resize(m_indices.size() ); if ( k.size()!= m_indices.size() ) { //sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl; for (unsigned int i=0; i<m_indices.size(); i++) { const unsigned int index = m_indices[i]; const unsigned int ext_index = m_ext_indices[i]; Deriv dx = p1[index] - p0[ext_index]; Springs_dir[i] = p1[index] - p0[ext_index]; Springs_dir[i].normalize(); f1[index] -= dx * k[0] ; // if (dx.norm()>0.00000001) // std::cout<<"force on point "<<index<<std::endl; // Deriv dx = p[i] - p_0[i]; // f[ indices[i] ] -= dx * k[0] ; } } else { for (unsigned int i=0; i<m_indices.size(); i++) { const unsigned int index = m_indices[i]; const unsigned int ext_index = m_ext_indices[i]; Deriv dx = p1[index] - p0[ext_index]; Springs_dir[i] = p1[index] - p0[ext_index]; Springs_dir[i].normalize(); f1[index] -= dx * k[index] ; // if (dx.norm()>0.00000001) // std::cout<<"force on point "<<index<<std::endl; // Deriv dx = p[i] - p_0[i]; // f[ indices[i] ] -= dx * k[i] ; } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addDForce(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& df, const DataVecDeriv& dx) { // remove to be able to build in parallel // const VecIndex& indices = points.getValue(); // const VecReal& k = stiffness.getValue(); sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > df1 = df; sofa::helper::ReadAccessor< core::objectmodel::Data< VecDeriv > > dx1 = dx; double kFactor = mparams->kFactor(); if (k.size()!= m_indices.size() ) { sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl; for (unsigned int i=0; i<m_indices.size(); i++) { df1[m_indices[i]] -= dx1[m_indices[i]] * k[0] * kFactor; } } else { for (unsigned int i=0; i<m_indices.size(); i++) { df1[m_indices[i]] -= dx1[m_indices[i]] * k[m_indices[i]] * kFactor ; } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addKToMatrix(const core::MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix ) { // remove to be able to build in parallel // const VecIndex& indices = points.getValue(); // const VecReal& k = stiffness.getValue(); sofa::core::behavior::MultiMatrixAccessor::MatrixRef mref = matrix->getMatrix(this->mstate); sofa::defaulttype::BaseMatrix* mat = mref.matrix; unsigned int offset = mref.offset; double kFact = mparams->kFactor(); const int N = Coord::total_size; unsigned int curIndex = 0; if (k.size()!= m_indices.size() ) { for (unsigned int index = 0; index < m_indices.size(); index++) { curIndex = m_indices[index]; for(int i = 0; i < N; i++) { // for (unsigned int j = 0; j < N; j++) // { // mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[0]); // } mat->add(offset + N * curIndex + i, offset + N * curIndex + i, -kFact * k[0]); } } } else { for (unsigned int index = 0; index < m_indices.size(); index++) { curIndex = m_indices[index]; for(int i = 0; i < N; i++) { // for (unsigned int j = 0; j < N; j++) // { // mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[curIndex]); // } mat->add(offset + N * curIndex + i, offset + N * curIndex + i, -kFact * k[curIndex]); } } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::draw(const core::visual::VisualParams* ) { } template <class DataTypes> bool RestShapeSpringsForceField<DataTypes>::addBBox(double*, double* ) { return false; } } // namespace forcefield } // namespace component } // namespace sofa #endif // SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL <commit_msg>r10856/sofa-dev : Bug fix with vec1d and Vec3d<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL #define SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL #include <sofa/core/behavior/ForceField.inl> #include "RestShapeSpringsForceField.h" #include <sofa/helper/system/config.h> #include <sofa/defaulttype/VecTypes.h> #include <sofa/defaulttype/RigidTypes.h> #include <sofa/helper/gl/template.h> #include <assert.h> #include <iostream> namespace sofa { namespace component { namespace forcefield { template<class DataTypes> RestShapeSpringsForceField<DataTypes>::RestShapeSpringsForceField() : points(initData(&points, "points", "points controlled by the rest shape springs")) , stiffness(initData(&stiffness, "stiffness", "stiffness values between the actual position and the rest shape position")) , angularStiffness(initData(&angularStiffness, "angularStiffness", "angularStiffness assigned when controlling the rotation of the points")) , external_rest_shape(initData(&external_rest_shape, "external_rest_shape", "rest_shape can be defined by the position of an external Mechanical State")) , external_points(initData(&external_points, "external_points", "points from the external Mechancial State that define the rest shape springs")) , recompute_indices(initData(&recompute_indices, false, "recompute_indices", "Recompute indices (should be false for BBOX)")) , restMState(NULL) // , pp_0(NULL) { } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::init() { core::behavior::ForceField<DataTypes>::init(); if (stiffness.getValue().empty()) { std::cout << "RestShapeSpringsForceField : No stiffness is defined, assuming equal stiffness on each node, k = 100.0 " << std::endl; VecReal stiffs; stiffs.push_back(100.0); stiffness.setValue(stiffs); } const std::string path = external_rest_shape.getValue(); restMState = NULL; if (path.size() > 0) { this->getContext()->get(restMState ,path); } if (!restMState) { useRestMState = false; if (path.size() > 0) { std::cout << "RestShapeSpringsForceField : " << external_rest_shape.getValue() << "not found\n"; } } else { useRestMState = true; // std::cout << "RestShapeSpringsForceField : Mechanical state named " << restMState->getName() << " found for RestShapeSpringFF named " << this->getName() << std::endl; } this->k = stiffness.getValue(); recomputeIndices(); } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::recomputeIndices() { m_indices.clear(); m_ext_indices.clear(); for (unsigned int i = 0; i < points.getValue().size(); i++) m_indices.push_back(points.getValue()[i]); for (unsigned int i = 0; i < external_points.getValue().size(); i++) m_ext_indices.push_back(external_points.getValue()[i]); if (m_indices.size()==0) { // std::cout << "in RestShapeSpringsForceField no point are defined, default case: points = all points " << std::endl; for (unsigned int i = 0; i < (unsigned)this->mstate->getSize(); i++) { m_indices.push_back(i); } } if (m_ext_indices.size()==0) { // std::cout << "in RestShapeSpringsForceField no external_points are defined, default case: points = all points " << std::endl; if (useRestMState) { for (unsigned int i = 0; i < (unsigned)restMState->getSize(); i++) { m_ext_indices.push_back(i); } } else { for (unsigned int i = 0; i < (unsigned)this->mstate->getSize(); i++) { m_ext_indices.push_back(i); } } } if (m_indices.size() > m_ext_indices.size()) { std::cerr << "Error : the dimention of the source and the targeted points are different " << std::endl; m_indices.clear(); } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addForce(const core::MechanicalParams* /* mparams */ /* PARAMS FIRST */, DataVecDeriv& f, const DataVecCoord& x, const DataVecDeriv& /* v */) { sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > f1 = f; sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p1 = x; sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p0 = *(useRestMState ? restMState->read(core::VecCoordId::position()) : this->mstate->read(core::VecCoordId::restPosition())); f1.resize(p1.size()); if (recompute_indices.getValue()) { recomputeIndices(); } Springs_dir.resize(m_indices.size() ); if ( k.size()!= m_indices.size() ) { //sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl; for (unsigned int i=0; i<m_indices.size(); i++) { const unsigned int index = m_indices[i]; const unsigned int ext_index = m_ext_indices[i]; Deriv dx = p1[index] - p0[ext_index]; Springs_dir[i] = p1[index] - p0[ext_index]; Springs_dir[i].normalize(); f1[index] -= dx * k[0] ; // if (dx.norm()>0.00000001) // std::cout<<"force on point "<<index<<std::endl; // Deriv dx = p[i] - p_0[i]; // f[ indices[i] ] -= dx * k[0] ; } } else { for (unsigned int i=0; i<m_indices.size(); i++) { const unsigned int index = m_indices[i]; const unsigned int ext_index = m_ext_indices[i]; Deriv dx = p1[index] - p0[ext_index]; Springs_dir[i] = p1[index] - p0[ext_index]; Springs_dir[i].normalize(); f1[index] -= dx * k[i] ; // if (dx.norm()>0.00000001) // std::cout<<"force on point "<<index<<std::endl; // Deriv dx = p[i] - p_0[i]; // f[ indices[i] ] -= dx * k[i] ; } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addDForce(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& df, const DataVecDeriv& dx) { // remove to be able to build in parallel // const VecIndex& indices = points.getValue(); // const VecReal& k = stiffness.getValue(); sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > df1 = df; sofa::helper::ReadAccessor< core::objectmodel::Data< VecDeriv > > dx1 = dx; double kFactor = mparams->kFactor(); if (k.size()!= m_indices.size() ) { sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl; for (unsigned int i=0; i<m_indices.size(); i++) { df1[m_indices[i]] -= dx1[m_indices[i]] * k[0] * kFactor; } } else { for (unsigned int i=0; i<m_indices.size(); i++) { df1[m_indices[i]] -= dx1[m_indices[i]] * k[i] * kFactor ; } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::addKToMatrix(const core::MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix ) { // remove to be able to build in parallel // const VecIndex& indices = points.getValue(); // const VecReal& k = stiffness.getValue(); sofa::core::behavior::MultiMatrixAccessor::MatrixRef mref = matrix->getMatrix(this->mstate); sofa::defaulttype::BaseMatrix* mat = mref.matrix; unsigned int offset = mref.offset; double kFact = mparams->kFactor(); const int N = Coord::total_size; unsigned int curIndex = 0; if (k.size()!= m_indices.size() ) { for (unsigned int index = 0; index < m_indices.size(); index++) { curIndex = m_indices[index]; for(int i = 0; i < N; i++) { // for (unsigned int j = 0; j < N; j++) // { // mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[0]); // } mat->add(offset + N * curIndex + i, offset + N * curIndex + i, -kFact * k[0]); } } } else { for (unsigned int index = 0; index < m_indices.size(); index++) { curIndex = m_indices[index]; for(int i = 0; i < N; i++) { // for (unsigned int j = 0; j < N; j++) // { // mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[curIndex]); // } mat->add(offset + N * curIndex + i, offset + N * curIndex + i, -kFact * k[i]); } } } } template<class DataTypes> void RestShapeSpringsForceField<DataTypes>::draw(const core::visual::VisualParams* ) { } template <class DataTypes> bool RestShapeSpringsForceField<DataTypes>::addBBox(double*, double* ) { return false; } } // namespace forcefield } // namespace component } // namespace sofa #endif // SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL <|endoftext|>
<commit_before>// // Copyright (c) 2018 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "nf_native_system_math.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, Library_nf_native_system_math_System_Math::Abs___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Abs___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Acos___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Acos___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Asin___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Asin___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Atan___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Atan___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Atan2___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::Atan2___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Ceiling___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Ceiling___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Cos___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Cos___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Cosh___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Cosh___STATIC__R4__R4, Library_nf_native_system_math_System_Math::IEEERemainder___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::IEEERemainder___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Exp___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Exp___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Floor___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Floor___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Log___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Log___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Log10___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Log10___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Max___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::Max___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Min___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::Min___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Pow___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::Pow___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Round___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Round___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Sign___STATIC__I4__R8, Library_nf_native_system_math_System_Math::Sign___STATIC__I4__R4, Library_nf_native_system_math_System_Math::Sin___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Sin___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Sinh___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Sinh___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Sqrt___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Sqrt___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Tan___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Tan___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Tanh___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Tanh___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Truncate___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Truncate___STATIC__R4__R4, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Math = { "System.Math", 0x4BDCF00F, method_lookup, { 1, 0, 2, 15 } }; <commit_msg>Update nanoFramework.System.Math version to 1.0.2 ***NO_CI***<commit_after>// // Copyright (c) 2018 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "nf_native_system_math.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, Library_nf_native_system_math_System_Math::Abs___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Abs___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Acos___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Acos___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Asin___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Asin___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Atan___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Atan___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Atan2___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::Atan2___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Ceiling___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Ceiling___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Cos___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Cos___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Cosh___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Cosh___STATIC__R4__R4, Library_nf_native_system_math_System_Math::IEEERemainder___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::IEEERemainder___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Exp___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Exp___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Floor___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Floor___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Log___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Log___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Log10___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Log10___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Max___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::Max___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Min___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::Min___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Pow___STATIC__R8__R8__R8, Library_nf_native_system_math_System_Math::Pow___STATIC__R4__R4__R4, Library_nf_native_system_math_System_Math::Round___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Round___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Sign___STATIC__I4__R8, Library_nf_native_system_math_System_Math::Sign___STATIC__I4__R4, Library_nf_native_system_math_System_Math::Sin___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Sin___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Sinh___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Sinh___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Sqrt___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Sqrt___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Tan___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Tan___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Tanh___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Tanh___STATIC__R4__R4, Library_nf_native_system_math_System_Math::Truncate___STATIC__R8__R8, Library_nf_native_system_math_System_Math::Truncate___STATIC__R4__R4, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Math = { "System.Math", 0x4BDCF00F, method_lookup, { 1, 0, 2, 2 } }; <|endoftext|>
<commit_before>/* * Copyright (c) 2002 - present, H. Hernan Saez * 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 copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER 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 "Rendering/Materials/UnlitMaterial.hpp" #include "Rendering/DescriptorSet.hpp" #include "Rendering/Pipeline.hpp" #include "Rendering/Programs/UnlitShaderProgram.hpp" #include "Rendering/Texture.hpp" #include "Rendering/UniformBuffer.hpp" #include "Simulation/AssetManager.hpp" using namespace crimild; UnlitMaterial::UnlitMaterial( void ) noexcept { setGraphicsPipeline( [] { auto pipeline = crimild::alloc< GraphicsPipeline >(); pipeline->setProgram( crimild::retain( AssetManager::getInstance()->get< UnlitShaderProgram >() ) ); return pipeline; }() ); setDescriptors( [ & ] { auto descriptors = crimild::alloc< DescriptorSet >(); descriptors->descriptors = { { .descriptorType = DescriptorType::UNIFORM_BUFFER, .obj = crimild::alloc< UniformBuffer >( RGBAColorf::ONE ), }, { .descriptorType = DescriptorType::TEXTURE, .obj = Texture::ONE, }, }; return descriptors; }() ); } void UnlitMaterial::setColor( const RGBAColorf &color ) noexcept { getDescriptors()->descriptors[ 0 ].get< UniformBuffer >()->setValue( color ); } RGBAColorf UnlitMaterial::getColor( void ) const noexcept { getDescriptors()->descriptors[ 0 ].get< UniformBuffer >()->getValue< RGBAColorf >(); } void UnlitMaterial::setTexture( SharedPointer< Texture > const &texture ) noexcept { getDescriptors()->descriptors[ 1 ].obj = texture; } const Texture *UnlitMaterial::getTexture( void ) const noexcept { return getDescriptors()->descriptors[ 1 ].get< Texture >(); } Texture *UnlitMaterial::getTexture( void ) noexcept { return getDescriptors()->descriptors[ 1 ].get< Texture >(); } <commit_msg>Fix return value in Unlit material<commit_after>/* * Copyright (c) 2002 - present, H. Hernan Saez * 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 copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER 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 "Rendering/Materials/UnlitMaterial.hpp" #include "Rendering/DescriptorSet.hpp" #include "Rendering/Pipeline.hpp" #include "Rendering/Programs/UnlitShaderProgram.hpp" #include "Rendering/Texture.hpp" #include "Rendering/UniformBuffer.hpp" #include "Simulation/AssetManager.hpp" using namespace crimild; UnlitMaterial::UnlitMaterial( void ) noexcept { setGraphicsPipeline( [] { auto pipeline = crimild::alloc< GraphicsPipeline >(); pipeline->setProgram( crimild::retain( AssetManager::getInstance()->get< UnlitShaderProgram >() ) ); return pipeline; }() ); setDescriptors( [ & ] { auto descriptors = crimild::alloc< DescriptorSet >(); descriptors->descriptors = { { .descriptorType = DescriptorType::UNIFORM_BUFFER, .obj = crimild::alloc< UniformBuffer >( RGBAColorf::ONE ), }, { .descriptorType = DescriptorType::TEXTURE, .obj = Texture::ONE, }, }; return descriptors; }() ); } void UnlitMaterial::setColor( const RGBAColorf &color ) noexcept { getDescriptors()->descriptors[ 0 ].get< UniformBuffer >()->setValue( color ); } RGBAColorf UnlitMaterial::getColor( void ) const noexcept { return getDescriptors()->descriptors[ 0 ].get< UniformBuffer >()->getValue< RGBAColorf >(); } void UnlitMaterial::setTexture( SharedPointer< Texture > const &texture ) noexcept { getDescriptors()->descriptors[ 1 ].obj = texture; } const Texture *UnlitMaterial::getTexture( void ) const noexcept { return getDescriptors()->descriptors[ 1 ].get< Texture >(); } Texture *UnlitMaterial::getTexture( void ) noexcept { return getDescriptors()->descriptors[ 1 ].get< Texture >(); } <|endoftext|>
<commit_before><commit_msg>Planning: remove unnecessary deep copy in ROI_decider.<commit_after><|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "MemoryLeakCheck.h" #include "OggVorbisLoader.h" #include "LoggingFunctions.h" #include <sstream> #ifndef TUNDRA_NO_AUDIO #include <vorbis/vorbisfile.h> #endif #ifndef TUNDRA_NO_AUDIO namespace { class OggMemDataSource { public: OggMemDataSource(const u8* data, size_t size) : data_(data), size_(size), position_(0) { } size_t Read(void* ptr, size_t size) { size_t max_read = size_ - position_; if (size > max_read) size = max_read; if (size) { memcpy(ptr, &data_[position_], size); position_ += size; } return size; } int Seek(ogg_int64_t offset, int whence) { size_t new_pos = position_; switch (whence) { case SEEK_SET: new_pos = offset; break; case SEEK_CUR: new_pos += offset; break; case SEEK_END: new_pos = size_ + offset; break; } if (new_pos < 0 || new_pos > size_) return -1; position_ = new_pos; return 0; } long Tell() const { return (long)position_; } private: const u8* data_; size_t size_; size_t position_; }; size_t OggReadCallback(void* ptr, size_t size, size_t nmemb, void* datasource) { OggMemDataSource* source = (OggMemDataSource*)datasource; return source->Read(ptr, size * nmemb); } int OggSeekCallback(void* datasource, ogg_int64_t offset, int whence) { OggMemDataSource* source = (OggMemDataSource*)datasource; return source->Seek(offset, whence); } long OggTellCallback(void* datasource) { OggMemDataSource* source = (OggMemDataSource*)datasource; return source->Tell(); } } // ~unnamed namespace #endif namespace OggVorbisLoader { bool LoadOggVorbisFromFileInMemory(const u8 *fileData, size_t numBytes, std::vector<u8> &dst, bool *isStereo, bool *is16Bit, int *frequency) { if (!fileData || numBytes == 0) { LogError("Null input data passed in"); return false; } if (!isStereo || !is16Bit || !frequency) { LogError("Outputs not set"); return false; } #ifndef TUNDRA_NO_AUDIO OggVorbis_File vf; OggMemDataSource src(fileData, numBytes); ov_callbacks cb; cb.read_func = &OggReadCallback; cb.seek_func = &OggSeekCallback; cb.tell_func = &OggTellCallback; cb.close_func = 0; int ret = ov_open_callbacks(&src, &vf, 0, 0, cb); if (ret < 0) { LogError("Not ogg vorbis format"); ov_clear(&vf); return false; } vorbis_info* vi = ov_info(&vf, -1); if (!vi) { LogError("No ogg vorbis stream info"); ov_clear(&vf); return false; } std::ostringstream msg; msg << "Decoding ogg vorbis stream with " << vi->channels << " channels, frequency " << vi->rate; // LogDebug(msg.str()); *frequency = vi->rate; *isStereo = (vi->channels > 1); *is16Bit = true; if (vi->channels != 1 && vi->channels != 2) LogWarning("Warning: Loaded Ogg Vorbis data contains an unsupported number of channels: " + QString::number(vi->channels)); uint decoded_bytes = 0; dst.clear(); for(;;) { static const int MAX_DECODE_SIZE = 16384; dst.resize(decoded_bytes + MAX_DECODE_SIZE); int bitstream; long ret = ov_read(&vf, (char*)&dst[decoded_bytes], MAX_DECODE_SIZE, 0, 2, 1, &bitstream); if (ret <= 0) break; decoded_bytes += ret; } dst.resize(decoded_bytes); { std::ostringstream msg; msg << "Decoded " << decoded_bytes << " bytes of ogg vorbis sound data"; // LogDebug(msg.str()); } ov_clear(&vf); return true; #else return false; #endif } } // ~OggVorbisLoader <commit_msg>LoadOggVorbisFromFileInMemory: Set is16Bit always to true (vorbis is always decoded at 16-bit). Fixes #672.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "MemoryLeakCheck.h" #include "OggVorbisLoader.h" #include "LoggingFunctions.h" #include <sstream> #ifndef TUNDRA_NO_AUDIO #include <vorbis/vorbisfile.h> #endif #ifndef TUNDRA_NO_AUDIO namespace { class OggMemDataSource { public: OggMemDataSource(const u8* data, size_t size) : data_(data), size_(size), position_(0) { } size_t Read(void* ptr, size_t size) { size_t max_read = size_ - position_; if (size > max_read) size = max_read; if (size) { memcpy(ptr, &data_[position_], size); position_ += size; } return size; } int Seek(ogg_int64_t offset, int whence) { size_t new_pos = position_; switch (whence) { case SEEK_SET: new_pos = offset; break; case SEEK_CUR: new_pos += offset; break; case SEEK_END: new_pos = size_ + offset; break; } if (new_pos < 0 || new_pos > size_) return -1; position_ = new_pos; return 0; } long Tell() const { return (long)position_; } private: const u8* data_; size_t size_; size_t position_; }; size_t OggReadCallback(void* ptr, size_t size, size_t nmemb, void* datasource) { OggMemDataSource* source = (OggMemDataSource*)datasource; return source->Read(ptr, size * nmemb); } int OggSeekCallback(void* datasource, ogg_int64_t offset, int whence) { OggMemDataSource* source = (OggMemDataSource*)datasource; return source->Seek(offset, whence); } long OggTellCallback(void* datasource) { OggMemDataSource* source = (OggMemDataSource*)datasource; return source->Tell(); } } // ~unnamed namespace #endif namespace OggVorbisLoader { bool LoadOggVorbisFromFileInMemory(const u8 *fileData, size_t numBytes, std::vector<u8> &dst, bool *isStereo, bool *is16Bit, int *frequency) { if (!fileData || numBytes == 0) { LogError("Null input data passed in"); return false; } if (!isStereo || !is16Bit || !frequency) { LogError("Outputs not set"); return false; } #ifndef TUNDRA_NO_AUDIO OggVorbis_File vf; OggMemDataSource src(fileData, numBytes); ov_callbacks cb; cb.read_func = &OggReadCallback; cb.seek_func = &OggSeekCallback; cb.tell_func = &OggTellCallback; cb.close_func = 0; int ret = ov_open_callbacks(&src, &vf, 0, 0, cb); if (ret < 0) { LogError("Not ogg vorbis format"); ov_clear(&vf); return false; } vorbis_info* vi = ov_info(&vf, -1); if (!vi) { LogError("No ogg vorbis stream info"); ov_clear(&vf); return false; } std::ostringstream msg; msg << "Decoding ogg vorbis stream with " << vi->channels << " channels, frequency " << vi->rate; // LogDebug(msg.str()); *is16Bit = true; // vorbis is always decoded at 16-bit *frequency = vi->rate; *isStereo = (vi->channels > 1); *is16Bit = true; if (vi->channels != 1 && vi->channels != 2) LogWarning("Warning: Loaded Ogg Vorbis data contains an unsupported number of channels: " + QString::number(vi->channels)); uint decoded_bytes = 0; dst.clear(); for(;;) { static const int MAX_DECODE_SIZE = 16384; dst.resize(decoded_bytes + MAX_DECODE_SIZE); int bitstream; long ret = ov_read(&vf, (char*)&dst[decoded_bytes], MAX_DECODE_SIZE, 0, 2, 1, &bitstream); if (ret <= 0) break; decoded_bytes += ret; } dst.resize(decoded_bytes); { std::ostringstream msg; msg << "Decoded " << decoded_bytes << " bytes of ogg vorbis sound data"; // LogDebug(msg.str()); } ov_clear(&vf); return true; #else return false; #endif } } // ~OggVorbisLoader <|endoftext|>
<commit_before>#include "rtkTest.h" #include "rtkConfiguration.h" #include "rtkMacro.h" #include "rtkSimplexSpectralProjectionsDecompositionImageFilter.h" #include "rtkSpectralForwardModelImageFilter.h" #include "rtkConstantImageSource.h" #include "rtkRayEllipsoidIntersectionImageFilter.h" #include <itkImageFileReader.h> /** * \file rtkdecomposespectralprojectionstest.cxx * * \brief Functional test for the filters performing spectral forward model and spectral projections' material decomposition * * This test generates analytical projections of a small phantom made of cylinder of water, * iodine and gadolinium, computes the expected photon counts in each detector bin in the * noiseless case, and performs a material decomposition on the photon counts to recover * the analytical projections. * * \author Cyril Mory */ int main(int , char** ) { typedef float PixelValueType; const unsigned int Dimension = 3; typedef itk::Image< PixelValueType, Dimension > OutputImageType; typedef itk::VectorImage< PixelValueType, Dimension > DecomposedProjectionType; typedef itk::VectorImage< PixelValueType, Dimension > SpectralProjectionsType; typedef itk::VectorImage< PixelValueType, Dimension-1 > IncidentSpectrumImageType; typedef itk::ImageFileReader<IncidentSpectrumImageType> IncidentSpectrumReaderType; typedef itk::Image< PixelValueType, Dimension-1 > DetectorResponseImageType; typedef itk::ImageFileReader<DetectorResponseImageType> DetectorResponseReaderType; typedef itk::Image< PixelValueType, Dimension-1 > MaterialAttenuationsImageType; typedef itk::ImageFileReader<MaterialAttenuationsImageType> MaterialAttenuationsReaderType; // Read all inputs IncidentSpectrumReaderType::Pointer incidentSpectrumReader = IncidentSpectrumReaderType::New(); incidentSpectrumReader->SetFileName( std::string(RTK_DATA_ROOT) + std::string("/Input/Spectral/incident_spectrum.mha") ); incidentSpectrumReader->Update(); DetectorResponseReaderType::Pointer detectorResponseReader = DetectorResponseReaderType::New(); detectorResponseReader->SetFileName( std::string(RTK_DATA_ROOT) + std::string("/Input/Spectral/detector_response.mha") ); detectorResponseReader->Update(); MaterialAttenuationsReaderType::Pointer materialAttenuationsReader = MaterialAttenuationsReaderType::New(); materialAttenuationsReader->SetFileName( std::string(RTK_DATA_ROOT) + std::string("/Input/Spectral/material_attenuations.mha") ); materialAttenuationsReader->Update(); #if FAST_TESTS_NO_CHECKS const unsigned int NumberOfProjectionImages = 1; #else const unsigned int NumberOfProjectionImages = 64; #endif // Constant image source for the analytical projections calculation typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New(); origin[0] = -255.; origin[1] = -0.5; origin[2] = -255.; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 1; size[2] = NumberOfProjectionImages; spacing[0] = 504.; spacing[1] = 504.; spacing[2] = 504.; #else size[0] = 64; size[1] = 1; size[2] = NumberOfProjectionImages; spacing[0] = 8.; spacing[1] = 1.; spacing[2] = 1.; #endif projectionsSource->SetOrigin( origin ); projectionsSource->SetSpacing( spacing ); projectionsSource->SetSize( size ); projectionsSource->SetConstant( 0. ); // Initialize the multi-materials projections DecomposedProjectionType::Pointer decomposed = DecomposedProjectionType::New(); decomposed->SetVectorLength(3); decomposed->SetOrigin( origin ); decomposed->SetSpacing( spacing ); DecomposedProjectionType::RegionType region; DecomposedProjectionType::IndexType index; index.Fill(0); region.SetSize(size); region.SetIndex(index); decomposed->SetRegions(region); decomposed->Allocate(); // Geometry object typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages); // Generate 3 phantoms, one per material typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType; REIType::Pointer rei; rei = REIType::New(); for (unsigned int material=0; material<3; material++) { REIType::VectorType semiprincipalaxis, center; semiprincipalaxis.Fill(10.); center.Fill(0.); // center[0] = (material-1) * 15; // center[2] = (material-1) * 15; center[0] = 15; center[2] = 15; rei->SetAngle(0.); if (material==2) //water rei->SetDensity(1.); else //iodine and gadolinium rei->SetDensity(0.01); rei->SetCenter(center); rei->SetAxis(semiprincipalaxis); // Compute analytical projections through them rei->SetInput( projectionsSource->GetOutput() ); rei->SetGeometry( geometry ); TRY_AND_EXIT_ON_ITK_EXCEPTION( rei->Update() ); // Merge these projections into the multi-material projections image itk::ImageRegionConstIterator<OutputImageType> inIt(rei->GetOutput(), rei->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionIterator<DecomposedProjectionType> outIt(decomposed, decomposed->GetLargestPossibleRegion()); outIt.GoToBegin(); while(!outIt.IsAtEnd()) { itk::VariableLengthVector<PixelValueType> vector = outIt.Get(); vector[material] = inIt.Get(); outIt.Set(vector); ++inIt; ++outIt; } } // Generate a set of zero-filled photon count projections SpectralProjectionsType::Pointer photonCounts = SpectralProjectionsType::New(); photonCounts->CopyInformation(decomposed); photonCounts->SetVectorLength(6); photonCounts->Allocate(); // Generate the thresholds vector itk::VariableLengthVector<unsigned int> thresholds; thresholds.SetSize(7); thresholds[0] = 25; thresholds[1] = 40; thresholds[2] = 55; thresholds[3] = 70; thresholds[4] = 85; thresholds[5] = 100; thresholds[6] = 180; // Apply the forward model to the multi-material projections typedef rtk::SpectralForwardModelImageFilter<DecomposedProjectionType, SpectralProjectionsType, IncidentSpectrumImageType> SpectralForwardFilterType; SpectralForwardFilterType::Pointer forward = SpectralForwardFilterType::New(); forward->SetInputDecomposedProjections(decomposed); forward->SetInputMeasuredProjections(photonCounts); forward->SetInputIncidentSpectrum(incidentSpectrumReader->GetOutput()); forward->SetDetectorResponse(detectorResponseReader->GetOutput()); forward->SetMaterialAttenuations(materialAttenuationsReader->GetOutput()); forward->SetThresholds(thresholds); TRY_AND_EXIT_ON_ITK_EXCEPTION(forward->Update()) // Generate a set of decomposed projections as input for the simplex DecomposedProjectionType::Pointer initialDecomposedProjections = DecomposedProjectionType::New(); initialDecomposedProjections->CopyInformation(decomposed); initialDecomposedProjections->SetRegions(region); initialDecomposedProjections->SetVectorLength(3); initialDecomposedProjections->Allocate(); DecomposedProjectionType::PixelType initPixel; initPixel.SetSize(3); initPixel[0] = 0.1; initPixel[1] = 0.1; initPixel[2] = 10; initialDecomposedProjections->FillBuffer(initPixel); // Create and set the simplex filter to perform the decomposition typedef rtk::SimplexSpectralProjectionsDecompositionImageFilter<DecomposedProjectionType, SpectralProjectionsType, IncidentSpectrumImageType> SimplexFilterType; SimplexFilterType::Pointer simplex = SimplexFilterType::New(); simplex->SetInputDecomposedProjections(initialDecomposedProjections); simplex->SetInputMeasuredProjections(forward->GetOutput()); simplex->SetInputIncidentSpectrum(incidentSpectrumReader->GetOutput()); simplex->SetDetectorResponse(detectorResponseReader->GetOutput()); simplex->SetMaterialAttenuations(materialAttenuationsReader->GetOutput()); simplex->SetThresholds(thresholds); simplex->SetNumberOfIterations(1000); TRY_AND_EXIT_ON_ITK_EXCEPTION(simplex->Update()) CheckVectorImageQuality<DecomposedProjectionType>(simplex->GetOutput(), decomposed, 0.0001, 15, 2.0); std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <commit_msg>Added test case in simplex for heuristic estimation of initial values<commit_after>#include "rtkTest.h" #include "rtkConfiguration.h" #include "rtkMacro.h" #include "rtkSimplexSpectralProjectionsDecompositionImageFilter.h" #include "rtkSpectralForwardModelImageFilter.h" #include "rtkConstantImageSource.h" #include "rtkRayEllipsoidIntersectionImageFilter.h" #include <itkImageFileReader.h> /** * \file rtkdecomposespectralprojectionstest.cxx * * \brief Functional test for the filters performing spectral forward model and spectral projections' material decomposition * * This test generates analytical projections of a small phantom made of cylinder of water, * iodine and gadolinium, computes the expected photon counts in each detector bin in the * noiseless case, and performs a material decomposition on the photon counts to recover * the analytical projections. * * \author Cyril Mory */ int main(int , char** ) { typedef float PixelValueType; const unsigned int Dimension = 3; typedef itk::Image< PixelValueType, Dimension > OutputImageType; typedef itk::VectorImage< PixelValueType, Dimension > DecomposedProjectionType; typedef itk::VectorImage< PixelValueType, Dimension > SpectralProjectionsType; typedef itk::VectorImage< PixelValueType, Dimension-1 > IncidentSpectrumImageType; typedef itk::ImageFileReader<IncidentSpectrumImageType> IncidentSpectrumReaderType; typedef itk::Image< PixelValueType, Dimension-1 > DetectorResponseImageType; typedef itk::ImageFileReader<DetectorResponseImageType> DetectorResponseReaderType; typedef itk::Image< PixelValueType, Dimension-1 > MaterialAttenuationsImageType; typedef itk::ImageFileReader<MaterialAttenuationsImageType> MaterialAttenuationsReaderType; // Read all inputs IncidentSpectrumReaderType::Pointer incidentSpectrumReader = IncidentSpectrumReaderType::New(); incidentSpectrumReader->SetFileName( std::string(RTK_DATA_ROOT) + std::string("/Input/Spectral/incident_spectrum.mha") ); incidentSpectrumReader->Update(); DetectorResponseReaderType::Pointer detectorResponseReader = DetectorResponseReaderType::New(); detectorResponseReader->SetFileName( std::string(RTK_DATA_ROOT) + std::string("/Input/Spectral/detector_response.mha") ); detectorResponseReader->Update(); MaterialAttenuationsReaderType::Pointer materialAttenuationsReader = MaterialAttenuationsReaderType::New(); materialAttenuationsReader->SetFileName( std::string(RTK_DATA_ROOT) + std::string("/Input/Spectral/material_attenuations.mha") ); materialAttenuationsReader->Update(); #if FAST_TESTS_NO_CHECKS const unsigned int NumberOfProjectionImages = 1; #else const unsigned int NumberOfProjectionImages = 64; #endif // Constant image source for the analytical projections calculation typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::PointType origin; ConstantImageSourceType::SizeType size; ConstantImageSourceType::SpacingType spacing; ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New(); origin[0] = -255.; origin[1] = -0.5; origin[2] = -255.; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 1; size[2] = NumberOfProjectionImages; spacing[0] = 504.; spacing[1] = 504.; spacing[2] = 504.; #else size[0] = 64; size[1] = 1; size[2] = NumberOfProjectionImages; spacing[0] = 8.; spacing[1] = 1.; spacing[2] = 1.; #endif projectionsSource->SetOrigin( origin ); projectionsSource->SetSpacing( spacing ); projectionsSource->SetSize( size ); projectionsSource->SetConstant( 0. ); // Initialize the multi-materials projections DecomposedProjectionType::Pointer decomposed = DecomposedProjectionType::New(); decomposed->SetVectorLength(3); decomposed->SetOrigin( origin ); decomposed->SetSpacing( spacing ); DecomposedProjectionType::RegionType region; DecomposedProjectionType::IndexType index; index.Fill(0); region.SetSize(size); region.SetIndex(index); decomposed->SetRegions(region); decomposed->Allocate(); // Geometry object typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages); // Generate 3 phantoms, one per material typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType; REIType::Pointer rei; rei = REIType::New(); for (unsigned int material=0; material<3; material++) { REIType::VectorType semiprincipalaxis, center; semiprincipalaxis.Fill(10.); center.Fill(0.); // center[0] = (material-1) * 15; // center[2] = (material-1) * 15; center[0] = 15; center[2] = 15; rei->SetAngle(0.); if (material==2) //water rei->SetDensity(1.); else //iodine and gadolinium rei->SetDensity(0.01); rei->SetCenter(center); rei->SetAxis(semiprincipalaxis); // Compute analytical projections through them rei->SetInput( projectionsSource->GetOutput() ); rei->SetGeometry( geometry ); TRY_AND_EXIT_ON_ITK_EXCEPTION( rei->Update() ); // Merge these projections into the multi-material projections image itk::ImageRegionConstIterator<OutputImageType> inIt(rei->GetOutput(), rei->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionIterator<DecomposedProjectionType> outIt(decomposed, decomposed->GetLargestPossibleRegion()); outIt.GoToBegin(); while(!outIt.IsAtEnd()) { itk::VariableLengthVector<PixelValueType> vector = outIt.Get(); vector[material] = inIt.Get(); outIt.Set(vector); ++inIt; ++outIt; } } // Generate a set of zero-filled photon count projections SpectralProjectionsType::Pointer photonCounts = SpectralProjectionsType::New(); photonCounts->CopyInformation(decomposed); photonCounts->SetVectorLength(6); photonCounts->Allocate(); // Generate the thresholds vector itk::VariableLengthVector<unsigned int> thresholds; thresholds.SetSize(7); thresholds[0] = 25; thresholds[1] = 40; thresholds[2] = 55; thresholds[3] = 70; thresholds[4] = 85; thresholds[5] = 100; thresholds[6] = 180; // Apply the forward model to the multi-material projections typedef rtk::SpectralForwardModelImageFilter<DecomposedProjectionType, SpectralProjectionsType, IncidentSpectrumImageType> SpectralForwardFilterType; SpectralForwardFilterType::Pointer forward = SpectralForwardFilterType::New(); forward->SetInputDecomposedProjections(decomposed); forward->SetInputMeasuredProjections(photonCounts); forward->SetInputIncidentSpectrum(incidentSpectrumReader->GetOutput()); forward->SetDetectorResponse(detectorResponseReader->GetOutput()); forward->SetMaterialAttenuations(materialAttenuationsReader->GetOutput()); forward->SetThresholds(thresholds); TRY_AND_EXIT_ON_ITK_EXCEPTION(forward->Update()) // Generate a set of decomposed projections as input for the simplex DecomposedProjectionType::Pointer initialDecomposedProjections = DecomposedProjectionType::New(); initialDecomposedProjections->CopyInformation(decomposed); initialDecomposedProjections->SetRegions(region); initialDecomposedProjections->SetVectorLength(3); initialDecomposedProjections->Allocate(); DecomposedProjectionType::PixelType initPixel; initPixel.SetSize(3); initPixel[0] = 0.1; initPixel[1] = 0.1; initPixel[2] = 10; initialDecomposedProjections->FillBuffer(initPixel); // Create and set the simplex filter to perform the decomposition typedef rtk::SimplexSpectralProjectionsDecompositionImageFilter<DecomposedProjectionType, SpectralProjectionsType, IncidentSpectrumImageType> SimplexFilterType; SimplexFilterType::Pointer simplex = SimplexFilterType::New(); simplex->SetInputDecomposedProjections(initialDecomposedProjections); simplex->SetInputMeasuredProjections(forward->GetOutput()); simplex->SetInputIncidentSpectrum(incidentSpectrumReader->GetOutput()); simplex->SetDetectorResponse(detectorResponseReader->GetOutput()); simplex->SetMaterialAttenuations(materialAttenuationsReader->GetOutput()); simplex->SetThresholds(thresholds); simplex->SetNumberOfIterations(10000); std::cout << "\n\n****** Case 1: User-provided initial values ******" << std::endl; TRY_AND_EXIT_ON_ITK_EXCEPTION(simplex->Update()) CheckVectorImageQuality<DecomposedProjectionType>(simplex->GetOutput(), decomposed, 0.0001, 15, 2.0); std::cout << "\n\n****** Case 2: Heuristically-determined initial values ******" << std::endl; simplex->SetGuessInitialization(true); TRY_AND_EXIT_ON_ITK_EXCEPTION(simplex->Update()) CheckVectorImageQuality<DecomposedProjectionType>(simplex->GetOutput(), decomposed, 0.0001, 15, 2.0); std::cout << "\n\nTest PASSED! " << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Fix a test to avoid a MSVC warning as error about constant truncation.<commit_after><|endoftext|>
<commit_before><commit_msg>Revert r23911, which switched from fork to vfork().<commit_after><|endoftext|>
<commit_before>/* * ofxImageObject.cpp * openFrameworks * * Created by Eric Gunther on 11/8/09. * Copyright 2009 Sosolimited. All rights reserved. * */ #include "ofxImageObject.h" #include "ofGraphics.h" ofxImageObject::ofxImageObject(string iFilename, bool iLoadNow) { filename = iFilename; if(iLoadNow){ image = new ofImage(); loaded = image->loadImage(iFilename); image->getTextureReference().texData.bFlipTexture = true; //Get images right side up in soso world }else{ image = NULL; } width = image->getWidth(); height = image->getHeight(); isCentered = false; renderDirty = true; //eg 070112 } ofxImageObject::~ofxImageObject(){ if (image) delete image; } void ofxImageObject::loadImage(string iFilename){ if (image==NULL){ image = new ofImage(); } if (loaded){ delete image; //remake image = new ofImage(); } loaded = image->loadImage(iFilename); image->getTextureReference().texData.bFlipTexture = true; //Get images right side up in soso world width = image->getWidth(); height = image->getHeight(); } void ofxImageObject::enableTexture(bool iB) { image->setUseTexture(iB); renderDirty = true; } //EG 021513 ofTexture ofxImageObject::getTexture() { return image->getTextureReference(); } void ofxImageObject::render() { //eg 070112 Added display lists. if(renderDirty){ glDeleteLists(displayList, 1); glNewList(displayList, GL_COMPILE_AND_EXECUTE); //For when iLoadNow=false is used in constructor if(width==0 || height==0){ width = image->getWidth(); height = image->getHeight(); } if(isCentered){ ofPushMatrix(); ofTranslate(-width/2, -height/2, 0); } glNormal3f(0,0,1); image->draw(0,0); if(isCentered){ ofPopMatrix(); } glEndList(); renderDirty = false; }else{ glCallList(displayList); } } void ofxImageObject::setCentered(bool iEnable) { isCentered = iEnable; renderDirty = true; } void ofxImageObject::clear() { if (loaded) { image->clear(); loaded = false; } renderDirty = true; }<commit_msg>check if image is null before getting height and width<commit_after>/* * ofxImageObject.cpp * openFrameworks * * Created by Eric Gunther on 11/8/09. * Copyright 2009 Sosolimited. All rights reserved. * */ #include "ofxImageObject.h" #include "ofGraphics.h" ofxImageObject::ofxImageObject(string iFilename, bool iLoadNow) { filename = iFilename; if(iLoadNow){ image = new ofImage(); loaded = image->loadImage(iFilename); image->getTextureReference().texData.bFlipTexture = true; //Get images right side up in soso world }else{ image = NULL; } if (image){ width = image->getWidth(); height = image->getHeight(); }else{ width = 0; height = 0; } isCentered = false; renderDirty = true; //eg 070112 } ofxImageObject::~ofxImageObject(){ if (image) delete image; } void ofxImageObject::loadImage(string iFilename){ if (image==NULL){ image = new ofImage(); } if (loaded){ delete image; //remake image = new ofImage(); } loaded = image->loadImage(iFilename); image->getTextureReference().texData.bFlipTexture = true; //Get images right side up in soso world width = image->getWidth(); height = image->getHeight(); } void ofxImageObject::enableTexture(bool iB) { if (image){ image->setUseTexture(iB); renderDirty = true; } } //EG 021513 ofTexture ofxImageObject::getTexture() { return image->getTextureReference(); } void ofxImageObject::render() { //eg 070112 Added display lists. if(renderDirty){ glDeleteLists(displayList, 1); glNewList(displayList, GL_COMPILE_AND_EXECUTE); //For when iLoadNow=false is used in constructor if(width==0 || height==0){ if (image){ width = image->getWidth(); height = image->getHeight(); }else{ width = 0; height = 0; } } if(isCentered){ ofPushMatrix(); ofTranslate(-width/2, -height/2, 0); } glNormal3f(0,0,1); if (image) image->draw(0,0); if(isCentered){ ofPopMatrix(); } glEndList(); renderDirty = false; }else{ glCallList(displayList); } } void ofxImageObject::setCentered(bool iEnable) { isCentered = iEnable; renderDirty = true; } void ofxImageObject::clear() { if (loaded) { if (image) image->clear(); loaded = false; } renderDirty = true; }<|endoftext|>
<commit_before><commit_msg>non copyable has a virtual destructor<commit_after><|endoftext|>
<commit_before><commit_msg>#i10000# Includes corrected (we are in module sfx2, so do not use sfx2 include path!).<commit_after><|endoftext|>
<commit_before>/* @author gogdizzy @date 2015-08-20 @desciption 收集到的一些位运算代码片段 @resource http://graphics.stanford.edu/~seander/bithacks.html */ // 返回大于等于x的最小的2次幂,0返回0,负数返回0 // 根据这个方法,可以很容易写出无符号版本和64bit版本 int32_t nextpow2( int32_t x ) { --x; x |= ( x >> 1 ); x |= ( x >> 2 ); x |= ( x >> 4 ); x |= ( x >> 8 ); x |= ( x >> 16 ); return ++x; } // 解析出最低bit int32_t lowbit( int32_t x ) { return x & -x; } // 求绝对值 int32_t abs( int32_t x ) { return ( x ^ ( x >> 31 ) ) - ( x >> 31 ); } float abs( float f ) { int x = *(int*)&f; x &= 0x7fffffff; return *(float*)&x; } <commit_msg>modify bitop<commit_after>/* @author gogdizzy @date 2015-08-20 @desciption 收集到的一些位运算代码片段 @resource http://graphics.stanford.edu/~seander/bithacks.html http://blog.jobbole.com/70993/ (原文:http://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c/746203#746203) */ // 返回大于等于x的最小的2次幂,0返回0,负数返回0 // 根据这个方法,可以很容易写出无符号版本和64bit版本 int32_t nextpow2( int32_t x ) { --x; x |= ( x >> 1 ); x |= ( x >> 2 ); x |= ( x >> 4 ); x |= ( x >> 8 ); x |= ( x >> 16 ); return ++x; } // 解析出最低bit int32_t lowbit( int32_t x ) { return x & -x; } // 求绝对值 int32_t abs( int32_t x ) { return ( x ^ ( x >> 31 ) ) - ( x >> 31 ); } float abs( float f ) { int x = *(int*)&f; x &= 0x7fffffff; return *(float*)&x; } // 位反转,这个在fft中经常用到 // http://blog.jobbole.com/70993/ <|endoftext|>
<commit_before> #include <boost/filesystem.hpp> #include <boost/make_shared.hpp> #include <boost/program_options.hpp> #include <iostream> #include <crypto++/files.h> #include <log4cplus/configurator.h> #include "buildconf.hpp" #include "lib/hashes.h" #include "server/config.hpp" #include "server/server.hpp" using namespace std; namespace asio = boost::asio; namespace fs = boost::filesystem; namespace po = boost::program_options; using namespace bithorded; class Layout : public log4cplus::TTCCLayout { public: Layout() : TTCCLayout() { dateFormat = "%Y-%m-%d %H:%M:%S.%q"; } }; int main(int argc, char* argv[]) { log4cplus::BasicConfigurator config; config.configure(); auto root = log4cplus::Logger::getDefaultHierarchy().getRoot(); auto layout = std::auto_ptr<log4cplus::Layout>(new Layout()); auto appenders = root.getAllAppenders(); for (auto iter = appenders.begin(); iter != appenders.end(); iter++) (*iter)->setLayout(layout); try { Config cfg(argc, argv); asio::io_service ioSvc; Server server(ioSvc, cfg); ioSvc.run(); return 0; } catch (VersionExit& e) { return bithorde::exit_version(); } catch (ArgumentError& e) { cerr << e.what() << endl; Config::print_usage(cerr); return -1; } } <commit_msg>[bithorded/main]Explicitly include hierarchy.<commit_after> #include <boost/filesystem.hpp> #include <boost/make_shared.hpp> #include <boost/program_options.hpp> #include <iostream> #include <crypto++/files.h> #include <log4cplus/configurator.h> #include <log4cplus/hierarchy.h> #include "buildconf.hpp" #include "lib/hashes.h" #include "server/config.hpp" #include "server/server.hpp" using namespace std; namespace asio = boost::asio; namespace fs = boost::filesystem; namespace po = boost::program_options; using namespace bithorded; class Layout : public log4cplus::TTCCLayout { public: Layout() : TTCCLayout() { dateFormat = "%Y-%m-%d %H:%M:%S.%q"; } }; int main(int argc, char* argv[]) { log4cplus::BasicConfigurator config; config.configure(); auto root = log4cplus::Logger::getDefaultHierarchy().getRoot(); auto layout = std::auto_ptr<log4cplus::Layout>(new Layout()); auto appenders = root.getAllAppenders(); for (auto iter = appenders.begin(); iter != appenders.end(); iter++) (*iter)->setLayout(layout); try { Config cfg(argc, argv); asio::io_service ioSvc; Server server(ioSvc, cfg); ioSvc.run(); return 0; } catch (VersionExit& e) { return bithorde::exit_version(); } catch (ArgumentError& e) { cerr << e.what() << endl; Config::print_usage(cerr); return -1; } } <|endoftext|>
<commit_before>#include <cassert> #include <iostream> #include <sstream> #include "lbfgs.h" #include "sparse_vector.h" #include "fdict.h" using namespace std; double TestOptimizer() { cerr << "TESTING NON-PERSISTENT OPTIMIZER\n"; // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5 // df/dx1 = 8*x1 + x2 // df/dx2 = 2*x2 + x1 // df/dx3 = 2*x3 + 6 double x[3]; double g[3]; scitbx::lbfgs::minimizer<double> opt(3); scitbx::lbfgs::traditional_convergence_test<double> converged(3); x[0] = 8; x[1] = 8; x[2] = 8; double obj = 0; do { g[0] = 8 * x[0] + x[1]; g[1] = 2 * x[1] + x[0]; g[2] = 2 * x[2] + 6; obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5; opt.run(x, obj, g); if (!opt.requests_f_and_g()) { if (converged(x,g)) break; opt.run(x, obj, g); } cerr << x[0] << " " << x[1] << " " << x[2] << endl; cerr << " obj=" << obj << "\td/dx1=" << g[0] << " d/dx2=" << g[1] << " d/dx3=" << g[2] << endl; cerr << opt << endl; } while (true); return obj; } double TestPersistentOptimizer() { cerr << "\nTESTING PERSISTENT OPTIMIZER\n"; // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5 // df/dx1 = 8*x1 + x2 // df/dx2 = 2*x2 + x1 // df/dx3 = 2*x3 + 6 double x[3]; double g[3]; scitbx::lbfgs::traditional_convergence_test<double> converged(3); x[0] = 8; x[1] = 8; x[2] = 8; double obj = 0; string state; do { g[0] = 8 * x[0] + x[1]; g[1] = 2 * x[1] + x[0]; g[2] = 2 * x[2] + 6; obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5; { scitbx::lbfgs::minimizer<double> opt(3); if (state.size() > 0) { istringstream is(state, ios::binary); opt.deserialize(&is); } opt.run(x, obj, g); ostringstream os(ios::binary); opt.serialize(&os); state = os.str(); } cerr << x[0] << " " << x[1] << " " << x[2] << endl; cerr << " obj=" << obj << "\td/dx1=" << g[0] << " d/dx2=" << g[1] << " d/dx3=" << g[2] << endl; } while (!converged(x, g)); return obj; } void TestSparseVector() { cerr << "Testing SparseVector<double> serialization.\n"; int f1 = FD::Convert("Feature_1"); int f2 = FD::Convert("Feature_2"); FD::Convert("LanguageModel"); int f4 = FD::Convert("SomeFeature"); int f5 = FD::Convert("SomeOtherFeature"); SparseVector<double> g; g.set_value(f2, log(0.5)); g.set_value(f4, log(0.125)); g.set_value(f1, 0); g.set_value(f5, 23.777); ostringstream os; double iobj = 1.5; B64::Encode(iobj, g, &os); cerr << iobj << "\t" << g << endl; string data = os.str(); cout << data << endl; SparseVector<double> v; double obj; assert(B64::Decode(&obj, &v, &data[0], data.size())); cerr << obj << "\t" << v << endl; assert(obj == iobj); assert(g.size() == v.size()); } int main() { double o1 = TestOptimizer(); double o2 = TestPersistentOptimizer(); if (o1 != o2) { cerr << "OPTIMIZERS PERFORMED DIFFERENTLY!\n" << o1 << " vs. " << o2 << endl; return 1; } TestSparseVector(); cerr << "SUCCESS\n"; return 0; } <commit_msg>another fix<commit_after>#include <cassert> #include <iostream> #include <sstream> #include <cmath> #include "lbfgs.h" #include "sparse_vector.h" #include "fdict.h" using namespace std; double TestOptimizer() { cerr << "TESTING NON-PERSISTENT OPTIMIZER\n"; // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5 // df/dx1 = 8*x1 + x2 // df/dx2 = 2*x2 + x1 // df/dx3 = 2*x3 + 6 double x[3]; double g[3]; scitbx::lbfgs::minimizer<double> opt(3); scitbx::lbfgs::traditional_convergence_test<double> converged(3); x[0] = 8; x[1] = 8; x[2] = 8; double obj = 0; do { g[0] = 8 * x[0] + x[1]; g[1] = 2 * x[1] + x[0]; g[2] = 2 * x[2] + 6; obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5; opt.run(x, obj, g); if (!opt.requests_f_and_g()) { if (converged(x,g)) break; opt.run(x, obj, g); } cerr << x[0] << " " << x[1] << " " << x[2] << endl; cerr << " obj=" << obj << "\td/dx1=" << g[0] << " d/dx2=" << g[1] << " d/dx3=" << g[2] << endl; cerr << opt << endl; } while (true); return obj; } double TestPersistentOptimizer() { cerr << "\nTESTING PERSISTENT OPTIMIZER\n"; // f(x,y) = 4x1^2 + x1*x2 + x2^2 + x3^2 + 6x3 + 5 // df/dx1 = 8*x1 + x2 // df/dx2 = 2*x2 + x1 // df/dx3 = 2*x3 + 6 double x[3]; double g[3]; scitbx::lbfgs::traditional_convergence_test<double> converged(3); x[0] = 8; x[1] = 8; x[2] = 8; double obj = 0; string state; do { g[0] = 8 * x[0] + x[1]; g[1] = 2 * x[1] + x[0]; g[2] = 2 * x[2] + 6; obj = 4 * x[0]*x[0] + x[0] * x[1] + x[1]*x[1] + x[2]*x[2] + 6 * x[2] + 5; { scitbx::lbfgs::minimizer<double> opt(3); if (state.size() > 0) { istringstream is(state, ios::binary); opt.deserialize(&is); } opt.run(x, obj, g); ostringstream os(ios::binary); opt.serialize(&os); state = os.str(); } cerr << x[0] << " " << x[1] << " " << x[2] << endl; cerr << " obj=" << obj << "\td/dx1=" << g[0] << " d/dx2=" << g[1] << " d/dx3=" << g[2] << endl; } while (!converged(x, g)); return obj; } void TestSparseVector() { cerr << "Testing SparseVector<double> serialization.\n"; int f1 = FD::Convert("Feature_1"); int f2 = FD::Convert("Feature_2"); FD::Convert("LanguageModel"); int f4 = FD::Convert("SomeFeature"); int f5 = FD::Convert("SomeOtherFeature"); SparseVector<double> g; g.set_value(f2, log(0.5)); g.set_value(f4, log(0.125)); g.set_value(f1, 0); g.set_value(f5, 23.777); ostringstream os; double iobj = 1.5; B64::Encode(iobj, g, &os); cerr << iobj << "\t" << g << endl; string data = os.str(); cout << data << endl; SparseVector<double> v; double obj; bool decode_b64 = B64::Decode(&obj, &v, &data[0], data.size()); cerr << obj << "\t" << v << endl; assert(decode_b64); assert(obj == iobj); assert(g.size() == v.size()); } int main() { double o1 = TestOptimizer(); double o2 = TestPersistentOptimizer(); if (fabs(o1 - o2) > 1e-5) { cerr << "OPTIMIZERS PERFORMED DIFFERENTLY!\n" << o1 << " vs. " << o2 << endl; return 1; } TestSparseVector(); cerr << "SUCCESS\n"; return 0; } <|endoftext|>
<commit_before>#include <osg/DrawPixels> using namespace osg; DrawPixels::DrawPixels() { // turn off display lists right now, just incase we want to modify the projection matrix along the way. setSupportsDisplayList(false); _position.set(0.0f,0.0f,0.0f); _useSubImage = false; _offsetX = 0; _offsetY = 0; _width = 0; _height = 0; } DrawPixels::DrawPixels(const DrawPixels& drawimage,const CopyOp& copyop=CopyOp::SHALLOW_COPY): Drawable(drawimage,copyop), _position(drawimage._position), _image(drawimage._image), _useSubImage(drawimage._useSubImage), _offsetX(drawimage._offsetX), _offsetY(drawimage._offsetY), _width(drawimage._width), _height(drawimage._height) { } DrawPixels::~DrawPixels() { // image will delete itself thanks to ref_ptr :-) } void DrawPixels::setPosition(const osg::Vec3& position) { _position = position; dirtyBound(); } void DrawPixels::setSubImageDimensions(unsigned int offsetX,unsigned int offsetY,unsigned int width,unsigned int height) { _useSubImage = true; _offsetX = offsetX; _offsetY = offsetY; _width = width; _height = height; } void DrawPixels::getSubImageDimensions(unsigned int& offsetX,unsigned int& offsetY,unsigned int& width,unsigned int& height) const { offsetX = _offsetX; offsetY = _offsetY; width = _width; height = _height; } const bool DrawPixels::computeBound() const { // really needs to be dependant of view poistion and projection... will implement simple version right now. _bbox.init(); float diagonal = 0.0f; if (_useSubImage) { diagonal = sqrtf(_width*_width+_height*_height); } else { diagonal = sqrtf(_image->s()*_image->s()+_image->t()*_image->t()); } _bbox.expandBy(_position-osg::Vec3(diagonal,diagonal,diagonal)); _bbox.expandBy(_position+osg::Vec3(diagonal,diagonal,diagonal)); _bbox_computed = true; return true; } void DrawPixels::drawImmediateMode(State&) { glRasterPos3f(_position.x(),_position.y(),_position.z()); if (_useSubImage) { const GLvoid* pixels = _image->data(); glDrawPixels(_width,_height, (GLenum)_image->pixelFormat(), (GLenum)_image->dataType(), pixels); } else { glDrawPixels(_image->s(), _image->t(), (GLenum)_image->pixelFormat(), (GLenum)_image->dataType(), _image->data() ); } } <commit_msg>Fix for Win32 build.<commit_after>#include <osg/DrawPixels> using namespace osg; DrawPixels::DrawPixels() { // turn off display lists right now, just incase we want to modify the projection matrix along the way. setSupportsDisplayList(false); _position.set(0.0f,0.0f,0.0f); _useSubImage = false; _offsetX = 0; _offsetY = 0; _width = 0; _height = 0; } DrawPixels::DrawPixels(const DrawPixels& drawimage,const CopyOp& copyop): Drawable(drawimage,copyop), _position(drawimage._position), _image(drawimage._image), _useSubImage(drawimage._useSubImage), _offsetX(drawimage._offsetX), _offsetY(drawimage._offsetY), _width(drawimage._width), _height(drawimage._height) { } DrawPixels::~DrawPixels() { // image will delete itself thanks to ref_ptr :-) } void DrawPixels::setPosition(const osg::Vec3& position) { _position = position; dirtyBound(); } void DrawPixels::setSubImageDimensions(unsigned int offsetX,unsigned int offsetY,unsigned int width,unsigned int height) { _useSubImage = true; _offsetX = offsetX; _offsetY = offsetY; _width = width; _height = height; } void DrawPixels::getSubImageDimensions(unsigned int& offsetX,unsigned int& offsetY,unsigned int& width,unsigned int& height) const { offsetX = _offsetX; offsetY = _offsetY; width = _width; height = _height; } const bool DrawPixels::computeBound() const { // really needs to be dependant of view poistion and projection... will implement simple version right now. _bbox.init(); float diagonal = 0.0f; if (_useSubImage) { diagonal = sqrtf(_width*_width+_height*_height); } else { diagonal = sqrtf(_image->s()*_image->s()+_image->t()*_image->t()); } _bbox.expandBy(_position-osg::Vec3(diagonal,diagonal,diagonal)); _bbox.expandBy(_position+osg::Vec3(diagonal,diagonal,diagonal)); _bbox_computed = true; return true; } void DrawPixels::drawImmediateMode(State&) { glRasterPos3f(_position.x(),_position.y(),_position.z()); if (_useSubImage) { const GLvoid* pixels = _image->data(); glDrawPixels(_width,_height, (GLenum)_image->pixelFormat(), (GLenum)_image->dataType(), pixels); } else { glDrawPixels(_image->s(), _image->t(), (GLenum)_image->pixelFormat(), (GLenum)_image->dataType(), _image->data() ); } } <|endoftext|>
<commit_before><commit_msg>AA_EnableHighDpiScaling and friends only work in Qt 5.6+<commit_after><|endoftext|>
<commit_before><commit_msg>arch-arm: Fix codying style in TableWalker descriptors<commit_after><|endoftext|>
<commit_before>/* * dialer - MeeGo Voice Call Manager * Copyright (c) 2009, 2010, Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 * */ #include "common.h" #include "mainwindow.h" #include "dialerapplication.h" #include "managerproxy.h" #include "genericpage.h" #include <MDialog> #include <MImageWidget> #include <MButton> #include <MLabel> #include <MLayout> #include <MGridLayoutPolicy> #include <MStylableWidget> #include <MNotification> #include <MToolBar> #include <QDateTime> #include "dialer_adaptor.h" MainWindow::MainWindow() : MApplicationWindow(), m_lastPage(0), m_alert(new AlertDialog()), m_notification(new NotificationDialog()), m_keypad(0), m_acceptAction(DBUS_SERVICE, DBUS_SERVICE_PATH, DBUS_SERVICE, "accept"), m_incomingCall(0), m_tbd(0) { new DialerAdaptor(this); QDBusConnection connection = QDBusConnection::sessionBus(); if(!connection.registerObject(DBUS_SERVICE_PATH,this)){ qCritical()<<"Error registering dbus object: "<< connection.lastError().message(); } TRACE if (orientation() != M::Portrait) setOrientationAngle(M::Angle270); // TODO: If we *REALLY* only support portrait, need to uncomment next line setOrientationLocked(true); setToolbarViewType(MToolBar::tabType); m_pages.clear(); } void MainWindow::showDebugPage() { TRACE if (currentPage() == m_pages.at(GenericPage::PAGE_DEBUG)) { if (m_lastPage) m_lastPage->appear(); else m_pages.at(GenericPage::PAGE_DEBUG)->disappear(); } else { m_lastPage = currentPage(); m_pages.at(GenericPage::PAGE_DEBUG)->appear(); } } void MainWindow::handleIncomingCall(CallItem *call) { TRACE qDebug("Handling an incoming call..."); if (isOnDisplay()) { m_alert->setCallItem(call); m_alert->appear(); } else { QString name; QString photo = DEFAULT_AVATAR_ICON; //% "Private" QString lineid = qtTrId("xx_private"); //% "Incoming call" QString summary(qtTrId("xx_incoming_call")); QString body; MNotification notice(NOTIFICATION_CALL_EVENT); if (call && call->isValid() && !call->lineID().isEmpty()) { lineid = stripLineID(call->lineID()); SeasideSyncModel *contacts = DA_SEASIDEMODEL; QModelIndex first = contacts->index(0,Seaside::ColumnPhoneNumbers); QModelIndexList matches = contacts->match(first, Qt::DisplayRole, QVariant(lineid),1); if (!matches.isEmpty()) { QModelIndex person = matches.at(0); //First match wins SEASIDE_SHORTCUTS SEASIDE_SET_MODEL_AND_ROW(person.model(), person.row()); QString firstName = SEASIDE_FIELD(FirstName, String); QString lastName = SEASIDE_FIELD(LastName, String); if (lastName.isEmpty()) // Contacts first (common) name //% "%1" name = qtTrId("xx_first_name").arg(firstName); else // Contacts full, sortable name, is "Lastname, Firstname" //% "%1, %2" name = qtTrId("xx_full_name").arg(lastName).arg(firstName); photo = SEASIDE_FIELD(Avatar, String); } // Save this for when RemoteAction "accept" is called, but make sure // we null it out if the state changes before user takes action m_incomingCall = call; connect(m_incomingCall,SIGNAL(stateChanged()),SLOT(callStateChanged())); } else { //% "Unavailable" lineid = qtTrId("xx_unavailable"); } //% "You have an incoming call from %1" body = QString(qtTrId("xx_incoming_body")) .arg(name.isEmpty()?lineid:name); notice.setSummary(summary); notice.setBody(body); notice.setImage(photo); notice.setAction(m_acceptAction); notice.publish(); qDebug() << QString("%1: %2").arg(summary).arg(body); } } void MainWindow::handleResourceUnavailability(const QString message) { TRACE DialerApplication *app = DialerApplication::instance(); if (isOnDisplay()) { m_notification->setNotification(message); m_notification->appear(); } } void MainWindow::callStateChanged() { TRACE if (m_incomingCall && m_incomingCall->isValid()) { disconnect(m_incomingCall, SIGNAL(stateChanged())); m_incomingCall = NULL; } } void MainWindow::call(QString no) { TRACE m_lastPage = currentPage(); if(!m_pages.size()) { qDebug("DialerPage probably hasn't been created yet."); return; } m_pages.at(GenericPage::PAGE_DIALER)->appear(); ManagerProxy *mp = ManagerProxy::instance(); if(!mp->callManager()->isValid()) return; mp->callManager()->dial(no); showMaximized(); } void MainWindow::accept() { TRACE if (!m_incomingCall || !m_incomingCall->isValid()) return; // A call is "waiting" if there is an active call already and a new // call comes in. This is handled by the call manager object instead if (m_incomingCall->state() == CallItemModel::STATE_WAITING) { CallManager *cm = ManagerProxy::instance()->callManager(); if (cm && cm->isValid()) cm->holdAndAnswer(); else qCritical("CallManager is invalid, cannot answer waiting calls"); } else { m_incomingCall->callProxy()->answer(); } // Switch to the dialer page where call views are shown if(m_pages.size()) m_pages.at(GenericPage::PAGE_DIALER)->appear(); showMaximized(); } void MainWindow::showTBD() { TRACE if (!m_tbd) //% "This feature is not yet implemented" m_tbd = new MMessageBox(qtTrId("xx_not_yet_implemented")); m_tbd->exec(this); } void MainWindow::simulateIncomingCall() { TRACE ManagerProxy *mp = ManagerProxy::instance(); qDebug("Dialing \"199\" to trigger phonesim to simulate an incoming call"); if (mp->isValid() && mp->callManager() && mp->callManager()->isValid()) mp->callManager()->dial("199"); // Invoke phonesim dialBack() } bool MainWindow::event(QEvent *event) { TRACE if (QEvent::KeyPress == event->type()) { QKeyEvent *kev = (QKeyEvent *)event; // Trap "F1" as trigger to show debug/info page if (Qt::Key_F1 == kev->key()) { MainWindow::showDebugPage(); return true; // Trap "F10" as trigger to simulate an incoming call event } else if (Qt::Key_F10 == kev->key()) { MainWindow::simulateIncomingCall(); return true; } } return MApplicationWindow::event(event); } DialerKeyPad *MainWindow::keypad() { TRACE if (!m_keypad) { m_keypad = new DialerKeyPad(); m_keypad->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); } return m_keypad; } <commit_msg>Fixed: BMC# 14321 - The whole dialer UI will move down ...<commit_after>/* * dialer - MeeGo Voice Call Manager * Copyright (c) 2009, 2010, Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 * */ #include "common.h" #include "mainwindow.h" #include "dialerapplication.h" #include "managerproxy.h" #include "genericpage.h" #include <MDialog> #include <MImageWidget> #include <MButton> #include <MLabel> #include <MLayout> #include <MGridLayoutPolicy> #include <MStylableWidget> #include <MNotification> #include <MToolBar> #include <QDateTime> #include "dialer_adaptor.h" MainWindow::MainWindow() : MApplicationWindow(), m_lastPage(0), m_alert(new AlertDialog()), m_notification(new NotificationDialog()), m_keypad(0), m_acceptAction(DBUS_SERVICE, DBUS_SERVICE_PATH, DBUS_SERVICE, "accept"), m_incomingCall(0), m_tbd(0) { new DialerAdaptor(this); QDBusConnection connection = QDBusConnection::sessionBus(); if(!connection.registerObject(DBUS_SERVICE_PATH,this)){ qCritical()<<"Error registering dbus object: "<< connection.lastError().message(); } TRACE if (orientation() != M::Portrait) setPortraitOrientation(); setOrientationLocked(true); setToolbarViewType(MToolBar::tabType); m_pages.clear(); } void MainWindow::showDebugPage() { TRACE if (currentPage() == m_pages.at(GenericPage::PAGE_DEBUG)) { if (m_lastPage) m_lastPage->appear(); else m_pages.at(GenericPage::PAGE_DEBUG)->disappear(); } else { m_lastPage = currentPage(); m_pages.at(GenericPage::PAGE_DEBUG)->appear(); } } void MainWindow::handleIncomingCall(CallItem *call) { TRACE qDebug("Handling an incoming call..."); if (isOnDisplay()) { m_alert->setCallItem(call); m_alert->appear(); } else { QString name; QString photo = DEFAULT_AVATAR_ICON; //% "Private" QString lineid = qtTrId("xx_private"); //% "Incoming call" QString summary(qtTrId("xx_incoming_call")); QString body; MNotification notice(NOTIFICATION_CALL_EVENT); if (call && call->isValid() && !call->lineID().isEmpty()) { lineid = stripLineID(call->lineID()); SeasideSyncModel *contacts = DA_SEASIDEMODEL; QModelIndex first = contacts->index(0,Seaside::ColumnPhoneNumbers); QModelIndexList matches = contacts->match(first, Qt::DisplayRole, QVariant(lineid),1); if (!matches.isEmpty()) { QModelIndex person = matches.at(0); //First match wins SEASIDE_SHORTCUTS SEASIDE_SET_MODEL_AND_ROW(person.model(), person.row()); QString firstName = SEASIDE_FIELD(FirstName, String); QString lastName = SEASIDE_FIELD(LastName, String); if (lastName.isEmpty()) // Contacts first (common) name //% "%1" name = qtTrId("xx_first_name").arg(firstName); else // Contacts full, sortable name, is "Lastname, Firstname" //% "%1, %2" name = qtTrId("xx_full_name").arg(lastName).arg(firstName); photo = SEASIDE_FIELD(Avatar, String); } // Save this for when RemoteAction "accept" is called, but make sure // we null it out if the state changes before user takes action m_incomingCall = call; connect(m_incomingCall,SIGNAL(stateChanged()),SLOT(callStateChanged())); } else { //% "Unavailable" lineid = qtTrId("xx_unavailable"); } //% "You have an incoming call from %1" body = QString(qtTrId("xx_incoming_body")) .arg(name.isEmpty()?lineid:name); notice.setSummary(summary); notice.setBody(body); notice.setImage(photo); notice.setAction(m_acceptAction); notice.publish(); qDebug() << QString("%1: %2").arg(summary).arg(body); } } void MainWindow::handleResourceUnavailability(const QString message) { TRACE DialerApplication *app = DialerApplication::instance(); if (isOnDisplay()) { m_notification->setNotification(message); m_notification->appear(); } } void MainWindow::callStateChanged() { TRACE if (m_incomingCall && m_incomingCall->isValid()) { disconnect(m_incomingCall, SIGNAL(stateChanged())); m_incomingCall = NULL; } } void MainWindow::call(QString no) { TRACE m_lastPage = currentPage(); if(!m_pages.size()) { qDebug("DialerPage probably hasn't been created yet."); return; } m_pages.at(GenericPage::PAGE_DIALER)->appear(); ManagerProxy *mp = ManagerProxy::instance(); if(!mp->callManager()->isValid()) return; mp->callManager()->dial(no); showMaximized(); } void MainWindow::accept() { TRACE if (!m_incomingCall || !m_incomingCall->isValid()) return; // A call is "waiting" if there is an active call already and a new // call comes in. This is handled by the call manager object instead if (m_incomingCall->state() == CallItemModel::STATE_WAITING) { CallManager *cm = ManagerProxy::instance()->callManager(); if (cm && cm->isValid()) cm->holdAndAnswer(); else qCritical("CallManager is invalid, cannot answer waiting calls"); } else { m_incomingCall->callProxy()->answer(); } // Switch to the dialer page where call views are shown if(m_pages.size()) m_pages.at(GenericPage::PAGE_DIALER)->appear(); showMaximized(); } void MainWindow::showTBD() { TRACE if (!m_tbd) //% "This feature is not yet implemented" m_tbd = new MMessageBox(qtTrId("xx_not_yet_implemented")); m_tbd->exec(this); } void MainWindow::simulateIncomingCall() { TRACE ManagerProxy *mp = ManagerProxy::instance(); qDebug("Dialing \"199\" to trigger phonesim to simulate an incoming call"); if (mp->isValid() && mp->callManager() && mp->callManager()->isValid()) mp->callManager()->dial("199"); // Invoke phonesim dialBack() } bool MainWindow::event(QEvent *event) { TRACE if (QEvent::KeyPress == event->type()) { QKeyEvent *kev = (QKeyEvent *)event; // Trap "F1" as trigger to show debug/info page if (Qt::Key_F1 == kev->key()) { MainWindow::showDebugPage(); return true; // Trap "F10" as trigger to simulate an incoming call event } else if (Qt::Key_F10 == kev->key()) { MainWindow::simulateIncomingCall(); return true; } } return MApplicationWindow::event(event); } DialerKeyPad *MainWindow::keypad() { TRACE if (!m_keypad) { m_keypad = new DialerKeyPad(); m_keypad->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); } return m_keypad; } <|endoftext|>
<commit_before>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT 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. */ /* HIT_START * BUILD: %t %s ../../test_common.cpp * RUN: %t --tests 0x1 * RUN: %t --tests 0x2 * HIT_END */ // TODO - bug if run both back-to-back #include"test_common.h" #include<malloc.h> __global__ void Inc(hipLaunchParm lp, float *Ad){ int tx = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x; Ad[tx] = Ad[tx] + float(1); } template<typename T> void doMemCopy(size_t numElements, int offset, T *A, T *Bh, T *Bd) { A = A + offset; numElements -= offset; size_t sizeBytes = numElements * sizeof(T); HIPCHECK(hipHostRegister(A, sizeBytes, 0)); // Reset for(size_t i=0;i<numElements;i++){ A[i] = float(i); Bh[i] = 0.0f; } HIPCHECK(hipMemset(Bd, 13.0f, sizeBytes)); // HIPCHECK(hipMemcpy(Bd, A, sizeBytes, hipMemcpyHostToDevice)); HIPCHECK(hipMemcpy(Bh, Bd, sizeBytes, hipMemcpyDeviceToHost)); // Make sure the copy worked for(size_t i=0;i<numElements;i++){ if (Bh[i] != A[i]) { printf ("mismatch at Bh[%zu]=%f, A[%zu]=%f\n", i, Bh[i], i, A[i]); failed("mismatch"); }; } HIPCHECK(hipHostUnregister(A)); } int main(int argc, char *argv[]) { HipTest::parseStandardArguments(argc, argv, true); const size_t size = N * sizeof(float); if (p_tests & 0x1) { float *A, **Ad; int num_devices; HIPCHECK(hipGetDeviceCount(&num_devices)); Ad = new float*[num_devices]; A = (float*)malloc(size); HIPCHECK(hipHostRegister(A, size, 0)); for(int i=0;i<N;i++){ A[i] = float(1); } for(int i=0;i<num_devices;i++){ HIPCHECK(hipSetDevice(i)); HIPCHECK(hipHostGetDevicePointer((void**)&Ad[i], A, 0)); } // Reference the registered device pointer Ad from inside the kernel: for(int i=0;i<num_devices;i++){ HIPCHECK(hipSetDevice(i)); hipLaunchKernel(Inc, dim3(N/512), dim3(512), 0, 0, Ad[i]); HIPCHECK(hipDeviceSynchronize()); } HIPASSERT(A[10] == 1.0f + float(num_devices)); HIPCHECK(hipHostUnregister(A)); free (A); } if (p_tests & 0x2) { // Sensitize HIP bug if device does not match where the memory was registered. HIPCHECK(hipSetDevice(0)); float * A = (float*)malloc(size); // Copy to B, this should be optimal pinned malloc copy: // Note we are using the host pointer here: float *Bh, *Bd; Bh = (float*)malloc(size); HIPCHECK(hipMalloc(&Bd, size)); // TODO - change to 256: #define OFFSETS_TO_TRY 1 assert (N>OFFSETS_TO_TRY); for (size_t i=0; i<OFFSETS_TO_TRY; i++) { doMemCopy(N, i, A, Bh, Bd); } free (A); } passed(); } <commit_msg>Refactor hipHostRegister test.<commit_after>/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT 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. */ /* HIT_START * BUILD: %t %s ../../test_common.cpp * RUN: %t --tests 0x1 * RUN: %t --tests 0x2 * RUN: %t --tests 0x4 * HIT_END */ // TODO - bug if run both back-to-back, once fixed should just need one command line #include"test_common.h" #include<malloc.h> __global__ void Inc(hipLaunchParm lp, float *Ad){ int tx = hipThreadIdx_x + hipBlockIdx_x * hipBlockDim_x; Ad[tx] = Ad[tx] + float(1); } template<typename T> void doMemCopy(size_t numElements, int offset, T *A, T *Bh, T *Bd, bool internalRegister) { A = A + offset; numElements -= offset; size_t sizeBytes = numElements * sizeof(T); if (internalRegister) { HIPCHECK(hipHostRegister(A, sizeBytes, 0)); } // Reset for(size_t i=0;i<numElements;i++){ A[i] = float(i); Bh[i] = 0.0f; } HIPCHECK(hipMemset(Bd, 13.0f, sizeBytes)); // HIPCHECK(hipMemcpy(Bd, A, sizeBytes, hipMemcpyHostToDevice)); HIPCHECK(hipMemcpy(Bh, Bd, sizeBytes, hipMemcpyDeviceToHost)); // Make sure the copy worked for(size_t i=0;i<numElements;i++){ if (Bh[i] != A[i]) { printf ("mismatch at Bh[%zu]=%f, A[%zu]=%f\n", i, Bh[i], i, A[i]); failed("mismatch"); }; } if (internalRegister) { HIPCHECK(hipHostUnregister(A)); } } int main(int argc, char *argv[]) { HipTest::parseStandardArguments(argc, argv, true); const size_t size = N * sizeof(float); if (p_tests & 0x1) { float *A, **Ad; int num_devices; HIPCHECK(hipGetDeviceCount(&num_devices)); Ad = new float*[num_devices]; A = (float*)malloc(size); HIPCHECK(hipHostRegister(A, size, 0)); for(int i=0;i<N;i++){ A[i] = float(1); } for(int i=0;i<num_devices;i++){ HIPCHECK(hipSetDevice(i)); HIPCHECK(hipHostGetDevicePointer((void**)&Ad[i], A, 0)); } // Reference the registered device pointer Ad from inside the kernel: for(int i=0;i<num_devices;i++){ HIPCHECK(hipSetDevice(i)); hipLaunchKernel(Inc, dim3(N/512), dim3(512), 0, 0, Ad[i]); HIPCHECK(hipDeviceSynchronize()); } HIPASSERT(A[10] == 1.0f + float(num_devices)); HIPCHECK(hipHostUnregister(A)); free (A); } if (p_tests & 0x6) { // Sensitize HIP bug if device does not match where the memory was registered. HIPCHECK(hipSetDevice(0)); float * A = (float*)malloc(size); // Copy to B, this should be optimal pinned malloc copy: // Note we are using the host pointer here: float *Bh, *Bd; Bh = (float*)malloc(size); HIPCHECK(hipMalloc(&Bd, size)); // TODO - set to 128 #define OFFSETS_TO_TRY 1 assert (N>OFFSETS_TO_TRY); if (p_tests & 0x2) { for (size_t i=0; i<OFFSETS_TO_TRY; i++) { doMemCopy(N, i, A, Bh, Bd, true/*internalRegister*/); } } if (p_tests & 0x4) { HIPCHECK(hipHostRegister(A, size, 0)); for (size_t i=0; i<OFFSETS_TO_TRY; i++) { doMemCopy(N, i, A, Bh, Bd, false/*internalRegister*/); } HIPCHECK(hipHostUnregister(A)); } free (A); } passed(); } <|endoftext|>
<commit_before>/* Copyright (c) 2014-2015 DataStax 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. */ /* Implementation of Dmitry Vyukov's MPMC algorithm http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue */ #ifndef __CASS_MPMC_QUEUE_INCLUDED__ #define __CASS_MPMC_QUEUE_INCLUDED__ #include "atomic.hpp" #include "utils.hpp" #include "macros.hpp" #include <assert.h> namespace cass { template <typename T> class MPMCQueue { public: typedef T EntryType; MPMCQueue(size_t size) : size_(next_pow_2(size)) , mask_(size_ - 1) , buffer_(new Node[size_]) , tail_(0) , head_(0) { // populate the sequence initial values for (size_t i = 0; i < size_; ++i) { buffer_[i].seq.store(i, MEMORY_ORDER_RELAXED); } } ~MPMCQueue() { delete[] buffer_; } bool enqueue(const T& data) { // head_seq_ only wraps at MAX(head_seq_) instead we use a mask to // convert the sequence to an array index this is why the ring // buffer must be a size which is a power of 2. this also allows // the sequence to double as a ticket/lock. size_t pos = tail_.load(MEMORY_ORDER_RELAXED); for (;;) { Node* node = &buffer_[pos & mask_]; size_t node_seq = node->seq.load(MEMORY_ORDER_ACQUIRE); intptr_t dif = (intptr_t)node_seq - (intptr_t)pos; // if seq and head_seq are the same then it means this slot is empty if (dif == 0) { // claim our spot by moving head if head isn't the same as we // last checked then that means someone beat us to the punch // weak compare is faster, but can return spurious results // which in this instance is OK, because it's in the loop if (tail_.compare_exchange_weak(pos, pos + 1, MEMORY_ORDER_RELAXED)) { // set the data node->data = data; // increment the sequence so that the tail knows it's accessible node->seq.store(pos + 1, MEMORY_ORDER_RELEASE); return true; } } else if (dif < 0) { // if seq is less than head seq then it means this slot is // full and therefore the buffer is full return false; } else { // under normal circumstances this branch should never be taken pos = tail_.load(MEMORY_ORDER_RELAXED); } } // never taken return false; } bool dequeue(T& data) { size_t pos = head_.load(MEMORY_ORDER_RELAXED); for (;;) { Node* node = &buffer_[pos & mask_]; size_t node_seq = node->seq.load(MEMORY_ORDER_ACQUIRE); intptr_t dif = (intptr_t)node_seq - (intptr_t)(pos + 1); // if seq and head_seq are the same then it means this slot is empty if (dif == 0) { // claim our spot by moving head if head isn't the same as we // last checked then that means someone beat us to the punch // weak compare is faster, but can return spurious results // which in this instance is OK, because it's in the loop if (head_.compare_exchange_weak(pos, pos + 1, MEMORY_ORDER_RELAXED)) { // set the output data = node->data; // set the sequence to what the head sequence should be next // time around node->seq.store(pos + mask_ + 1, MEMORY_ORDER_RELEASE); return true; } } else if (dif < 0) { // if seq is less than head seq then it means this slot is // full and therefore the buffer is full return false; } else { // under normal circumstances this branch should never be taken pos = head_.load(MEMORY_ORDER_RELAXED); } } // never taken return false; } bool is_empty() const { size_t pos = head_.load(MEMORY_ORDER_ACQUIRE); Node* node = &buffer_[pos & mask_]; size_t node_seq = node->seq.load(MEMORY_ORDER_ACQUIRE); return (intptr_t)node_seq - (intptr_t)(pos + 1) < 0; } static void memory_fence() { #if defined(__x86_64__) || defined(_M_X64) || defined(__i386) || defined(_M_IX86) // No fence required becauase compare_exchange_weak() emits "lock cmpxchg" on x86/x64 enforcing total order. #elif defined(CASS_USE_BOOST_ATOMIC) || defined(CASS_USE_STD_ATOMIC) atomic_thread_fence(MEMORY_ORDER_SEQ_CST); #endif } private: struct Node { Atomic<size_t> seq; T data; }; // it's either 32 or 64 so 64 is good enough typedef char CachePad[64]; CachePad pad0_; const size_t size_; const size_t mask_; Node* const buffer_; CachePad pad1_; Atomic<size_t> tail_; CachePad pad2_; Atomic<size_t> head_; CachePad pad3_; DISALLOW_COPY_AND_ASSIGN(MPMCQueue); }; } // namespace cass #endif <commit_msg>MPMC queue should emit a memory fence on x86/x64<commit_after>/* Copyright (c) 2014-2015 DataStax 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. */ /* Implementation of Dmitry Vyukov's MPMC algorithm http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue */ #ifndef __CASS_MPMC_QUEUE_INCLUDED__ #define __CASS_MPMC_QUEUE_INCLUDED__ #include "atomic.hpp" #include "utils.hpp" #include "macros.hpp" #include <assert.h> namespace cass { template <typename T> class MPMCQueue { public: typedef T EntryType; MPMCQueue(size_t size) : size_(next_pow_2(size)) , mask_(size_ - 1) , buffer_(new Node[size_]) , tail_(0) , head_(0) { // populate the sequence initial values for (size_t i = 0; i < size_; ++i) { buffer_[i].seq.store(i, MEMORY_ORDER_RELAXED); } } ~MPMCQueue() { delete[] buffer_; } bool enqueue(const T& data) { // head_seq_ only wraps at MAX(head_seq_) instead we use a mask to // convert the sequence to an array index this is why the ring // buffer must be a size which is a power of 2. this also allows // the sequence to double as a ticket/lock. size_t pos = tail_.load(MEMORY_ORDER_RELAXED); for (;;) { Node* node = &buffer_[pos & mask_]; size_t node_seq = node->seq.load(MEMORY_ORDER_ACQUIRE); intptr_t dif = (intptr_t)node_seq - (intptr_t)pos; // if seq and head_seq are the same then it means this slot is empty if (dif == 0) { // claim our spot by moving head if head isn't the same as we // last checked then that means someone beat us to the punch // weak compare is faster, but can return spurious results // which in this instance is OK, because it's in the loop if (tail_.compare_exchange_weak(pos, pos + 1, MEMORY_ORDER_RELAXED)) { // set the data node->data = data; // increment the sequence so that the tail knows it's accessible node->seq.store(pos + 1, MEMORY_ORDER_RELEASE); return true; } } else if (dif < 0) { // if seq is less than head seq then it means this slot is // full and therefore the buffer is full return false; } else { // under normal circumstances this branch should never be taken pos = tail_.load(MEMORY_ORDER_RELAXED); } } // never taken return false; } bool dequeue(T& data) { size_t pos = head_.load(MEMORY_ORDER_RELAXED); for (;;) { Node* node = &buffer_[pos & mask_]; size_t node_seq = node->seq.load(MEMORY_ORDER_ACQUIRE); intptr_t dif = (intptr_t)node_seq - (intptr_t)(pos + 1); // if seq and head_seq are the same then it means this slot is empty if (dif == 0) { // claim our spot by moving head if head isn't the same as we // last checked then that means someone beat us to the punch // weak compare is faster, but can return spurious results // which in this instance is OK, because it's in the loop if (head_.compare_exchange_weak(pos, pos + 1, MEMORY_ORDER_RELAXED)) { // set the output data = node->data; // set the sequence to what the head sequence should be next // time around node->seq.store(pos + mask_ + 1, MEMORY_ORDER_RELEASE); return true; } } else if (dif < 0) { // if seq is less than head seq then it means this slot is // full and therefore the buffer is full return false; } else { // under normal circumstances this branch should never be taken pos = head_.load(MEMORY_ORDER_RELAXED); } } // never taken return false; } bool is_empty() const { size_t pos = head_.load(MEMORY_ORDER_ACQUIRE); Node* node = &buffer_[pos & mask_]; size_t node_seq = node->seq.load(MEMORY_ORDER_ACQUIRE); return (intptr_t)node_seq - (intptr_t)(pos + 1) < 0; } static void memory_fence() { #if defined(CASS_USE_BOOST_ATOMIC) || defined(CASS_USE_STD_ATOMIC) atomic_thread_fence(MEMORY_ORDER_SEQ_CST); #endif } private: struct Node { Atomic<size_t> seq; T data; }; // it's either 32 or 64 so 64 is good enough typedef char CachePad[64]; CachePad pad0_; const size_t size_; const size_t mask_; Node* const buffer_; CachePad pad1_; Atomic<size_t> tail_; CachePad pad2_; Atomic<size_t> head_; CachePad pad3_; DISALLOW_COPY_AND_ASSIGN(MPMCQueue); }; } // namespace cass #endif <|endoftext|>
<commit_before>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #define _USE_MATH_DEFINES #include <math.h> #include "renderer.hpp" Renderer::Renderer(std::shared_ptr<Scene> scene) : scene_{scene}, colorbuffer_(scene->camera.xres()*scene->camera.yres(), Color{}), //scene-> quivalent zu (*scene). ppm_(scene->camera.xres(), scene->camera.yres(), scene->filename) {} /*void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < scene_->camera.yres(); ++y) { for (unsigned x = 0; x < scene_->camera.xres(); ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x) / scene_->camera.yres()); } else { p.color = Color(1.0, 0.0, float(y) / scene_->camera.xres()); } write(p); } } ppm_.save(); }*/ void Renderer::render() { unsigned z = (scene_->camera.xres()/2)/(tan(scene_->camera.fovx()/360 * M_PI)); for (unsigned y = 0; y < scene_->camera.yres(); ++y) { for (unsigned x = 0; x < scene_->camera.xres(); ++x) { glm::vec3 direction (-scene_->camera.xres()/2-0.5+x, -scene_->camera.yres()/2-0.5+y, z); Ray ray = scene_->camera.castray(direction); for (std::vector<std::shared_ptr<Shape>>::iterator i =scene_->shapes_ptr.begin();i != scene_->shapes_ptr.end();++i){ *scene_->shapes_ptr[0].intersect(ray); } Pixel p(x,y); write(p); } } ppm_.save(); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (scene_->camera.xres()*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } <commit_msg>structuring code<commit_after>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #define _USE_MATH_DEFINES #include <math.h> #include "renderer.hpp" Renderer::Renderer(std::shared_ptr<Scene> scene) : scene_{scene}, colorbuffer_(scene->camera.xres()*scene->camera.yres(), Color{}), //scene-> quivalent zu (*scene). ppm_(scene->camera.xres(), scene->camera.yres(), scene->filename) {} /*void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < scene_->camera.yres(); ++y) { for (unsigned x = 0; x < scene_->camera.xres(); ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x) / scene_->camera.yres()); } else { p.color = Color(1.0, 0.0, float(y) / scene_->camera.xres()); } write(p); } } ppm_.save(); }*/ void Renderer::render() { unsigned z = (scene_->camera.xres()/2)/(tan(scene_->camera.fovx()/360 * M_PI)); for (unsigned y = 0; y < scene_->camera.yres(); ++y) { for (unsigned x = 0; x < scene_->camera.xres(); ++x) { glm::vec3 direction (-scene_->camera.xres()/2-0.5+x, -scene_->camera.yres()/2-0.5+y, z); Ray ray = scene_->camera.castray(direction); for (std::vector<std::shared_ptr<Shape>>::iterator i =scene_->shapes_ptr.begin();i != scene_->shapes_ptr.end();++i){ *scene_->shapes_ptr[0].intersect(ray); } Pixel p(x,y); write(p); } } ppm_.save(); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (scene_->camera.xres()*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/ThreadPool.h" #include <cassert> #include <functional> #include "joynr/Runnable.h" namespace joynr { INIT_LOGGER(ThreadPool); ThreadPool::ThreadPool(const std::string& /*name*/, std::uint8_t numberOfThreads) : threads(), scheduler(), keepRunning(true), currentlyRunning(), mutex() { for (std::uint8_t i = 0; i < numberOfThreads; ++i) { threads.emplace_back(std::bind(&ThreadPool::threadLifecycle, this)); } #if 0 // This is not working in g_SystemIntegrationTests #ifdef linux if (name.c_str() != nullptr) { for (auto thread = threads.begin(); thread != threads.end(); ++thread) { pthread_setname_np(thread->native_handle(), name.c_str()); } } #endif #endif } ThreadPool::~ThreadPool() { shutdown(); assert(keepRunning == false); assert(threads.empty()); } void ThreadPool::shutdown() { keepRunning = false; // Signal scheduler that pending Runnables will not be // taken by this ThreadPool scheduler.shutdown(); { std::lock_guard<std::mutex> lock(mutex); for (Runnable* runnable : currentlyRunning) { runnable->shutdown(); } } for (auto thread = threads.begin(); thread != threads.end(); ++thread) { if (thread->joinable()) { thread->join(); } } threads.clear(); // Runnables should be cleaned in the thread loop assert(currentlyRunning.size() == 0); } bool ThreadPool::isRunning() { return keepRunning; } void ThreadPool::execute(Runnable* runnable) { scheduler.add(runnable); } void ThreadPool::threadLifecycle() { JOYNR_LOG_TRACE(logger, "Thread enters lifecycle"); while (keepRunning) { JOYNR_LOG_TRACE(logger, "Thread is waiting"); // Take a runnable Runnable* runnable = scheduler.take(); if (runnable != nullptr) { JOYNR_LOG_TRACE(logger, "Thread got runnable and will do work"); // Add runnable to the queue of currently running context { std::lock_guard<std::mutex> lock(mutex); if (!keepRunning) { // Call Dtor of runnable if needed if (runnable->isDeleteOnExit()) { delete runnable; } break; } currentlyRunning.insert(runnable); } // Run the runnable runnable->run(); JOYNR_LOG_TRACE(logger, "Thread finished work"); { std::lock_guard<std::mutex> lock(mutex); currentlyRunning.erase(runnable); } // Call Dtor of runnable if needed if (runnable->isDeleteOnExit()) { delete runnable; } } } JOYNR_LOG_TRACE(logger, "Thread leaves lifecycle"); } } // namespace joynr <commit_msg>[C++] Don't try to join own thread in ThreadPool<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/ThreadPool.h" #include <cassert> #include <functional> #include <set> #include "joynr/Runnable.h" namespace joynr { INIT_LOGGER(ThreadPool); ThreadPool::ThreadPool(const std::string& /*name*/, std::uint8_t numberOfThreads) : threads(), scheduler(), keepRunning(true), currentlyRunning(), mutex() { for (std::uint8_t i = 0; i < numberOfThreads; ++i) { threads.emplace_back(std::bind(&ThreadPool::threadLifecycle, this)); } #if 0 // This is not working in g_SystemIntegrationTests #ifdef linux if (name.c_str() != nullptr) { for (auto thread = threads.begin(); thread != threads.end(); ++thread) { pthread_setname_np(thread->native_handle(), name.c_str()); } } #endif #endif } ThreadPool::~ThreadPool() { if (keepRunning) { shutdown(); } assert(keepRunning == false); assert(threads.empty()); } void ThreadPool::shutdown() { keepRunning = false; // Signal scheduler that pending Runnables will not be // taken by this ThreadPool scheduler.shutdown(); { std::lock_guard<std::mutex> lock(mutex); for (Runnable* runnable : currentlyRunning) { runnable->shutdown(); } } std::set<Runnable*>::size_type maxRunning = 0; for (auto thread = threads.begin(); thread != threads.end(); ++thread) { // do not cause an abort waiting for ourselves if (std::this_thread::get_id() == thread->get_id()) { thread->detach(); maxRunning = 1; } else if (thread->joinable()) { thread->join(); } } threads.clear(); { std::lock_guard<std::mutex> lock(mutex); // Runnables should be cleaned in the thread loop // except for the thread that runs this code in case // it was part of the ThreadPool assert(currentlyRunning.size() <= maxRunning); } } bool ThreadPool::isRunning() { return keepRunning; } void ThreadPool::execute(Runnable* runnable) { scheduler.add(runnable); } void ThreadPool::threadLifecycle() { JOYNR_LOG_TRACE(logger, "Thread enters lifecycle"); while (keepRunning) { JOYNR_LOG_TRACE(logger, "Thread is waiting"); // Take a runnable Runnable* runnable = scheduler.take(); if (runnable != nullptr) { JOYNR_LOG_TRACE(logger, "Thread got runnable and will do work"); // Add runnable to the queue of currently running context { std::lock_guard<std::mutex> lock(mutex); if (!keepRunning) { // Call Dtor of runnable if needed if (runnable->isDeleteOnExit()) { delete runnable; } break; } currentlyRunning.insert(runnable); } // Run the runnable runnable->run(); JOYNR_LOG_TRACE(logger, "Thread finished work"); { std::lock_guard<std::mutex> lock(mutex); currentlyRunning.erase(runnable); } // Call Dtor of runnable if needed if (runnable->isDeleteOnExit()) { delete runnable; } } } JOYNR_LOG_TRACE(logger, "Thread leaves lifecycle"); } } // namespace joynr <|endoftext|>
<commit_before>/* * */ #ifndef BASH_HANDLE_HPP #define BASH_HANDLE_HPP #include <atomic> #include <condition_variable> #include <list> #include <mutex> // #include "unix/codec.hpp" #include "unix/condition-queue.hpp" #include "unix/refsymbol.hpp" #include "unix/request.hpp" #include "unix/response.hpp" #include "bash-queue.hpp" #include "mcu-queue.hpp" #include "mcu-msg.hpp" #include "render.hpp" namespace led_d { class bash_handle_t { public: bash_handle_t (const std::string &default_font); bash_handle_t (const bash_handle_t&) = delete; ~bash_handle_t () {}; void start (); void stop (); bash_queue_t& bash_queue () {return m_bash_queue;} mcu_queue_t& from_mcu_queue () {return m_from_mcu_queue;} void to_mcu_queue (mcu_queue_t &to_mcu_queue) {m_to_mcu_queue = &to_mcu_queue;} private: using refsymbol_t = unix::refsymbol_t; using request_t = unix::request_t; using response_t = unix::response_t; // using codec_t = unix::codec_t<refsymbol_t>; void notify (); void handle_bash (std::string msg); void handle_mcu (mcu_msg_t &msg); // handle mcu messages void mcu_version (const mcu_msg_t &msg); void mcu_poll (); // handle unix messages bool unix_insert (const request_t &request); std::mutex m_mutex; std::condition_variable m_condition; bash_queue_t m_bash_queue; mcu_queue_t m_from_mcu_queue; mcu_queue_t *m_to_mcu_queue; //content_t &m_content; render_t m_render; std::atomic_bool m_go; // special client, that consumes mcu messages like // button presses. // !!! Can be zero // session_ptr_t m_client; }; } // namespace led_d #endif <commit_msg>github: Test key 2<commit_after>/* * */ #ifndef BASH_HANDLE_HPP #define BASH_HANDLE_HPP #include <atomic> #include <condition_variable> #include <list> #include <mutex> // #include "unix/codec.hpp" #include "unix/condition-queue.hpp" // #include "unix/refsymbol.hpp" #include "unix/request.hpp" #include "unix/response.hpp" #include "bash-queue.hpp" #include "mcu-queue.hpp" #include "mcu-msg.hpp" #include "render.hpp" namespace led_d { class bash_handle_t { public: bash_handle_t (const std::string &default_font); bash_handle_t (const bash_handle_t&) = delete; ~bash_handle_t () {}; void start (); void stop (); bash_queue_t& bash_queue () {return m_bash_queue;} mcu_queue_t& from_mcu_queue () {return m_from_mcu_queue;} void to_mcu_queue (mcu_queue_t &to_mcu_queue) {m_to_mcu_queue = &to_mcu_queue;} private: // using refsymbol_t = unix::refsymbol_t; using request_t = unix::request_t; using response_t = unix::response_t; // using codec_t = unix::codec_t<refsymbol_t>; void notify (); void handle_bash (std::string msg); void handle_mcu (mcu_msg_t &msg); // handle mcu messages void mcu_version (const mcu_msg_t &msg); void mcu_poll (); // handle unix messages bool unix_insert (const request_t &request); std::mutex m_mutex; std::condition_variable m_condition; bash_queue_t m_bash_queue; mcu_queue_t m_from_mcu_queue; mcu_queue_t *m_to_mcu_queue; //content_t &m_content; render_t m_render; std::atomic_bool m_go; // special client, that consumes mcu messages like // button presses. // !!! Can be zero // session_ptr_t m_client; }; } // namespace led_d #endif <|endoftext|>
<commit_before>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #include "renderer.hpp" #include "optional_hit.hpp" #include "ray.hpp" #include "scene.hpp" #include "camera.hpp" #include "sdf_loader.hpp" #include "color.hpp" #include "shape.hpp" #include <algorithm> // min_element #include <glm/glm.hpp> #include <glm/vec3.hpp> Renderer::Renderer(unsigned w, unsigned h, std::string const& file): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_) {} Renderer::Renderer(): width_(0), height_(0), colorbuffer_(0, Color(0.0, 0.0, 0.0)), filename_(""), ppm_(width_, height_) {} unsigned Renderer::get_width() const{ return width_; } unsigned Renderer::get_height() const{ return height_; } std::string Renderer::get_filename() const{ return filename_; } Scene Renderer::get_scene() const{ return scene_; } Renderer& Renderer::operator= (Renderer const& rhs){ width_ = rhs.get_width(); height_ = rhs.get_height(); filename_ = rhs.get_filename(); return *this; } void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < height_; ++y) { for (unsigned x = 0; x < width_; ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x)/height_); } else { p.color = Color(1.0, 0.0, float(y)/width_); } write(p); } } ppm_.save(filename_); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (width_*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } Optional_hit Renderer::intersect(Ray const& ray) const{ Optional_hit o; Optional_hit temp; std::vector<float> hits; for (std::vector<std::shared_ptr <Shape>>::const_iterator it = scene_.shapes.begin(); it != scene_.shapes.end(); ++it) { if (it == scene_.shapes.begin() || !o.hit) { o.hit = (*it)->intersect(ray, o.distance, o.intersection, o.normal); o.shape = &**it; } else { temp.hit = (*it)->intersect(ray, temp.distance, temp.intersection, temp.normal); temp.shape = &**it; if(o.distance > temp.distance && temp.distance > 0) { o = temp; } } } //std::cout << o.shape->get_name() << std::endl; return o; } Color Renderer::raytrace(Ray const& ray, int depth){ Optional_hit o = intersect(ray); if(o.hit) return shade(ray, o, depth); else return scene_.ambient; } /* Color Renderer::shade(Ray const& ray, Optional_hit const& o, int depth){ //braucht man noch color und recursion depth statt distance? wenn ja woher? Material temp_mat = scene_.material[o.shape->get_material()]; float r = 0, g = 0, b = 0; float red = 0, green = 0, blue = 0; for(std::vector<Light_source>::const_iterator l = scene_.lights.begin(); l != scene_.lights.end(); ++l) { //Ray von Schnittpunkt zu Lichtquelle Ray lightray(o.intersection, glm::normalize((*l).get_position())); //Lichtintensität (Skalarprodukt, wird dann mit Reflexionskoeffizient und Helligkeit der Lichtquelle multipliziert) //oder Winkel zwischen Normale und Lichtquelle float tmp = glm::dot(o.normal, glm::normalize((*l).get_position()-o.intersection) ); float angle_n_l = std::max(tmp, 0.0f); float temp_r = 0, temp_g = 0, temp_b = 0; Optional_hit shadow = intersect(lightray); if(!shadow.hit){ /* Reflection ?? //Winkel Kamera/Lichquelle float cam_light_angle = glm::dot(glm::normalize(o.intersection - scene_.cam.get_position()), glm::normalize((*l).get_position() - o.intersection)); //Reflektionswinkel float reflection = cam_light_angle - (2* tmp); //Reflektionsvecktor glm::vec3 reflect_vec((2 * tmp * o.normal.x - (*l).get_position().x), (2 * tmp * o.normal.y - (*l).get_position().y), (2 * tmp * o.normal.z - (*l).get_position().z)); //Ray reflection_ray(o.intersection, reflect_vec); //oder Ray reflection_ray = reflect_ray(o.intersection, o.normale, l.get_position()); ? Ray reflection_ray = reflect_ray(o.intersection, o.normal, (*l).get_position()); temp_r = temp_mat.get_ks().r; //* pow(reflection, m); temp_g = temp_mat.get_ks().g; //* pow(reflection, m); temp_b = temp_mat.get_ks().b; //* pow(reflection, m); //...... r += (*l).get_diffuse().r * (angle_n_l * temp_mat.get_kd().r + temp_mat.get_ks().r); g += (*l).get_diffuse().g * (angle_n_l * temp_mat.get_kd().g + temp_mat.get_ks().g); b += (*l).get_diffuse().b * (angle_n_l * temp_mat.get_kd().b + temp_mat.get_ks().b); } else{ //Wenn im Schatten werden die Werde berechnet, sonst 0 ( Operator shadow.hit ? 1 : 0) r += temp_mat.get_kd().r * (*l).get_diffuse().r * angle_n_l; g += temp_mat.get_kd().g * (*l).get_diffuse().g * angle_n_l; b += temp_mat.get_kd().b * (*l).get_diffuse().b * angle_n_l; } } //mit Ambiente red = temp_mat.get_ka().r * scene_.ambient.r + r; green = temp_mat.get_ka().g * scene_.ambient.g + g; blue = temp_mat.get_ka().b * scene_.ambient.b + b; return Color(red, green, blue); }*/ Color Renderer::shade(Ray const& ray, Optional_hit const& o, int depth){ Color color; // Farbe des Strahls Ray rRay, tRay, sRay; // Reflexions-, Brechungs- und Schattenstrahlen Color rColor, tColor; // Farbe des reflektierten und gebrochenen Strahls Material temp_mat = scene_.material[o.shape->get_material()]; // Material des geschnittenen Shapes for (std::vector<Light_source>::const_iterator l = scene_.lights.begin(); l != scene_.lights.end(); ++l) { sRay = Ray(o.intersection, glm::normalize((*l).get_position())); //Teste ob Skalarprodukt von Normalen und sRay.direction positiv ist if(glm::dot(o.normal, sRay.direction) > 0){ // Wieviel Licht wird von opaken und transparenten Flächen blockiert? Optional_hit shadow= intersect(sRay); float shading = glm::dot(o.normal, glm::normalize((*l).get_position()-o.intersection) ); float shading_pos = std::max(shading, 0.0f); if (!shadow.hit) { color += (*l).get_diffuse() * (( temp_mat.get_kd() * shading_pos) + temp_mat.get_ks()); } else{ //Wenn im Schatten color += (*l).get_diffuse() * (( temp_mat.get_kd() * shading_pos)); } } } if (depth <= 3)//3 = Max depth, { if (temp_mat.get_m() != 0)//Objekt reflektiert { //Reflektionsray mit Reflektionsrichtung (ist der Einfallsvektor = Schnittpunkt?) rRay = reflect_ray(o.intersection, o.normal, o.intersection); rColor = raytrace(rRay, depth + 1); rColor *= temp_mat.get_m(); //rColor *= temp_mat.get_ks(); color += rColor; } /* if (temp_mat.get_opacity() != 0)//Objekt transparent { //Ray in Brechungsrichtung tRay = Ray (o.intersection, (o.intersection + o.intersection * temp_mat.get_opacity())); if(temp_mat.get_m() != 1) tColor = raytrace(tRay, depth + 1); tColor *= temp_mat.get_opacity(); color += tColor; }*/ } //ambiente Beleuchtung color += temp_mat.get_ka() * scene_.ambient; return color; } //ungefähres Prozedere? was ist mit den Methoden vom Bernstein? void Renderer::render_scene(std::string filename){ //Scene wird geladen Sdf_loader loader{filename}; scene_ = loader.load_scene(filename); //Daten aus Transferobjekt in den Renderer schreiben width_ = scene_.render.width; height_ = scene_.render.height; filename_= scene_.render.filename; std::vector<Color> buffer(width_*height_, Color(0.0, 0.0, 0.0)); colorbuffer_=buffer; PpmWriter ppm(width_, height_); ppm_ = ppm; //for(std::map<std::string, Material>::const_iterator it = scene_.material.begin(); it != scene_.material.end(); ++it){ // std::cout << it->second << std::endl; //} //Rays für das Bild gernerieren std::vector<Ray> rays; scene_.cam.generate_rays(width_, height_, rays); //std::cout << rays.size() << std::endl; std::vector<Pixel> pixel; for (unsigned i = 0; i < height_; ++i) { for (unsigned j = 0; j < width_; ++j) { Pixel p_temp(j,i); pixel.push_back(p_temp); } } std::vector<Pixel>::iterator j = pixel.begin(); //Farbe für jeden Pixel berechnen for (std::vector<Ray>::iterator i = rays.begin(); i < rays.end(); ++i) { Color temp = raytrace(*i,1); (*j).color = temp; //std::cout << temp; write(*j); ++j; } ppm_.save(filename_); } //warum haben wir render und render_scene? Ray Renderer::reflect_ray(glm::vec3 const& intersection, glm::vec3 const& normale, glm::vec3 const& rayDirection) const{ glm::vec3 spiegel{0.0f, 0.0f, 0.0f}; //neuer Ray direction kommt hier rein, origin ist intersection spiegel.x = (2*normale.x*normale.x*rayDirection.x + 2*normale.x*normale.y*rayDirection.y + 2*normale.x*normale.z*rayDirection.z - rayDirection.x); spiegel.y = (2*normale.x*normale.y*rayDirection.x + 2*normale.x*normale.y*rayDirection.y + 2*normale.y*normale.z*rayDirection.z - rayDirection.y); spiegel.z = (2*normale.y*normale.z*rayDirection.x + 2*normale.y*normale.z*rayDirection.y + 2*normale.z*normale.z*rayDirection.z - rayDirection.z); Ray newRay{intersection, spiegel}; //spiegel muss vielleicht *-1 genommen werden, bin mir nicht sicher ob der in die richtige Richtung zeigt return newRay; } <commit_msg>Kleine Äanderungen<commit_after>// ----------------------------------------------------------------------------- // Copyright : (C) 2014 Andreas-C. Bernstein // License : MIT (see the file LICENSE) // Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de> // Stability : experimental // // Renderer // ----------------------------------------------------------------------------- #include "renderer.hpp" #include "optional_hit.hpp" #include "ray.hpp" #include "scene.hpp" #include "camera.hpp" #include "sdf_loader.hpp" #include "color.hpp" #include "shape.hpp" #include <algorithm> // min_element #include <glm/glm.hpp> #include <glm/vec3.hpp> Renderer::Renderer(unsigned w, unsigned h, std::string const& file): width_(w), height_(h), colorbuffer_(w*h, Color(0.0, 0.0, 0.0)), filename_(file), ppm_(width_, height_) {} Renderer::Renderer(): width_(0), height_(0), colorbuffer_(0, Color(0.0, 0.0, 0.0)), filename_(""), ppm_(width_, height_) {} unsigned Renderer::get_width() const{ return width_; } unsigned Renderer::get_height() const{ return height_; } std::string Renderer::get_filename() const{ return filename_; } Scene Renderer::get_scene() const{ return scene_; } Renderer& Renderer::operator= (Renderer const& rhs){ width_ = rhs.get_width(); height_ = rhs.get_height(); filename_ = rhs.get_filename(); return *this; } void Renderer::render() { const std::size_t checkersize = 20; for (unsigned y = 0; y < height_; ++y) { for (unsigned x = 0; x < width_; ++x) { Pixel p(x,y); if ( ((x/checkersize)%2) != ((y/checkersize)%2)) { p.color = Color(0.0, 1.0, float(x)/height_); } else { p.color = Color(1.0, 0.0, float(y)/width_); } write(p); } } ppm_.save(filename_); } void Renderer::write(Pixel const& p) { // flip pixels, because of opengl glDrawPixels size_t buf_pos = (width_*p.y + p.x); if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) { std::cerr << "Fatal Error Renderer::write(Pixel p) : " << "pixel out of ppm_ : " << (int)p.x << "," << (int)p.y << std::endl; } else { colorbuffer_[buf_pos] = p.color; } ppm_.write(p); } Optional_hit Renderer::intersect(Ray const& ray) const{ Optional_hit o; Optional_hit temp; std::vector<float> hits; for (std::vector<std::shared_ptr <Shape>>::const_iterator it = scene_.shapes.begin(); it != scene_.shapes.end(); ++it) { if (it == scene_.shapes.begin() || !o.hit) { o.hit = (*it)->intersect(ray, o.distance, o.intersection, o.normal); o.shape = &**it; } else { temp.hit = (*it)->intersect(ray, temp.distance, temp.intersection, temp.normal); temp.shape = &**it; if(o.distance > temp.distance && temp.distance > 0) { o = temp; } } } //std::cout << o.shape->get_name() << std::endl; return o; } Color Renderer::raytrace(Ray const& ray, int depth){ Optional_hit o = intersect(ray); if(o.hit) return shade(ray, o, depth); else return scene_.ambient; } /* Color Renderer::shade(Ray const& ray, Optional_hit const& o, int depth){ //braucht man noch color und recursion depth statt distance? wenn ja woher? Material temp_mat = scene_.material[o.shape->get_material()]; float r = 0, g = 0, b = 0; float red = 0, green = 0, blue = 0; for(std::vector<Light_source>::const_iterator l = scene_.lights.begin(); l != scene_.lights.end(); ++l) { //Ray von Schnittpunkt zu Lichtquelle Ray lightray(o.intersection, glm::normalize((*l).get_position())); //Lichtintensität (Skalarprodukt, wird dann mit Reflexionskoeffizient und Helligkeit der Lichtquelle multipliziert) //oder Winkel zwischen Normale und Lichtquelle float tmp = glm::dot(o.normal, glm::normalize((*l).get_position()-o.intersection) ); float angle_n_l = std::max(tmp, 0.0f); float temp_r = 0, temp_g = 0, temp_b = 0; Optional_hit shadow = intersect(lightray); if(!shadow.hit){ /* Reflection ?? //Winkel Kamera/Lichquelle float cam_light_angle = glm::dot(glm::normalize(o.intersection - scene_.cam.get_position()), glm::normalize((*l).get_position() - o.intersection)); //Reflektionswinkel float reflection = cam_light_angle - (2* tmp); //Reflektionsvecktor glm::vec3 reflect_vec((2 * tmp * o.normal.x - (*l).get_position().x), (2 * tmp * o.normal.y - (*l).get_position().y), (2 * tmp * o.normal.z - (*l).get_position().z)); //Ray reflection_ray(o.intersection, reflect_vec); //oder Ray reflection_ray = reflect_ray(o.intersection, o.normale, l.get_position()); ? Ray reflection_ray = reflect_ray(o.intersection, o.normal, (*l).get_position()); temp_r = temp_mat.get_ks().r; //* pow(reflection, m); temp_g = temp_mat.get_ks().g; //* pow(reflection, m); temp_b = temp_mat.get_ks().b; //* pow(reflection, m); //...... r += (*l).get_diffuse().r * (angle_n_l * temp_mat.get_kd().r + temp_mat.get_ks().r); g += (*l).get_diffuse().g * (angle_n_l * temp_mat.get_kd().g + temp_mat.get_ks().g); b += (*l).get_diffuse().b * (angle_n_l * temp_mat.get_kd().b + temp_mat.get_ks().b); } else{ //Wenn im Schatten werden die Werde berechnet, sonst 0 ( Operator shadow.hit ? 1 : 0) r += temp_mat.get_kd().r * (*l).get_diffuse().r * angle_n_l; g += temp_mat.get_kd().g * (*l).get_diffuse().g * angle_n_l; b += temp_mat.get_kd().b * (*l).get_diffuse().b * angle_n_l; } } //mit Ambiente red = temp_mat.get_ka().r * scene_.ambient.r + r; green = temp_mat.get_ka().g * scene_.ambient.g + g; blue = temp_mat.get_ka().b * scene_.ambient.b + b; return Color(red, green, blue); }*/ Color Renderer::shade(Ray const& ray, Optional_hit const& o, int depth){ Color color; // Farbe des Strahls Ray rRay, tRay, sRay; // Reflexions-, Brechungs- und Schattenstrahlen Color rColor, tColor; // Farbe des reflektierten und gebrochenen Strahls Material temp_mat = scene_.material[o.shape->get_material()]; // Material des geschnittenen Shapes for (std::vector<Light_source>::const_iterator l = scene_.lights.begin(); l != scene_.lights.end(); ++l) { sRay = Ray(o.intersection, glm::normalize((*l).get_position())); //Teste ob Skalarprodukt von Normalen und sRay.direction positiv ist if(glm::dot(o.normal, sRay.direction) > 0){ // Wieviel Licht wird von opaken und transparenten Flächen blockiert? Optional_hit shadow= intersect(sRay); float shading = glm::dot(o.normal, glm::normalize((*l).get_position()-o.intersection) ); float shading_pos = std::max(shading, 0.0f); if (!shadow.hit) { color += (*l).get_diffuse() * (( temp_mat.get_kd() * shading_pos) + temp_mat.get_ks()); } else{ //Wenn im Schatten color += (*l).get_diffuse() * (( temp_mat.get_kd() * shading_pos)); } } } if (depth <= 3)//3 = Max depth, { if (temp_mat.get_m() != 0)//Objekt reflektiert(spiegelt) { //Reflektionsray mit Reflektionsrichtung (ist der Einfallsvektor = Schnittpunkt?) rRay = reflect_ray(o.intersection, o.normal, o.intersection); rColor = raytrace(rRay, depth + 1); rColor *= temp_mat.get_m(); //rColor *= temp_mat.get_ks(); color += rColor; } /* if (temp_mat.get_opacity() != 0)//Objekt transparent(mit Refraktion) { //Ray in Brechungsrichtung tRay = Ray (o.intersection, (o.intersection + o.intersection * temp_mat.get_refract())); if(temp_mat.get_m() != 1) tColor = raytrace(tRay, depth + 1); tColor *= temp_mat.get_opacity(); color += tColor; }*/ } //ambiente Beleuchtung color += temp_mat.get_ka() * scene_.ambient; return color; } void Renderer::render_scene(std::string filename){ //Scene wird geladen Sdf_loader loader{filename}; scene_ = loader.load_scene(filename); //Daten aus Transferobjekt in den Renderer schreiben width_ = scene_.render.width; height_ = scene_.render.height; filename_= scene_.render.filename; std::vector<Color> buffer(width_*height_, Color(0.0, 0.0, 0.0)); colorbuffer_=buffer; PpmWriter ppm(width_, height_); ppm_ = ppm; //Rays für das Bild gernerieren std::vector<Ray> rays; scene_.cam.generate_rays(width_, height_, rays); //Pixel für die Rays generieren std::vector<Pixel> pixel; for (unsigned i = 0; i < height_; ++i) { for (unsigned j = 0; j < width_; ++j) { Pixel p_temp(j,i); pixel.push_back(p_temp); } } std::vector<Pixel>::iterator j = pixel.begin(); //Farbe für jeden Pixel berechnen for (std::vector<Ray>::iterator i = rays.begin(); i < rays.end(); ++i) { Color temp = raytrace(*i,1); (*j).color = temp; //std::cout << temp; write(*j); ++j; } ppm_.save(filename_); } Ray Renderer::reflect_ray(glm::vec3 const& intersection, glm::vec3 const& normale, glm::vec3 const& rayDirection) const{ glm::vec3 spiegel{0.0f, 0.0f, 0.0f}; //neuer Ray direction kommt hier rein, origin ist intersection spiegel.x = (2*normale.x*normale.x*rayDirection.x + 2*normale.x*normale.y*rayDirection.y + 2*normale.x*normale.z*rayDirection.z - rayDirection.x); spiegel.y = (2*normale.x*normale.y*rayDirection.x + 2*normale.x*normale.y*rayDirection.y + 2*normale.y*normale.z*rayDirection.z - rayDirection.y); spiegel.z = (2*normale.y*normale.z*rayDirection.x + 2*normale.y*normale.z*rayDirection.y + 2*normale.z*normale.z*rayDirection.z - rayDirection.z); Ray newRay{intersection, spiegel}; //spiegel muss vielleicht *-1 genommen werden, bin mir nicht sicher ob der in die richtige Richtung zeigt return newRay; } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/MessageSender.h" #include <cassert> #include "joynr/BroadcastSubscriptionRequest.h" #include "joynr/IDispatcher.h" #include "joynr/IMessageRouter.h" #include "joynr/ImmutableMessage.h" #include "joynr/MulticastPublication.h" #include "joynr/MulticastSubscriptionRequest.h" #include "joynr/MutableMessage.h" #include "joynr/OneWayRequest.h" #include "joynr/Reply.h" #include "joynr/Request.h" #include "joynr/SubscriptionPublication.h" #include "joynr/SubscriptionReply.h" #include "joynr/SubscriptionRequest.h" #include "joynr/SubscriptionStop.h" #include "joynr/exceptions/JoynrException.h" #include "joynr/exceptions/MethodInvocationException.h" namespace joynr { MessageSender::MessageSender(std::shared_ptr<IMessageRouter> messageRouter, std::shared_ptr<IKeychain> keyChain, std::uint64_t ttlUpliftMs) : _dispatcher(), _messageRouter(std::move(messageRouter)), _messageFactory(ttlUpliftMs, std::move(keyChain)), _replyToAddress() { } void MessageSender::setReplyToAddress(const std::string& replyToAddress) { this->_replyToAddress = replyToAddress; } void MessageSender::registerDispatcher(std::weak_ptr<IDispatcher> dispatcher) { this->_dispatcher = std::move(dispatcher); } void MessageSender::sendRequest(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const Request& request, std::shared_ptr<IReplyCaller> callback, bool isLocalMessage) { auto dispatcherSharedPtr = _dispatcher.lock(); if (dispatcherSharedPtr == nullptr) { JOYNR_LOG_ERROR(logger(), "Sending a request failed. Dispatcher is null. Probably a proxy " "was used after the runtime was deleted."); return; } MutableMessage message = _messageFactory.createRequest( senderParticipantId, receiverParticipantId, qos, request, isLocalMessage); dispatcherSharedPtr->addReplyCaller(request.getRequestReplyId(), std::move(callback), qos); if (!message.isLocalMessage()) { message.setReplyTo(_replyToAddress); } JOYNR_LOG_DEBUG(logger(), "Send Request: method: {}, requestReplyId: {}, messageId: {}, " "proxy participantId: {}, provider participantId: {}", request.getMethodName(), request.getRequestReplyId(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } void MessageSender::sendOneWayRequest(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const OneWayRequest& request, bool isLocalMessage) { try { MutableMessage message = _messageFactory.createOneWayRequest( senderParticipantId, receiverParticipantId, qos, request, isLocalMessage); JOYNR_LOG_DEBUG(logger(), "Send OneWayRequest: method: {}, messageId: {}, proxy participantId: {}, " "provider participantId: {}", request.getMethodName(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendReply(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, std::unordered_map<std::string, std::string> prefixedCustomHeaders, const Reply& reply) { try { MutableMessage message = _messageFactory.createReply(senderParticipantId, receiverParticipantId, qos, std::move(prefixedCustomHeaders), reply); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } catch (const exceptions::JoynrRuntimeException& e) { JOYNR_LOG_ERROR(logger(), "Reply with RequestReplyId {} could not be sent to {}. Error: {}", reply.getRequestReplyId(), receiverParticipantId, e.getMessage()); } } void MessageSender::sendSubscriptionRequest(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const SubscriptionRequest& subscriptionRequest, bool isLocalMessage) { try { MutableMessage message = _messageFactory.createSubscriptionRequest(senderParticipantId, receiverParticipantId, qos, subscriptionRequest, isLocalMessage); if (!message.isLocalMessage()) { message.setReplyTo(_replyToAddress); } JOYNR_LOG_DEBUG(logger(), "Send AttributeSubscriptionRequest: subscriptionId: {}, messageId: {}, " "proxy participantId: {}, provider participantId: {}", subscriptionRequest.getSubscriptionId(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendBroadcastSubscriptionRequest( const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const BroadcastSubscriptionRequest& subscriptionRequest, bool isLocalMessage) { try { MutableMessage message = _messageFactory.createBroadcastSubscriptionRequest(senderParticipantId, receiverParticipantId, qos, subscriptionRequest, isLocalMessage); if (!message.isLocalMessage()) { message.setReplyTo(_replyToAddress); } JOYNR_LOG_DEBUG(logger(), "Send BroadcastSubscriptionRequest: subscriptionId: {}, messageId: {}, " "proxy participantId: {}, provider participantId: {}", subscriptionRequest.getSubscriptionId(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendMulticastSubscriptionRequest( const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const MulticastSubscriptionRequest& subscriptionRequest, bool isLocalMessage) { try { MutableMessage message = _messageFactory.createMulticastSubscriptionRequest(senderParticipantId, receiverParticipantId, qos, subscriptionRequest, isLocalMessage); if (!message.isLocalMessage()) { message.setReplyTo(_replyToAddress); } JOYNR_LOG_DEBUG(logger(), "Send MulticastSubscriptionRequest: subscriptionId: {}, messageId: {}, " "proxy participantId: {}, provider participantId: {}", subscriptionRequest.getSubscriptionId(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendSubscriptionReply(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const SubscriptionReply& subscriptionReply) { try { MutableMessage message = _messageFactory.createSubscriptionReply( senderParticipantId, receiverParticipantId, qos, subscriptionReply); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } catch (const exceptions::JoynrRuntimeException& e) { JOYNR_LOG_ERROR( logger(), "SubscriptionReply with SubscriptionId {} could not be sent to {}. Error: {}", subscriptionReply.getSubscriptionId(), receiverParticipantId, e.getMessage()); } } void MessageSender::sendSubscriptionStop(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const SubscriptionStop& subscriptionStop) { try { MutableMessage message = _messageFactory.createSubscriptionStop( senderParticipantId, receiverParticipantId, qos, subscriptionStop); JOYNR_LOG_DEBUG(logger(), "UNREGISTER SUBSCRIPTION call proxy: subscriptionId: {}, messageId: {}, " "proxy participantId: {}, provider participantId: {}", subscriptionStop.getSubscriptionId(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendSubscriptionPublication(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, SubscriptionPublication&& subscriptionPublication) { try { MutableMessage message = _messageFactory.createSubscriptionPublication( senderParticipantId, receiverParticipantId, qos, subscriptionPublication); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } catch (const exceptions::JoynrRuntimeException& e) { JOYNR_LOG_ERROR( logger(), "SubscriptionPublication with SubscriptionId {} could not be sent to {}. Error: {}", subscriptionPublication.getSubscriptionId(), receiverParticipantId, e.getMessage()); } } void MessageSender::sendMulticast(const std::string& fromParticipantId, const MulticastPublication& multicastPublication, const MessagingQos& messagingQos) { try { MutableMessage message = _messageFactory.createMulticastPublication( fromParticipantId, messagingQos, multicastPublication); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } catch (const exceptions::JoynrRuntimeException& e) { JOYNR_LOG_ERROR(logger(), "MulticastPublication with multicastId {} could not be sent. Error: {}", multicastPublication.getMulticastId(), e.getMessage()); } } } // namespace joynr <commit_msg>[C++] Do not transmit MulticastSubscriptionRequest any longer<commit_after>/* * #%L * %% * Copyright (C) 2020 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "joynr/MessageSender.h" #include <cassert> #include "joynr/BroadcastSubscriptionRequest.h" #include "joynr/IDispatcher.h" #include "joynr/IMessageRouter.h" #include "joynr/ImmutableMessage.h" #include "joynr/MulticastPublication.h" #include "joynr/MulticastSubscriptionRequest.h" #include "joynr/MutableMessage.h" #include "joynr/OneWayRequest.h" #include "joynr/Reply.h" #include "joynr/Request.h" #include "joynr/SubscriptionPublication.h" #include "joynr/SubscriptionReply.h" #include "joynr/SubscriptionRequest.h" #include "joynr/SubscriptionStop.h" #include "joynr/exceptions/JoynrException.h" #include "joynr/exceptions/MethodInvocationException.h" namespace joynr { MessageSender::MessageSender(std::shared_ptr<IMessageRouter> messageRouter, std::shared_ptr<IKeychain> keyChain, std::uint64_t ttlUpliftMs) : _dispatcher(), _messageRouter(std::move(messageRouter)), _messageFactory(ttlUpliftMs, std::move(keyChain)), _replyToAddress() { } void MessageSender::setReplyToAddress(const std::string& replyToAddress) { this->_replyToAddress = replyToAddress; } void MessageSender::registerDispatcher(std::weak_ptr<IDispatcher> dispatcher) { this->_dispatcher = std::move(dispatcher); } void MessageSender::sendRequest(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const Request& request, std::shared_ptr<IReplyCaller> callback, bool isLocalMessage) { auto dispatcherSharedPtr = _dispatcher.lock(); if (dispatcherSharedPtr == nullptr) { JOYNR_LOG_ERROR(logger(), "Sending a request failed. Dispatcher is null. Probably a proxy " "was used after the runtime was deleted."); return; } MutableMessage message = _messageFactory.createRequest( senderParticipantId, receiverParticipantId, qos, request, isLocalMessage); dispatcherSharedPtr->addReplyCaller(request.getRequestReplyId(), std::move(callback), qos); if (!message.isLocalMessage()) { message.setReplyTo(_replyToAddress); } JOYNR_LOG_DEBUG(logger(), "Send Request: method: {}, requestReplyId: {}, messageId: {}, " "proxy participantId: {}, provider participantId: {}", request.getMethodName(), request.getRequestReplyId(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } void MessageSender::sendOneWayRequest(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const OneWayRequest& request, bool isLocalMessage) { try { MutableMessage message = _messageFactory.createOneWayRequest( senderParticipantId, receiverParticipantId, qos, request, isLocalMessage); JOYNR_LOG_DEBUG(logger(), "Send OneWayRequest: method: {}, messageId: {}, proxy participantId: {}, " "provider participantId: {}", request.getMethodName(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendReply(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, std::unordered_map<std::string, std::string> prefixedCustomHeaders, const Reply& reply) { try { MutableMessage message = _messageFactory.createReply(senderParticipantId, receiverParticipantId, qos, std::move(prefixedCustomHeaders), reply); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } catch (const exceptions::JoynrRuntimeException& e) { JOYNR_LOG_ERROR(logger(), "Reply with RequestReplyId {} could not be sent to {}. Error: {}", reply.getRequestReplyId(), receiverParticipantId, e.getMessage()); } } void MessageSender::sendSubscriptionRequest(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const SubscriptionRequest& subscriptionRequest, bool isLocalMessage) { try { MutableMessage message = _messageFactory.createSubscriptionRequest(senderParticipantId, receiverParticipantId, qos, subscriptionRequest, isLocalMessage); if (!message.isLocalMessage()) { message.setReplyTo(_replyToAddress); } JOYNR_LOG_DEBUG(logger(), "Send AttributeSubscriptionRequest: subscriptionId: {}, messageId: {}, " "proxy participantId: {}, provider participantId: {}", subscriptionRequest.getSubscriptionId(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendBroadcastSubscriptionRequest( const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const BroadcastSubscriptionRequest& subscriptionRequest, bool isLocalMessage) { try { MutableMessage message = _messageFactory.createBroadcastSubscriptionRequest(senderParticipantId, receiverParticipantId, qos, subscriptionRequest, isLocalMessage); if (!message.isLocalMessage()) { message.setReplyTo(_replyToAddress); } JOYNR_LOG_DEBUG(logger(), "Send BroadcastSubscriptionRequest: subscriptionId: {}, messageId: {}, " "proxy participantId: {}, provider participantId: {}", subscriptionRequest.getSubscriptionId(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendMulticastSubscriptionRequest( const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const MulticastSubscriptionRequest& subscriptionRequest, bool isLocalMessage) { std::ignore = isLocalMessage; try { // MulticastSubscriptionRequest is no longer transmitted, instead // the SubscriptionReply formerly sent by provider is simulated and // routed back to invoke regular reply handling as before. JOYNR_LOG_DEBUG(logger(), "MulticastSubscription: subscriptionId: {}, " "proxy participantId: {}, provider participantId: {}", subscriptionRequest.getSubscriptionId(), senderParticipantId, receiverParticipantId); SubscriptionReply subscriptionReply; subscriptionReply.setSubscriptionId(subscriptionRequest.getSubscriptionId()); sendSubscriptionReply(receiverParticipantId, senderParticipantId, qos, subscriptionReply); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendSubscriptionReply(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const SubscriptionReply& subscriptionReply) { try { MutableMessage message = _messageFactory.createSubscriptionReply( senderParticipantId, receiverParticipantId, qos, subscriptionReply); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } catch (const exceptions::JoynrRuntimeException& e) { JOYNR_LOG_ERROR( logger(), "SubscriptionReply with SubscriptionId {} could not be sent to {}. Error: {}", subscriptionReply.getSubscriptionId(), receiverParticipantId, e.getMessage()); } } void MessageSender::sendSubscriptionStop(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, const SubscriptionStop& subscriptionStop) { try { MutableMessage message = _messageFactory.createSubscriptionStop( senderParticipantId, receiverParticipantId, qos, subscriptionStop); JOYNR_LOG_DEBUG(logger(), "UNREGISTER SUBSCRIPTION call proxy: subscriptionId: {}, messageId: {}, " "proxy participantId: {}, provider participantId: {}", subscriptionStop.getSubscriptionId(), message.getId(), senderParticipantId, receiverParticipantId); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } } void MessageSender::sendSubscriptionPublication(const std::string& senderParticipantId, const std::string& receiverParticipantId, const MessagingQos& qos, SubscriptionPublication&& subscriptionPublication) { try { MutableMessage message = _messageFactory.createSubscriptionPublication( senderParticipantId, receiverParticipantId, qos, subscriptionPublication); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } catch (const exceptions::JoynrRuntimeException& e) { JOYNR_LOG_ERROR( logger(), "SubscriptionPublication with SubscriptionId {} could not be sent to {}. Error: {}", subscriptionPublication.getSubscriptionId(), receiverParticipantId, e.getMessage()); } } void MessageSender::sendMulticast(const std::string& fromParticipantId, const MulticastPublication& multicastPublication, const MessagingQos& messagingQos) { try { MutableMessage message = _messageFactory.createMulticastPublication( fromParticipantId, messagingQos, multicastPublication); assert(_messageRouter); _messageRouter->route(message.getImmutableMessage()); } catch (const std::invalid_argument& exception) { throw joynr::exceptions::MethodInvocationException(exception.what()); } catch (const exceptions::JoynrRuntimeException& e) { JOYNR_LOG_ERROR(logger(), "MulticastPublication with multicastId {} could not be sent. Error: {}", multicastPublication.getMulticastId(), e.getMessage()); } } } // namespace joynr <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// /// \file generic.hpp /// ----------------- /// /// (c) Copyright Domagoj Saric 2016. /// /// Use, modification and distribution are subject to the /// Boost Software License, Version 1.0. (See accompanying file /// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /// /// See http://www.boost.org for most recent version. /// //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ #ifndef generic_hpp__99FE2034_248F_4C7D_8CD2_EB2BB8247377 #define generic_hpp__99FE2034_248F_4C7D_8CD2_EB2BB8247377 #pragma once //------------------------------------------------------------------------------ #include <boost/container/small_vector.hpp> #include <boost/container/static_vector.hpp> #include <boost/functionoid/functionoid.hpp> #include <boost/range/algorithm/count_if.hpp> #include <boost/range/iterator_range_core.hpp> #include <atomic> #include <cstdint> #include <future> #include <memory> #include <mutex> #include <thread> //------------------------------------------------------------------------------ namespace boost { //------------------------------------------------------------------------------ namespace sweater { //------------------------------------------------------------------------------ #ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURENCY # define BOOST_SWEATER_MAX_HARDWARE_CONCURENCY 0 #endif // BOOST_SWEATER_MAX_HARDWARE_CONCURENCY inline auto hardware_concurency() noexcept { return static_cast<std::uint8_t>( std::thread::hardware_concurrency() ); } class impl { private: #ifdef __ANROID__ // https://petewarden.com/2015/10/11/one-weird-trick-for-faster-android-multithreading static auto constexpr spin_count = 30 * 1000 * 1000; #else static auto constexpr spin_count = 1; #endif // __ANROID__ public: impl() #if BOOST_SWEATER_MAX_HARDWARE_CONCURENCY : pool_( BOOST_SWEATER_MAX_HARDWARE_CONCURENCY - 1 ) #endif { #if !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY auto const number_of_worker_threads( hardware_concurency() - 1 ); auto p_workers( std::make_unique<worker[]>( number_of_worker_threads ) ); pool_ = make_iterator_range_n( p_workers.get(), number_of_worker_threads ); #endif // !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY for ( auto & worker : pool_ ) { auto const worker_loop ( [&worker, this]() noexcept { auto & __restrict my_work_available( worker.have_work ); auto & __restrict my_work ( worker.work ); auto & __restrict my_event ( worker.event ); for ( ; ; ) { for ( auto try_count( 0 ); try_count < spin_count; ++try_count ) { if ( BOOST_LIKELY( my_work_available.load( std::memory_order_acquire ) ) ) { my_work(); std::unique_lock<std::mutex> lock( mutex_ ); my_work_available.store( false, std::memory_order_relaxed ); my_event.notify_one(); } } if ( BOOST_UNLIKELY( brexit_.load( std::memory_order_relaxed ) ) ) return; std::unique_lock<std::mutex> lock( mutex_ ); /// \note No need for a another loop here as a /// suprious-wakeup would be handled by the check in the /// loop above. /// (08.11.2016.) (Domagoj Saric) if ( !BOOST_LIKELY( my_work_available.load( std::memory_order_relaxed ) ) ) worker.event.wait( lock ); BOOST_ASSERT( brexit_ || my_work_available ); } } ); // worker_loop worker.thread = std::thread( worker_loop ); } #if !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY p_workers.release(); #endif // !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY } ~impl() noexcept { brexit_.store( true, std::memory_order_relaxed ); for ( auto & worker : pool_ ) { worker.event .notify_one(); worker.thread.join (); } #if !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY delete[] pool_.begin(); #endif // BOOST_SWEATER_MAX_HARDWARE_CONCURENCY } auto number_of_workers() const { return static_cast<std::uint16_t>( pool_.size() + 1 ); } /// For GCD dispatch_apply/OMP-like parallel loops template <typename F> void spread_the_sweat( std::uint16_t const iterations, F && __restrict work ) noexcept { static_assert( noexcept( work( iterations, iterations ) ), "F must be noexcept" ); auto const number_of_workers ( this->number_of_workers() ); auto const iterations_per_worker ( iterations / number_of_workers ); auto const threads_with_extra_iteration( iterations % number_of_workers ); std::uint16_t iteration( 0 ); iteration = spread_iterations ( 0, threads_with_extra_iteration, iteration, iterations_per_worker + 1, work ); iteration = spread_iterations ( threads_with_extra_iteration, pool_.size(), iteration, iterations_per_worker, work ); auto const caller_thread_start_iteration( iteration ); BOOST_ASSERT( caller_thread_start_iteration <= iterations ); work( caller_thread_start_iteration, iterations ); join(); } template <typename F> static void fire_and_forget( F && work ) { std::thread( std::forward<F>( work ) ).detach(); } template <typename F> static auto dispatch( F && work ) { // http://scottmeyers.blogspot.hr/2013/03/stdfutures-from-stdasync-arent-special.html return std::async( std::launch::async | std::launch::deferred, std::forward<F>( work ) ); } private: BOOST_NOINLINE void join() noexcept { for ( auto const & worker : pool_ ) { bool worker_done; for ( auto try_count( 0 ); try_count < spin_count; ++try_count ) { worker_done = !worker.have_work.load( std::memory_order_relaxed ); if ( worker_done ) break; } if ( worker_done ) continue; std::unique_lock<std::mutex> lock( mutex_ ); while ( worker.have_work.load( std::memory_order_relaxed ) ) worker.event.wait( lock ); } } template <typename F> std::uint16_t spread_iterations ( std::uint8_t const begin_thread, std::uint8_t const end_thread, std::uint16_t const begin_iteration, std::uint16_t const iterations_per_worker, F && work ) noexcept { auto iteration( begin_iteration ); for ( auto thread_index( begin_thread ); thread_index < end_thread; ++thread_index ) { auto & delegate( pool_[ thread_index ].work ); auto const end_iteration( iteration + iterations_per_worker ); delegate = [&work, start_iteration = iteration, end_iteration]() noexcept { work( start_iteration, end_iteration ); }; /// \note The mutex lock and std::condition_variable::notify_one() /// call below should imply a release so we can get away with a /// relaxed store here. /// (14.10.2016.) (Domagoj Saric) std::unique_lock<std::mutex> lock( mutex_ ); pool_[ thread_index ].have_work.store( true, std::memory_order_relaxed ); pool_[ thread_index ].event.notify_one(); iteration = end_iteration; } return iteration; } private: std::atomic<bool> brexit_ = ATOMIC_FLAG_INIT; std::mutex mutex_; struct worker_traits : functionoid::std_traits { static constexpr auto copyable = functionoid::support_level::na ; static constexpr auto moveable = functionoid::support_level::nofail; static constexpr auto destructor = functionoid::support_level::nofail; static constexpr auto is_noexcept = true; static constexpr auto rtti = false; using empty_handler = functionoid::assert_on_empty; }; // struct worker_traits struct worker { std::atomic<bool> have_work = ATOMIC_FLAG_INIT; functionoid::callable<void(), worker_traits> work ; mutable std::condition_variable event ; std::thread thread; }; // struct worker #if BOOST_SWEATER_MAX_HARDWARE_CONCURENCY using pool_threads_t = container::static_vector<worker, BOOST_SWEATER_MAX_HARDWARE_CONCURENCY - 1>; // also sweat on the calling thread #else using pool_threads_t = iterator_range<worker *>; #endif pool_threads_t pool_; /// \todo Implement a work queue. /// https://en.wikipedia.org/wiki/Work_stealing /// http://www.drdobbs.com/parallel/writing-lock-free-code-a-corrected-queue/210604448 /// https://github.com/cameron314/readerwriterqueue /// http://moodycamel.com/blog/2013/a-fast-lock-free-queue-for-c++ /// http://stackoverflow.com/questions/1164023/is-there-a-production-ready-lock-free-queue-or-hash-implementation-in-c#14936831 /// https://github.com/facebook/folly/blob/master/folly/docs/ProducerConsumerQueue.md /// https://github.com/facebook/folly/blob/master/folly/MPMCQueue.h /// http://landenlabs.com/code/ring/ring.html /// https://github.com/Qarterd/Honeycomb/blob/master/src/common/Honey/Thread/Pool.cpp /// (12.10.2016.) (Domagoj Saric) }; // class impl //------------------------------------------------------------------------------ } // namespace sweater //------------------------------------------------------------------------------ } // namespace boost //------------------------------------------------------------------------------ #endif // generic_hpp<commit_msg>Minor optimization and refactoring.<commit_after>//////////////////////////////////////////////////////////////////////////////// /// /// \file generic.hpp /// ----------------- /// /// (c) Copyright Domagoj Saric 2016. /// /// Use, modification and distribution are subject to the /// Boost Software License, Version 1.0. (See accompanying file /// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /// /// See http://www.boost.org for most recent version. /// //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ #ifndef generic_hpp__99FE2034_248F_4C7D_8CD2_EB2BB8247377 #define generic_hpp__99FE2034_248F_4C7D_8CD2_EB2BB8247377 #pragma once //------------------------------------------------------------------------------ #include <boost/container/small_vector.hpp> #include <boost/container/static_vector.hpp> #include <boost/functionoid/functionoid.hpp> #include <boost/range/algorithm/count_if.hpp> #include <boost/range/iterator_range_core.hpp> #include <atomic> #include <cstdint> #include <future> #include <memory> #include <mutex> #include <thread> //------------------------------------------------------------------------------ namespace boost { //------------------------------------------------------------------------------ namespace sweater { //------------------------------------------------------------------------------ #ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURENCY # define BOOST_SWEATER_MAX_HARDWARE_CONCURENCY 0 #endif // BOOST_SWEATER_MAX_HARDWARE_CONCURENCY inline auto hardware_concurency() noexcept { return static_cast<std::uint8_t>( std::thread::hardware_concurrency() ); } class impl { private: #ifdef __ANROID__ // https://petewarden.com/2015/10/11/one-weird-trick-for-faster-android-multithreading static auto constexpr spin_count = 30 * 1000 * 1000; #else static auto constexpr spin_count = 1; #endif // __ANROID__ public: impl() #if BOOST_SWEATER_MAX_HARDWARE_CONCURENCY : pool_( BOOST_SWEATER_MAX_HARDWARE_CONCURENCY - 1 ) #endif { #if !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY auto const number_of_worker_threads( hardware_concurency() - 1 ); auto p_workers( std::make_unique<worker[]>( number_of_worker_threads ) ); pool_ = make_iterator_range_n( p_workers.get(), number_of_worker_threads ); #endif // !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY for ( auto & worker : pool_ ) { auto const worker_loop ( [&worker, this]() noexcept { auto & __restrict my_work_available( worker.have_work ); auto & __restrict my_work ( worker.work ); auto & __restrict my_event ( worker.event ); for ( ; ; ) { for ( auto try_count( 0 ); try_count < spin_count; ++try_count ) { if ( BOOST_LIKELY( my_work_available.load( std::memory_order_acquire ) ) ) { my_work(); if ( spin_count > 1 ) // restart the spin-wait try_count = 0; std::unique_lock<std::mutex> lock( mutex_ ); my_work_available.store( false, std::memory_order_relaxed ); my_event.notify_one(); } } if ( BOOST_UNLIKELY( brexit_.load( std::memory_order_relaxed ) ) ) return; std::unique_lock<std::mutex> lock( mutex_ ); /// \note No need for a another loop here as a /// spurious-wakeup would be handled by the check in the /// loop above. /// (08.11.2016.) (Domagoj Saric) if ( !BOOST_LIKELY( my_work_available.load( std::memory_order_relaxed ) ) ) worker.event.wait( lock ); BOOST_ASSERT( brexit_ || my_work_available ); } } ); // worker_loop worker.thread = std::thread( worker_loop ); } #if !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY p_workers.release(); #endif // !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY } ~impl() noexcept { brexit_.store( true, std::memory_order_relaxed ); for ( auto & worker : pool_ ) { worker.event .notify_one(); worker.thread.join (); } #if !BOOST_SWEATER_MAX_HARDWARE_CONCURENCY delete[] pool_.begin(); #endif // BOOST_SWEATER_MAX_HARDWARE_CONCURENCY } auto number_of_workers() const { return static_cast<std::uint16_t>( pool_.size() + 1 ); } /// For GCD dispatch_apply/OMP-like parallel loops template <typename F> void spread_the_sweat( std::uint16_t const iterations, F && __restrict work ) noexcept { static_assert( noexcept( work( iterations, iterations ) ), "F must be noexcept" ); auto const number_of_workers ( this->number_of_workers() ); auto const iterations_per_worker ( iterations / number_of_workers ); auto const threads_with_extra_iteration( iterations % number_of_workers ); std::uint16_t iteration( 0 ); iteration = spread_iterations ( 0, threads_with_extra_iteration, iteration, iterations_per_worker + 1, work ); iteration = spread_iterations ( threads_with_extra_iteration, pool_.size(), iteration, iterations_per_worker, work ); auto const caller_thread_start_iteration( iteration ); BOOST_ASSERT( caller_thread_start_iteration <= iterations ); work( caller_thread_start_iteration, iterations ); join(); } template <typename F> static void fire_and_forget( F && work ) { std::thread( std::forward<F>( work ) ).detach(); } template <typename F> static auto dispatch( F && work ) { // http://scottmeyers.blogspot.hr/2013/03/stdfutures-from-stdasync-arent-special.html return std::async( std::launch::async | std::launch::deferred, std::forward<F>( work ) ); } private: BOOST_NOINLINE void join() noexcept { for ( auto const & worker : pool_ ) { bool worker_done; for ( auto try_count( 0 ); try_count < spin_count; ++try_count ) { worker_done = !worker.have_work.load( std::memory_order_relaxed ); if ( worker_done ) break; } if ( worker_done ) continue; std::unique_lock<std::mutex> lock( mutex_ ); while ( worker.have_work.load( std::memory_order_relaxed ) ) worker.event.wait( lock ); } } template <typename F> std::uint16_t spread_iterations ( std::uint8_t const begin_thread, std::uint8_t const end_thread, std::uint16_t const begin_iteration, std::uint16_t const iterations_per_worker, F && work ) noexcept { auto iteration( begin_iteration ); for ( auto thread_index( begin_thread ); thread_index < end_thread; ++thread_index ) { BOOST_ASSERT( !pool_[ thread_index ].have_work ); auto const end_iteration( iteration + iterations_per_worker ); pool_[ thread_index ].work = [&work, start_iteration = iteration, end_iteration]() noexcept { work( start_iteration, end_iteration ); }; /// \note The mutex lock and std::condition_variable::notify_one() /// call below should imply a release so we can get away with a /// relaxed store here. /// (14.10.2016.) (Domagoj Saric) std::unique_lock<std::mutex> lock( mutex_ ); pool_[ thread_index ].have_work.store( true, std::memory_order_relaxed ); pool_[ thread_index ].event.notify_one(); iteration = end_iteration; } return iteration; } private: std::atomic<bool> brexit_ = ATOMIC_FLAG_INIT; std::mutex mutex_; struct worker_traits : functionoid::std_traits { static constexpr auto copyable = functionoid::support_level::na ; static constexpr auto moveable = functionoid::support_level::nofail; static constexpr auto destructor = functionoid::support_level::nofail; static constexpr auto is_noexcept = true; static constexpr auto rtti = false; using empty_handler = functionoid::assert_on_empty; }; // struct worker_traits struct worker { std::atomic<bool> have_work = ATOMIC_FLAG_INIT; functionoid::callable<void(), worker_traits> work ; mutable std::condition_variable event ; std::thread thread; }; // struct worker #if BOOST_SWEATER_MAX_HARDWARE_CONCURENCY using pool_threads_t = container::static_vector<worker, BOOST_SWEATER_MAX_HARDWARE_CONCURENCY - 1>; // also sweat on the calling thread #else using pool_threads_t = iterator_range<worker *>; #endif pool_threads_t pool_; /// \todo Implement a work queue. /// https://en.wikipedia.org/wiki/Work_stealing /// http://www.drdobbs.com/parallel/writing-lock-free-code-a-corrected-queue/210604448 /// https://github.com/cameron314/readerwriterqueue /// http://moodycamel.com/blog/2013/a-fast-lock-free-queue-for-c++ /// http://stackoverflow.com/questions/1164023/is-there-a-production-ready-lock-free-queue-or-hash-implementation-in-c#14936831 /// https://github.com/facebook/folly/blob/master/folly/docs/ProducerConsumerQueue.md /// https://github.com/facebook/folly/blob/master/folly/MPMCQueue.h /// http://landenlabs.com/code/ring/ring.html /// https://github.com/Qarterd/Honeycomb/blob/master/src/common/Honey/Thread/Pool.cpp /// (12.10.2016.) (Domagoj Saric) }; // class impl //------------------------------------------------------------------------------ } // namespace sweater //------------------------------------------------------------------------------ } // namespace boost //------------------------------------------------------------------------------ #endif // generic_hpp<|endoftext|>
<commit_before>/* * This file is part of libqcalparser * * Copyright (C) Rohan Garg <rohan16garg@gmail.com> * * 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 "qcalparser.h" //Local includes #include "qcalevent.h" //Qt includes #include <QFile> #include <QDateTime> #include <QDebug> #include <QTextStream> QCalParser::QCalParser(QFile *iCalFile, QObject *parent) : QObject(parent) { Q_ASSERT(iCalFile->open(QIODevice::ReadOnly | QIODevice::Text)); m_eventList.clear(); m_dataStream = new QTextStream(iCalFile); parseICalFile(); iCalFile->close(); } QCalParser::~QCalParser() { delete m_dataStream; } void QCalParser::parseICalFile() { QString line = m_dataStream->readLine(); while(!line.isNull()) { if(line.contains("BEGIN:VEVENT")) { parseICalBlock(); } line = m_dataStream->readLine(); }; } void QCalParser::parseICalBlock() { QCalEvent *event = new QCalEvent(this); QString line; do { line = m_dataStream->readLine(); if(line.startsWith(QLatin1String("UID:"))) { event->setUid(line.section(QLatin1Char(':'), 1)); } else if (line.startsWith(QLatin1String("DTSTART:"))){ event->setStartDate(QDateTime::fromString(line, "'DTSTART:'yyyyMMdd'T'hhmmss'Z'")); } else if (line.startsWith(QLatin1String("DTEND:"))){ event->setStopDate(QDateTime::fromString(line, "'DTEND:'yyyyMMdd'T'hhmmss'Z'")); } else if (line.startsWith(QLatin1String("CATEGORIES:"))) { event->setCategories(line.section(QLatin1Char(':'), 1).split(" " || ",", QString::SkipEmptyParts)); } else if (line.startsWith(QLatin1String("SUMMARY:"))) { event->setSummary(line.section(QLatin1Char(':'), 1)); } else if (line.startsWith(QLatin1String("LOCATION:"))) { event->setLocation(line.section(QLatin1Char(':'), 1)); } else if (line.startsWith(QLatin1String("DESCRIPTION:"))) { event->setDescription(line.section(QLatin1Char(':'), 1)); } else if (line.startsWith(QLatin1String("URL:"))) { event->setEventUrl(line.section(QLatin1Char(':'), 1)); } else if (line.startsWith(QLatin1String("X-TYPE:"))) { event->setEvpentUrlType(line.section(QLatin1Char(':'), 1)); } else if (line.startsWith(QLatin1String("X-ROOMNAME:"))) { event->setRoomName(line.section(QLatin1Char(':'), 1)); } }while(!line.contains(QByteArray("END:VEVENT"))); m_eventList.append(event); } QList <QCalEvent*> QCalParser::getEventList() { return m_eventList; } <commit_msg>Make loop faster by using continue statements<commit_after>/* * This file is part of libqcalparser * * Copyright (C) Rohan Garg <rohan16garg@gmail.com> * * 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 "qcalparser.h" //Local includes #include "qcalevent.h" //Qt includes #include <QFile> #include <QDateTime> #include <QDebug> #include <QTextStream> QCalParser::QCalParser(QFile *iCalFile, QObject *parent) : QObject(parent) { Q_ASSERT(iCalFile->open(QIODevice::ReadOnly | QIODevice::Text)); m_eventList.clear(); m_dataStream = new QTextStream(iCalFile); parseICalFile(); iCalFile->close(); } QCalParser::~QCalParser() { delete m_dataStream; } void QCalParser::parseICalFile() { QString line = m_dataStream->readLine(); while(!line.isNull()) { if(line.contains("BEGIN:VEVENT")) { parseICalBlock(); } line = m_dataStream->readLine(); }; } void QCalParser::parseICalBlock() { QCalEvent *event = new QCalEvent(this); QString line; do { line = m_dataStream->readLine(); if(line.startsWith(QLatin1String("UID:"))) { event->setUid(line.section(QLatin1Char(':'), 1)); continue; } else if (line.startsWith(QLatin1String("DTSTART:"))){ event->setStartDate(QDateTime::fromString(line, "'DTSTART:'yyyyMMdd'T'hhmmss'Z'")); continue; } else if (line.startsWith(QLatin1String("DTEND:"))){ event->setStopDate(QDateTime::fromString(line, "'DTEND:'yyyyMMdd'T'hhmmss'Z'")); continue; } else if (line.startsWith(QLatin1String("CATEGORIES:"))) { event->setCategories(line.section(QLatin1Char(':'), 1).split(" " || ",", QString::SkipEmptyParts)); continue; } else if (line.startsWith(QLatin1String("SUMMARY:"))) { event->setSummary(line.section(QLatin1Char(':'), 1)); continue; } else if (line.startsWith(QLatin1String("LOCATION:"))) { event->setLocation(line.section(QLatin1Char(':'), 1)); continue; } else if (line.startsWith(QLatin1String("DESCRIPTION:"))) { event->setDescription(line.section(QLatin1Char(':'), 1)); continue; } else if (line.startsWith(QLatin1String("URL:"))) { event->setEventUrl(line.section(QLatin1Char(':'), 1)); continue; } else if (line.startsWith(QLatin1String("X-TYPE:"))) { event->setEvpentUrlType(line.section(QLatin1Char(':'), 1)); continue; } else if (line.startsWith(QLatin1String("X-ROOMNAME:"))) { event->setRoomName(line.section(QLatin1Char(':'), 1)); continue; } }while(!line.contains(QByteArray("END:VEVENT"))); m_eventList.append(event); } QList <QCalEvent*> QCalParser::getEventList() { return m_eventList; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: officeforms.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:17:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_FORMS_OFFICEFORMS_HXX_ #include "officeforms.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _COMPHELPER_EXTRACT_HXX_ #include <comphelper/extract.hxx> #endif #ifndef _XMLOFF_FORMS_STRINGS_HXX_ #include "strings.hxx" #endif #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif //......................................................................... namespace xmloff { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::xml; using ::xmloff::token::XML_FORMS; //========================================================================= //= OFormsRootImport //========================================================================= TYPEINIT1(OFormsRootImport, SvXMLImportContext); //------------------------------------------------------------------------- OFormsRootImport::OFormsRootImport( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName ) :SvXMLImportContext(rImport, nPrfx, rLocalName) { } //------------------------------------------------------------------------- OFormsRootImport::~OFormsRootImport() { } //------------------------------------------------------------------------- SvXMLImportContext* OFormsRootImport::CreateChildContext( USHORT _nPrefix, const ::rtl::OUString& _rLocalName, const Reference< sax::XAttributeList>& xAttrList ) { return GetImport().GetFormImport()->createContext( _nPrefix, _rLocalName, xAttrList ); } //------------------------------------------------------------------------- void OFormsRootImport::implImportBool(const Reference< sax::XAttributeList >& _rxAttributes, OfficeFormsAttributes _eAttribute, const Reference< XPropertySet >& _rxProps, const Reference< XPropertySetInfo >& _rxPropInfo, const ::rtl::OUString& _rPropName, sal_Bool _bDefault) { // the complete attribute name to look for ::rtl::OUString sCompleteAttributeName = GetImport().GetNamespaceMap().GetQNameByIndex( OAttributeMetaData::getOfficeFormsAttributeNamespace(_eAttribute), ::rtl::OUString::createFromAscii(OAttributeMetaData::getOfficeFormsAttributeName(_eAttribute))); // get and convert the value ::rtl::OUString sAttributeValue = _rxAttributes->getValueByName(sCompleteAttributeName); sal_Bool bValue = _bDefault; GetImport().GetMM100UnitConverter().convertBool(bValue, sAttributeValue); // set the property if (_rxPropInfo->hasPropertyByName(_rPropName)) _rxProps->setPropertyValue(_rPropName, ::cppu::bool2any(bValue)); } //------------------------------------------------------------------------- void OFormsRootImport::StartElement( const Reference< sax::XAttributeList >& _rxAttrList ) { ENTER_LOG_CONTEXT( "xmloff::OFormsRootImport - importing the complete tree" ); SvXMLImportContext::StartElement( _rxAttrList ); try { Reference< XPropertySet > xDocProperties(GetImport().GetModel(), UNO_QUERY); if ( xDocProperties.is() ) { // an empty model is allowed: when doing a copy'n'paste from e.g. Writer to Calc, // this is done via streaming the controls as XML. Reference< XPropertySetInfo > xDocPropInfo; if (xDocProperties.is()) xDocPropInfo = xDocProperties->getPropertySetInfo(); implImportBool(_rxAttrList, ofaAutomaticFocus, xDocProperties, xDocPropInfo, PROPERTY_AUTOCONTROLFOCUS, sal_False); implImportBool(_rxAttrList, ofaApplyDesignMode, xDocProperties, xDocPropInfo, PROPERTY_APPLYDESIGNMODE, sal_True); } } catch(Exception&) { OSL_ENSURE(sal_False, "OFormsRootImport::StartElement: caught an exception while setting the document properties!"); } } //------------------------------------------------------------------------- void OFormsRootImport::EndElement() { SvXMLImportContext::EndElement(); LEAVE_LOG_CONTEXT( ); } //===================================================================== //= OFormsRootExport //===================================================================== //--------------------------------------------------------------------- OFormsRootExport::OFormsRootExport( SvXMLExport& _rExp ) :m_pImplElement(NULL) { addModelAttributes(_rExp); m_pImplElement = new SvXMLElementExport(_rExp, XML_NAMESPACE_OFFICE, XML_FORMS, sal_True, sal_True); } //--------------------------------------------------------------------- OFormsRootExport::~OFormsRootExport( ) { delete m_pImplElement; } //------------------------------------------------------------------------- void OFormsRootExport::implExportBool(SvXMLExport& _rExp, OfficeFormsAttributes _eAttribute, const Reference< XPropertySet >& _rxProps, const Reference< XPropertySetInfo >& _rxPropInfo, const ::rtl::OUString& _rPropName, sal_Bool _bDefault) { // retrieve the property value sal_Bool bValue = _bDefault; if (_rxPropInfo->hasPropertyByName(_rPropName)) bValue = ::cppu::any2bool(_rxProps->getPropertyValue(_rPropName)); // convert into a string ::rtl::OUStringBuffer aValue; _rExp.GetMM100UnitConverter().convertBool(aValue, bValue); // add the attribute _rExp.AddAttribute( OAttributeMetaData::getOfficeFormsAttributeNamespace(_eAttribute), OAttributeMetaData::getOfficeFormsAttributeName(_eAttribute), aValue.makeStringAndClear()); } //------------------------------------------------------------------------- void OFormsRootExport::addModelAttributes(SvXMLExport& _rExp) SAL_THROW(()) { try { Reference< XPropertySet > xDocProperties(_rExp.GetModel(), UNO_QUERY); if ( xDocProperties.is() ) { // an empty model is allowed: when doing a copy'n'paste from e.g. Writer to Calc, // this is done via streaming the controls as XML. Reference< XPropertySetInfo > xDocPropInfo; if (xDocProperties.is()) xDocPropInfo = xDocProperties->getPropertySetInfo(); implExportBool(_rExp, ofaAutomaticFocus, xDocProperties, xDocPropInfo, PROPERTY_AUTOCONTROLFOCUS, sal_False); implExportBool(_rExp, ofaApplyDesignMode, xDocProperties, xDocPropInfo, PROPERTY_APPLYDESIGNMODE, sal_True); } } catch(Exception&) { OSL_ENSURE(sal_False, "OFormsRootExport::addModelAttributes: caught an exception while retrieving the document properties!"); } } //......................................................................... } // namespace xmloff //......................................................................... <commit_msg>INTEGRATION: CWS changefileheader (1.10.162); FILE MERGED 2008/04/01 16:09:47 thb 1.10.162.3: #i85898# Stripping all external header guards 2008/04/01 13:04:53 thb 1.10.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:13 rt 1.10.162.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: officeforms.cxx,v $ * $Revision: 1.11 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include "officeforms.hxx" #include <xmloff/xmluconv.hxx> #include <xmloff/xmltoken.hxx> #include "xmlnmspe.hxx" #include <xmloff/xmlexp.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/nmspmap.hxx> #include <comphelper/extract.hxx> #include "strings.hxx" #include <rtl/logfile.hxx> //......................................................................... namespace xmloff { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::xml; using ::xmloff::token::XML_FORMS; //========================================================================= //= OFormsRootImport //========================================================================= TYPEINIT1(OFormsRootImport, SvXMLImportContext); //------------------------------------------------------------------------- OFormsRootImport::OFormsRootImport( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName ) :SvXMLImportContext(rImport, nPrfx, rLocalName) { } //------------------------------------------------------------------------- OFormsRootImport::~OFormsRootImport() { } //------------------------------------------------------------------------- SvXMLImportContext* OFormsRootImport::CreateChildContext( USHORT _nPrefix, const ::rtl::OUString& _rLocalName, const Reference< sax::XAttributeList>& xAttrList ) { return GetImport().GetFormImport()->createContext( _nPrefix, _rLocalName, xAttrList ); } //------------------------------------------------------------------------- void OFormsRootImport::implImportBool(const Reference< sax::XAttributeList >& _rxAttributes, OfficeFormsAttributes _eAttribute, const Reference< XPropertySet >& _rxProps, const Reference< XPropertySetInfo >& _rxPropInfo, const ::rtl::OUString& _rPropName, sal_Bool _bDefault) { // the complete attribute name to look for ::rtl::OUString sCompleteAttributeName = GetImport().GetNamespaceMap().GetQNameByIndex( OAttributeMetaData::getOfficeFormsAttributeNamespace(_eAttribute), ::rtl::OUString::createFromAscii(OAttributeMetaData::getOfficeFormsAttributeName(_eAttribute))); // get and convert the value ::rtl::OUString sAttributeValue = _rxAttributes->getValueByName(sCompleteAttributeName); sal_Bool bValue = _bDefault; GetImport().GetMM100UnitConverter().convertBool(bValue, sAttributeValue); // set the property if (_rxPropInfo->hasPropertyByName(_rPropName)) _rxProps->setPropertyValue(_rPropName, ::cppu::bool2any(bValue)); } //------------------------------------------------------------------------- void OFormsRootImport::StartElement( const Reference< sax::XAttributeList >& _rxAttrList ) { ENTER_LOG_CONTEXT( "xmloff::OFormsRootImport - importing the complete tree" ); SvXMLImportContext::StartElement( _rxAttrList ); try { Reference< XPropertySet > xDocProperties(GetImport().GetModel(), UNO_QUERY); if ( xDocProperties.is() ) { // an empty model is allowed: when doing a copy'n'paste from e.g. Writer to Calc, // this is done via streaming the controls as XML. Reference< XPropertySetInfo > xDocPropInfo; if (xDocProperties.is()) xDocPropInfo = xDocProperties->getPropertySetInfo(); implImportBool(_rxAttrList, ofaAutomaticFocus, xDocProperties, xDocPropInfo, PROPERTY_AUTOCONTROLFOCUS, sal_False); implImportBool(_rxAttrList, ofaApplyDesignMode, xDocProperties, xDocPropInfo, PROPERTY_APPLYDESIGNMODE, sal_True); } } catch(Exception&) { OSL_ENSURE(sal_False, "OFormsRootImport::StartElement: caught an exception while setting the document properties!"); } } //------------------------------------------------------------------------- void OFormsRootImport::EndElement() { SvXMLImportContext::EndElement(); LEAVE_LOG_CONTEXT( ); } //===================================================================== //= OFormsRootExport //===================================================================== //--------------------------------------------------------------------- OFormsRootExport::OFormsRootExport( SvXMLExport& _rExp ) :m_pImplElement(NULL) { addModelAttributes(_rExp); m_pImplElement = new SvXMLElementExport(_rExp, XML_NAMESPACE_OFFICE, XML_FORMS, sal_True, sal_True); } //--------------------------------------------------------------------- OFormsRootExport::~OFormsRootExport( ) { delete m_pImplElement; } //------------------------------------------------------------------------- void OFormsRootExport::implExportBool(SvXMLExport& _rExp, OfficeFormsAttributes _eAttribute, const Reference< XPropertySet >& _rxProps, const Reference< XPropertySetInfo >& _rxPropInfo, const ::rtl::OUString& _rPropName, sal_Bool _bDefault) { // retrieve the property value sal_Bool bValue = _bDefault; if (_rxPropInfo->hasPropertyByName(_rPropName)) bValue = ::cppu::any2bool(_rxProps->getPropertyValue(_rPropName)); // convert into a string ::rtl::OUStringBuffer aValue; _rExp.GetMM100UnitConverter().convertBool(aValue, bValue); // add the attribute _rExp.AddAttribute( OAttributeMetaData::getOfficeFormsAttributeNamespace(_eAttribute), OAttributeMetaData::getOfficeFormsAttributeName(_eAttribute), aValue.makeStringAndClear()); } //------------------------------------------------------------------------- void OFormsRootExport::addModelAttributes(SvXMLExport& _rExp) SAL_THROW(()) { try { Reference< XPropertySet > xDocProperties(_rExp.GetModel(), UNO_QUERY); if ( xDocProperties.is() ) { // an empty model is allowed: when doing a copy'n'paste from e.g. Writer to Calc, // this is done via streaming the controls as XML. Reference< XPropertySetInfo > xDocPropInfo; if (xDocProperties.is()) xDocPropInfo = xDocProperties->getPropertySetInfo(); implExportBool(_rExp, ofaAutomaticFocus, xDocProperties, xDocPropInfo, PROPERTY_AUTOCONTROLFOCUS, sal_False); implExportBool(_rExp, ofaApplyDesignMode, xDocProperties, xDocPropInfo, PROPERTY_APPLYDESIGNMODE, sal_True); } } catch(Exception&) { OSL_ENSURE(sal_False, "OFormsRootExport::addModelAttributes: caught an exception while retrieving the document properties!"); } } //......................................................................... } // namespace xmloff //......................................................................... <|endoftext|>
<commit_before>#pragma once #include <condition_variable> #include <functional> #include <limits> #include <mutex> #include <queue> namespace dai { template <typename T> class LockingQueue { public: LockingQueue() = default; explicit LockingQueue(unsigned maxSize, bool blocking = true) { this->maxSize = maxSize; this->blocking = blocking; } void setMaxSize(unsigned sz) { // Lock first std::unique_lock<std::mutex> lock(guard); maxSize = sz; } void setBlocking(bool bl) { // Lock first std::unique_lock<std::mutex> lock(guard); blocking = bl; } unsigned getMaxSize() const { // Lock first std::unique_lock<std::mutex> lock(guard); return maxSize; } bool getBlocking() const { // Lock first std::unique_lock<std::mutex> lock(guard); return blocking; } void destruct() { destructed = true; signalPop.notify_all(); signalPush.notify_all(); } ~LockingQueue() = default; template <typename Rep, typename Period> bool waitAndConsumeAll(std::function<void(T&)> callback, std::chrono::duration<Rep, Period> timeout) { { std::unique_lock<std::mutex> lock(guard); // First checks predicate, then waits bool pred = signalPush.wait_for(lock, timeout, [this]() { return !queue.empty() || destructed; }); if(destructed) return false; if(!pred) return false; // Continue here if and only if queue has any elements while(!queue.empty()) { callback(queue.front()); queue.pop(); } } signalPop.notify_all(); return true; } bool waitAndConsumeAll(std::function<void(T&)> callback) { { std::unique_lock<std::mutex> lock(guard); signalPush.wait(lock, [this]() { return !queue.empty() || destructed; }); if(destructed) return false; if(queue.empty()) return false; while(!queue.empty()) { callback(queue.front()); queue.pop(); } } signalPop.notify_all(); return true; } bool consumeAll(std::function<void(T&)> callback) { { std::lock_guard<std::mutex> lock(guard); if(queue.empty()) return false; while(!queue.empty()) { callback(queue.front()); queue.pop(); } } signalPop.notify_all(); return true; } bool push(T const& data) { { std::unique_lock<std::mutex> lock(guard); if(!blocking) { // if non blocking, remove as many oldest elements as necessary, so next one will fit // necessary if maxSize was changed while(queue.size() >= maxSize) { queue.pop(); } } else { signalPop.wait(lock, [this]() { return queue.size() < maxSize || destructed; }); if(destructed) return false; } queue.push(data); } signalPush.notify_all(); return true; } template <typename Rep, typename Period> bool tryWaitAndPush(T const& data, std::chrono::duration<Rep, Period> timeout) { { std::unique_lock<std::mutex> lock(guard); if(!blocking) { // if non blocking, remove as many oldest elements as necessary, so next one will fit // necessary if maxSize was changed while(queue.size() >= maxSize) { queue.pop(); } } else { // First checks predicate, then waits bool pred = signalPop.wait_for(lock, timeout, [this]() { return queue.size() < maxSize || destructed; }); if(!pred) return false; if(destructed) return false; } queue.push(data); } signalPush.notify_all(); return true; } bool empty() const { std::lock_guard<std::mutex> lock(guard); return queue.empty(); } bool front(T& value) { std::unique_lock<std::mutex> lock(guard); if(queue.empty()) { return false; } value = queue.front(); return true; } bool tryPop(T& value) { { std::lock_guard<std::mutex> lock(guard); if(queue.empty()) { return false; } value = queue.front(); queue.pop(); } signalPop.notify_all(); return true; } bool waitAndPop(T& value) { { std::unique_lock<std::mutex> lock(guard); signalPush.wait(lock, [this]() { return (!queue.empty() || destructed); }); if(destructed) return false; if(queue.empty()) return false; value = queue.front(); queue.pop(); } signalPop.notify_all(); return true; } template <typename Rep, typename Period> bool tryWaitAndPop(T& value, std::chrono::duration<Rep, Period> timeout) { { std::unique_lock<std::mutex> lock(guard); // First checks predicate, then waits bool pred = signalPush.wait_for(lock, timeout, [this]() { return !queue.empty() || destructed; }); if(destructed) return false; if(!pred) return false; value = queue.front(); queue.pop(); } signalPop.notify_all(); return true; } void waitEmpty() { std::unique_lock<std::mutex> lock(guard); signalPop.wait(lock, [this]() { return queue.empty() || destructed; }); } private: unsigned maxSize = std::numeric_limits<unsigned>::max(); bool blocking = true; std::queue<T> queue; mutable std::mutex guard; std::atomic<bool> destructed{false}; std::condition_variable signalPop; std::condition_variable signalPush; }; } // namespace dai <commit_msg>Throw value error if queue size 0 is specified<commit_after>#pragma once #include <condition_variable> #include <functional> #include <limits> #include <mutex> #include <queue> namespace dai { template <typename T> class LockingQueue { public: LockingQueue() = default; explicit LockingQueue(unsigned maxSize, bool blocking = true) { this->maxSize = maxSize; this->blocking = blocking; } void setMaxSize(unsigned sz) { // Lock first if(sz == 0) throw std::invalid_argument("Queue size can't be 0!"); std::unique_lock<std::mutex> lock(guard); maxSize = sz; } void setBlocking(bool bl) { // Lock first std::unique_lock<std::mutex> lock(guard); blocking = bl; } unsigned getMaxSize() const { // Lock first std::unique_lock<std::mutex> lock(guard); return maxSize; } bool getBlocking() const { // Lock first std::unique_lock<std::mutex> lock(guard); return blocking; } void destruct() { destructed = true; signalPop.notify_all(); signalPush.notify_all(); } ~LockingQueue() = default; template <typename Rep, typename Period> bool waitAndConsumeAll(std::function<void(T&)> callback, std::chrono::duration<Rep, Period> timeout) { { std::unique_lock<std::mutex> lock(guard); // First checks predicate, then waits bool pred = signalPush.wait_for(lock, timeout, [this]() { return !queue.empty() || destructed; }); if(destructed) return false; if(!pred) return false; // Continue here if and only if queue has any elements while(!queue.empty()) { callback(queue.front()); queue.pop(); } } signalPop.notify_all(); return true; } bool waitAndConsumeAll(std::function<void(T&)> callback) { { std::unique_lock<std::mutex> lock(guard); signalPush.wait(lock, [this]() { return !queue.empty() || destructed; }); if(destructed) return false; if(queue.empty()) return false; while(!queue.empty()) { callback(queue.front()); queue.pop(); } } signalPop.notify_all(); return true; } bool consumeAll(std::function<void(T&)> callback) { { std::lock_guard<std::mutex> lock(guard); if(queue.empty()) return false; while(!queue.empty()) { callback(queue.front()); queue.pop(); } } signalPop.notify_all(); return true; } bool push(T const& data) { { std::unique_lock<std::mutex> lock(guard); if(!blocking) { // if non blocking, remove as many oldest elements as necessary, so next one will fit // necessary if maxSize was changed while(queue.size() >= maxSize) { queue.pop(); } } else { signalPop.wait(lock, [this]() { return queue.size() < maxSize || destructed; }); if(destructed) return false; } queue.push(data); } signalPush.notify_all(); return true; } template <typename Rep, typename Period> bool tryWaitAndPush(T const& data, std::chrono::duration<Rep, Period> timeout) { { std::unique_lock<std::mutex> lock(guard); if(!blocking) { // if non blocking, remove as many oldest elements as necessary, so next one will fit // necessary if maxSize was changed while(queue.size() >= maxSize) { queue.pop(); } } else { // First checks predicate, then waits bool pred = signalPop.wait_for(lock, timeout, [this]() { return queue.size() < maxSize || destructed; }); if(!pred) return false; if(destructed) return false; } queue.push(data); } signalPush.notify_all(); return true; } bool empty() const { std::lock_guard<std::mutex> lock(guard); return queue.empty(); } bool front(T& value) { std::unique_lock<std::mutex> lock(guard); if(queue.empty()) { return false; } value = queue.front(); return true; } bool tryPop(T& value) { { std::lock_guard<std::mutex> lock(guard); if(queue.empty()) { return false; } value = queue.front(); queue.pop(); } signalPop.notify_all(); return true; } bool waitAndPop(T& value) { { std::unique_lock<std::mutex> lock(guard); signalPush.wait(lock, [this]() { return (!queue.empty() || destructed); }); if(destructed) return false; if(queue.empty()) return false; value = queue.front(); queue.pop(); } signalPop.notify_all(); return true; } template <typename Rep, typename Period> bool tryWaitAndPop(T& value, std::chrono::duration<Rep, Period> timeout) { { std::unique_lock<std::mutex> lock(guard); // First checks predicate, then waits bool pred = signalPush.wait_for(lock, timeout, [this]() { return !queue.empty() || destructed; }); if(destructed) return false; if(!pred) return false; value = queue.front(); queue.pop(); } signalPop.notify_all(); return true; } void waitEmpty() { std::unique_lock<std::mutex> lock(guard); signalPop.wait(lock, [this]() { return queue.empty() || destructed; }); } private: unsigned maxSize = std::numeric_limits<unsigned>::max(); bool blocking = true; std::queue<T> queue; mutable std::mutex guard; std::atomic<bool> destructed{false}; std::condition_variable signalPop; std::condition_variable signalPush; }; } // namespace dai <|endoftext|>
<commit_before>/* * Copyright 2014, Nicolas Mansard, LAAS-CNRS * * This file is part of eigenpy. * eigenpy is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __eigenpy_quaternion_hpp__ #define __eigenpy_quaternion_hpp__ #include <Eigen/Core> #include <Eigen/Geometry> #include "eigenpy/exception.hpp" namespace eigenpy { class ExceptionIndex : public Exception { public: ExceptionIndex(int index,int imin,int imax) : Exception("") { std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<"."; message = oss.str(); } }; namespace bp = boost::python; template<typename Quaternion> class QuaternionVisitor : public boost::python::def_visitor< QuaternionVisitor<Quaternion> > { typedef Eigen::QuaternionBase<Quaternion> QuaternionBase; typedef typename QuaternionBase::Scalar Scalar; typedef typename Quaternion::Coefficients Coefficients; typedef typename QuaternionBase::Vector3 Vector3; typedef typename Eigen::Matrix<Scalar,4,1> Vector4; typedef typename QuaternionBase::Matrix3 Matrix3; typedef typename QuaternionBase::AngleAxisType AngleAxis; public: template<class PyClass> void visit(PyClass& cl) const { cl .def(bp::init<>("Default constructor")) .def(bp::init<Matrix3>((bp::arg("matrixRotation")),"Initialize from rotation matrix.")) .def(bp::init<AngleAxis>((bp::arg("angleaxis")),"Initialize from angle axis.")) .def(bp::init<Quaternion>((bp::arg("clone")),"Copy constructor.")) .def("__init__",bp::make_constructor(&QuaternionVisitor::FromTwoVectors, bp::default_call_policies(), (bp::arg("u"),bp::arg("v"))),"Initialize from two vector u,v") .def(bp::init<Scalar,Scalar,Scalar,Scalar> ((bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")), "Initialize from coefficients.\n\n" "... note:: The order of coefficients is *w*, *x*, *y*, *z*. " "The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!")) .add_property("x", (Scalar (Quaternion::*)()const)&Quaternion::x, &QuaternionVisitor::setCoeff<0>,"The x coefficient.") .add_property("y", (Scalar (Quaternion::*)()const)&Quaternion::y, &QuaternionVisitor::setCoeff<1>,"The y coefficient.") .add_property("z", (Scalar (Quaternion::*)()const)&Quaternion::z, &QuaternionVisitor::setCoeff<2>,"The z coefficient.") .add_property("w", (Scalar (Quaternion::*)()const)&Quaternion::w, &QuaternionVisitor::setCoeff<3>,"The w coefficient.") // .def("isApprox",(bool (Quaternion::*)(const Quaternion &))&Quaternion::template isApprox<Quaternion>, // "Returns true if *this is approximately equal to other.") // .def("isApprox",(bool (Quaternion::*)(const Quaternion &, const Scalar prec))&Quaternion::template isApprox<Quaternion>, // "Returns true if *this is approximately equal to other, within the precision determined by prec..") .def("isApprox",(bool (*)(const Quaternion &))&isApprox, "Returns true if *this is approximately equal to other.") .def("isApprox",(bool (*)(const Quaternion &, const Scalar prec))&isApprox, "Returns true if *this is approximately equal to other, within the precision determined by prec..") /* --- Methods --- */ .def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs, bp::return_value_policy<bp::copy_const_reference>()) .def("matrix",&Quaternion::matrix,"Returns an equivalent rotation matrix") .def("toRotationMatrix ",&Quaternion::toRotationMatrix,"Returns an equivalent 3x3 rotation matrix.") .def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("a"),bp::arg("b"))),"Set *this to be the quaternion which transform a into b through a rotation." ,bp::return_self<>()) .def("conjugate",&Quaternion::conjugate,"Returns the conjugated quaternion. The conjugate of a quaternion represents the opposite rotation.") .def("inverse",&Quaternion::inverse,"Returns the quaternion describing the inverse rotation.") .def("setIdentity",&Quaternion::setIdentity,bp::return_self<>(),"Set *this to the idendity rotation.") .def("norm",&Quaternion::norm,"Returns the norm of the quaternion's coefficients.") .def("normalize",&Quaternion::normalize,"Normalizes the quaternion *this.") .def("normalized",&Quaternion::normalized,"Returns a normalized copy of *this.") .def("squaredNorm",&Quaternion::squaredNorm,"Returns the squared norm of the quaternion's coefficients.") .def("dot",&Quaternion::template dot<Quaternion>,bp::arg("other"),"Returns the dot product of *this with other" "Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.") .def("_transformVector",&Quaternion::_transformVector,bp::arg("vector"),"Rotation of a vector by a quaternion.") .def("vec",&vec,"Returns a vector expression of the imaginary part (x,y,z).") .def("angularDistance",&Quaternion::template angularDistance<Quaternion>,"Returns the angle (in radian) between two rotations.") .def("slerp",&Quaternion::template slerp<Quaternion>,bp::args("t","other"), "Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].") /* --- Operators --- */ .def(bp::self * bp::self) .def(bp::self *= bp::self) .def(bp::self * bp::other<Vector3>()) .def("__eq__",&QuaternionVisitor::__eq__) .def("__ne__",&QuaternionVisitor::__ne__) .def("__abs__",&Quaternion::norm) .def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__") .def("__setitem__",&QuaternionVisitor::__setitem__) .def("__getitem__",&QuaternionVisitor::__getitem__) .def("assign",&assign<Quaternion>, bp::arg("quat"),"Set *this from an quaternion quat and returns a reference to *this.",bp::return_self<>()) .def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=, bp::arg("aa"),"Set *this from an angle-axis aa and returns a reference to *this.",bp::return_self<>()) .def("__str__",&print) .def("__repr__",&print) // .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>, // bp::args("a","b"), // "Returns the quaternion which transform a into b through a rotation.") .def("FromTwoVectors",&FromTwoVectors, bp::args("a","b"), "Returns the quaternion which transform a into b through a rotation.", bp::return_value_policy<bp::manage_new_object>()) .staticmethod("FromTwoVectors") .def("Identity",&Quaternion::Identity,"Returns a quaternion representing an identity rotation.") .staticmethod("Identity") ; } private: template<int i> static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; } static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b) { return self.setFromTwoVectors(a,b); } template<typename OtherQuat> static Quaternion & assign(Quaternion & self, const OtherQuat & quat) { return self = quat; } static Quaternion* FromTwoVectors(const Vector3& u, const Vector3& v) { Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v); return q; } static bool isApprox(const Quaternion & self, const Quaternion & other, const Scalar prec = Eigen::NumTraits<Scalar>::dummy_precision) { return self.isApprox(other,prec); } static bool __eq__(const Quaternion& u, const Quaternion& v) { return u.isApprox(v,1e-9); } static bool __ne__(const Quaternion& u, const Quaternion& v) { return !__eq__(u,v); } static Scalar __getitem__(const Quaternion & self, int idx) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); return self.coeffs()[idx]; } static void __setitem__(Quaternion& self, int idx, const Scalar value) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); self.coeffs()[idx] = value; } static int __len__() { return 4; } static Vector3 vec(const Quaternion & self) { return self.vec(); } static std::string print(const Quaternion & self) { std::stringstream ss; ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl; return ss.str(); } public: static void expose() { bp::class_<Quaternion>("Quaternion", "Quaternion representing rotation.\n\n" "Supported operations " "('q is a Quaternion, 'v' is a Vector3): " "'q*q' (rotation composition), " "'q*=q', " "'q*v' (rotating 'v' by 'q'), " "'q==q', 'q!=q', 'q[0..3]'.", bp::no_init) .def(QuaternionVisitor<Quaternion>()) ; } }; } // namespace eigenpy #endif // ifndef __eigenpy_quaternion_hpp__ <commit_msg>[Geometry] Make Quaternion with newest versions of Eigen<commit_after>/* * Copyright 2014, Nicolas Mansard, LAAS-CNRS * * This file is part of eigenpy. * eigenpy is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __eigenpy_quaternion_hpp__ #define __eigenpy_quaternion_hpp__ #include <Eigen/Core> #include <Eigen/Geometry> #include "eigenpy/exception.hpp" namespace eigenpy { class ExceptionIndex : public Exception { public: ExceptionIndex(int index,int imin,int imax) : Exception("") { std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<"."; message = oss.str(); } }; namespace bp = boost::python; template<typename Quaternion> class QuaternionVisitor : public boost::python::def_visitor< QuaternionVisitor<Quaternion> > { typedef Eigen::QuaternionBase<Quaternion> QuaternionBase; typedef typename QuaternionBase::Scalar Scalar; typedef typename Quaternion::Coefficients Coefficients; typedef typename QuaternionBase::Vector3 Vector3; typedef typename Eigen::Matrix<Scalar,4,1> Vector4; typedef typename QuaternionBase::Matrix3 Matrix3; typedef typename QuaternionBase::AngleAxisType AngleAxis; public: template<class PyClass> void visit(PyClass& cl) const { cl .def(bp::init<>("Default constructor")) .def(bp::init<Matrix3>((bp::arg("matrixRotation")),"Initialize from rotation matrix.")) .def(bp::init<AngleAxis>((bp::arg("angleaxis")),"Initialize from angle axis.")) .def(bp::init<Quaternion>((bp::arg("clone")),"Copy constructor.")) .def("__init__",bp::make_constructor(&QuaternionVisitor::FromTwoVectors, bp::default_call_policies(), (bp::arg("u"),bp::arg("v"))),"Initialize from two vector u,v") .def(bp::init<Scalar,Scalar,Scalar,Scalar> ((bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")), "Initialize from coefficients.\n\n" "... note:: The order of coefficients is *w*, *x*, *y*, *z*. " "The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!")) .add_property("x", &QuaternionVisitor::getCoeff<0>, &QuaternionVisitor::setCoeff<0>,"The x coefficient.") .add_property("y", &QuaternionVisitor::getCoeff<1>, &QuaternionVisitor::setCoeff<1>,"The y coefficient.") .add_property("z", &QuaternionVisitor::getCoeff<2>, &QuaternionVisitor::setCoeff<2>,"The z coefficient.") .add_property("w", &QuaternionVisitor::getCoeff<3>, &QuaternionVisitor::setCoeff<3>,"The w coefficient.") // .def("isApprox",(bool (Quaternion::*)(const Quaternion &))&Quaternion::template isApprox<Quaternion>, // "Returns true if *this is approximately equal to other.") // .def("isApprox",(bool (Quaternion::*)(const Quaternion &, const Scalar prec))&Quaternion::template isApprox<Quaternion>, // "Returns true if *this is approximately equal to other, within the precision determined by prec..") .def("isApprox",(bool (*)(const Quaternion &))&isApprox, "Returns true if *this is approximately equal to other.") .def("isApprox",(bool (*)(const Quaternion &, const Scalar prec))&isApprox, "Returns true if *this is approximately equal to other, within the precision determined by prec..") /* --- Methods --- */ .def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs, bp::return_value_policy<bp::copy_const_reference>()) .def("matrix",&Quaternion::matrix,"Returns an equivalent rotation matrix") .def("toRotationMatrix ",&Quaternion::toRotationMatrix,"Returns an equivalent 3x3 rotation matrix.") .def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("a"),bp::arg("b"))),"Set *this to be the quaternion which transform a into b through a rotation." ,bp::return_self<>()) .def("conjugate",&Quaternion::conjugate,"Returns the conjugated quaternion. The conjugate of a quaternion represents the opposite rotation.") .def("inverse",&Quaternion::inverse,"Returns the quaternion describing the inverse rotation.") .def("setIdentity",&Quaternion::setIdentity,bp::return_self<>(),"Set *this to the idendity rotation.") .def("norm",&Quaternion::norm,"Returns the norm of the quaternion's coefficients.") .def("normalize",&Quaternion::normalize,"Normalizes the quaternion *this.") .def("normalized",&Quaternion::normalized,"Returns a normalized copy of *this.") .def("squaredNorm",&Quaternion::squaredNorm,"Returns the squared norm of the quaternion's coefficients.") .def("dot",&Quaternion::template dot<Quaternion>,bp::arg("other"),"Returns the dot product of *this with other" "Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.") .def("_transformVector",&Quaternion::_transformVector,bp::arg("vector"),"Rotation of a vector by a quaternion.") .def("vec",&vec,"Returns a vector expression of the imaginary part (x,y,z).") .def("angularDistance",&Quaternion::template angularDistance<Quaternion>,"Returns the angle (in radian) between two rotations.") .def("slerp",&Quaternion::template slerp<Quaternion>,bp::args("t","other"), "Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].") /* --- Operators --- */ .def(bp::self * bp::self) .def(bp::self *= bp::self) .def(bp::self * bp::other<Vector3>()) .def("__eq__",&QuaternionVisitor::__eq__) .def("__ne__",&QuaternionVisitor::__ne__) .def("__abs__",&Quaternion::norm) .def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__") .def("__setitem__",&QuaternionVisitor::__setitem__) .def("__getitem__",&QuaternionVisitor::__getitem__) .def("assign",&assign<Quaternion>, bp::arg("quat"),"Set *this from an quaternion quat and returns a reference to *this.",bp::return_self<>()) .def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=, bp::arg("aa"),"Set *this from an angle-axis aa and returns a reference to *this.",bp::return_self<>()) .def("__str__",&print) .def("__repr__",&print) // .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>, // bp::args("a","b"), // "Returns the quaternion which transform a into b through a rotation.") .def("FromTwoVectors",&FromTwoVectors, bp::args("a","b"), "Returns the quaternion which transform a into b through a rotation.", bp::return_value_policy<bp::manage_new_object>()) .staticmethod("FromTwoVectors") .def("Identity",&Quaternion::Identity,"Returns a quaternion representing an identity rotation.") .staticmethod("Identity") ; } private: template<int i> static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; } template<int i> static Scalar getCoeff(Quaternion & self) { return self.coeffs()[i]; } static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b) { return self.setFromTwoVectors(a,b); } template<typename OtherQuat> static Quaternion & assign(Quaternion & self, const OtherQuat & quat) { return self = quat; } static Quaternion* FromTwoVectors(const Vector3& u, const Vector3& v) { Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v); return q; } static bool isApprox(const Quaternion & self, const Quaternion & other, const Scalar prec = Eigen::NumTraits<Scalar>::dummy_precision) { return self.isApprox(other,prec); } static bool __eq__(const Quaternion& u, const Quaternion& v) { return u.isApprox(v,1e-9); } static bool __ne__(const Quaternion& u, const Quaternion& v) { return !__eq__(u,v); } static Scalar __getitem__(const Quaternion & self, int idx) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); return self.coeffs()[idx]; } static void __setitem__(Quaternion& self, int idx, const Scalar value) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); self.coeffs()[idx] = value; } static int __len__() { return 4; } static Vector3 vec(const Quaternion & self) { return self.vec(); } static std::string print(const Quaternion & self) { std::stringstream ss; ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl; return ss.str(); } public: static void expose() { bp::class_<Quaternion>("Quaternion", "Quaternion representing rotation.\n\n" "Supported operations " "('q is a Quaternion, 'v' is a Vector3): " "'q*q' (rotation composition), " "'q*=q', " "'q*v' (rotating 'v' by 'q'), " "'q==q', 'q!=q', 'q[0..3]'.", bp::no_init) .def(QuaternionVisitor<Quaternion>()) ; } }; } // namespace eigenpy #endif // ifndef __eigenpy_quaternion_hpp__ <|endoftext|>
<commit_before>/* * function_traits.hpp * * Created on: Feb 2, 2016 * Author: zmij */ #ifndef WIRE_UTIL_FUNCTION_TRAITS_HPP_ #define WIRE_UTIL_FUNCTION_TRAITS_HPP_ #include <tuple> #include <wire/util/meta_helpers.hpp> namespace wire { namespace util { namespace detail { template <typename T> struct has_call_operator { private: struct _fallback { void operator()(); }; struct _derived : T, _fallback {}; template<typename U, U> struct _check; template<typename> static ::std::true_type test(...); template<typename C> static ::std::false_type test( _check<void (_fallback::*)(), &C::operator()>*); public: static const bool value = ::std::is_same< decltype(test<_derived>(0)), ::std::true_type >::value; }; } // namespace detail template < typename T > struct is_callable : ::std::conditional< ::std::is_class< T >::value, detail::has_call_operator< T >, ::std::is_function<T> >::type { }; /** * Primary function_traits template */ template < typename ... T > struct function_traits; template < typename T > struct not_a_function { static const int arity = -1; }; /** * function_traits for a function pointer with argument count > 1 */ template < typename Return, typename ... Args > struct function_traits< Return(*)(Args...) > { enum { arity = sizeof...(Args) }; using result_type = Return; using args_tuple_type = ::std::tuple< Args ... >; using decayed_args_tuple_type = ::std::tuple< typename ::std::decay<Args>::type ... >; template < size_t n> struct arg { using type = typename ::std::tuple_element<n, args_tuple_type>::type; }; }; /** * function_traits for a function pointer with argument count == 1 */ template < typename Return, typename Arg > struct function_traits< Return(*)(Arg) > { enum { arity = 1 }; using result_type = Return; using args_tuple_type = Arg; using decayed_args_tuple_type = typename ::std::decay<Arg>::type; }; /** * function_traits for a function pointer with argument count == 0 */ template < typename Return > struct function_traits< Return(*)() > { enum { arity = 0 }; using result_type = Return; using args_tuple_type = void; using decayed_args_tuple_type = void; }; /** * function_traits for a class member const function with argument count > 1 */ template < typename Class, typename Return, typename ... Args > struct function_traits< Return(Class::*)(Args...) const> { enum { arity = sizeof...(Args) }; using class_type = Class; using result_type = Return; using args_tuple_type = ::std::tuple< Args ... >; using decayed_args_tuple_type = ::std::tuple< typename ::std::decay<Args>::type ... >; template < size_t n> struct arg { using type = typename ::std::tuple_element<n, args_tuple_type>::type; }; }; /** * function_traits for a class member const function with argument count == 1 */ template < typename Class, typename Return, typename Arg > struct function_traits< Return(Class::*)(Arg) const > { enum { arity = 1 }; using class_type = Class; using result_type = Return; using args_tuple_type = Arg; using decayed_args_tuple_type = typename ::std::decay<Arg>::type; }; /** * function_traits for a class member const function with argument count == 0 */ template < typename Class, typename Return > struct function_traits< Return(Class::*)() const> { enum { arity = 0 }; using class_type = Class; using result_type = Return; using args_tuple_type = void; using decayed_args_tuple_type = void; }; /** * function_traits for a class member non-const function with argument count > 1 */ template < typename Class, typename Return, typename ... Args > struct function_traits< Return(Class::*)(Args...) > { enum { arity = sizeof...(Args) }; using class_type = Class; using result_type = Return; using args_tuple_type = ::std::tuple< Args ... >; using decayed_args_tuple_type = ::std::tuple< typename ::std::decay<Args>::type ... >; template < size_t n> struct arg { using type = typename ::std::tuple_element<n, args_tuple_type>::type; }; }; /** * function_traits for a class member non-const function with argument count == 1 */ template < typename Class, typename Return, typename Arg > struct function_traits< Return(Class::*)(Arg) > { enum { arity = 1 }; using class_type = Class; using result_type = Return; using args_tuple_type = Arg; using decayed_args_tuple_type = typename ::std::decay<Arg>::type; }; /** * function_traits for a class member non-const function with argument count == 0 */ template < typename Class, typename Return > struct function_traits< Return(Class::*)() > { enum { arity = 0 }; using class_type = Class; using result_type = Return; using args_tuple_type = void; using decayed_args_tuple_type = void; }; template < typename T > struct call_operator_traits : function_traits< decltype(&T::operator()) > {}; template < typename T > struct function_traits<T> : ::std::conditional< is_callable< T >::value, call_operator_traits< T >, not_a_function<T> >::type {}; template < typename Func > struct is_func_void : ::std::conditional< ::std::is_same< typename function_traits< Func >::result_type, void >::value, ::std::true_type, ::std::false_type >::type {}; namespace detail { template < typename Func, size_t ... Indexes, typename ... T > typename function_traits<Func>::result_type invoke(Func func, indexes_tuple< Indexes ... >, ::std::tuple< T ... >& args) { return func(::std::get<Indexes>(args) ...); } template < typename Func, size_t ... Indexes, typename ... T > typename function_traits<Func>::result_type invoke(Func func, indexes_tuple< Indexes ... >, T&& ... args) { return func(::std::forward<T>(args) ... ); } } // namespace detail template < typename Func, typename ... T > typename function_traits<Func>::result_type invoke(Func func, ::std::tuple< T ... >& args) { using index_type = typename index_builder< sizeof ... (T) >::type; return detail::invoke(func, index_type(), args); } template < typename Func, typename ... T > typename function_traits<Func>::result_type invoke(Func func, T&& ... args) { using index_type = typename index_builder< sizeof ... (T)>::type; return detail::invoke(func, index_type{}, ::std::forward<T>(args) ...); } } // namespace util } // namespace wire #endif /* WIRE_UTIL_FUNCTION_TRAITS_HPP_ */ <commit_msg>Move function_traits to metapushkin library<commit_after>/* * function_traits.hpp * * Created on: Feb 2, 2016 * Author: zmij */ #ifndef PSST_META_FUNCTION_TRAITS_HPP_ #define PSST_META_FUNCTION_TRAITS_HPP_ #include <tuple> #include <pushkin/meta/index_tuple.hpp> namespace psst { namespace meta { namespace detail { template <typename T> struct has_call_operator { private: struct _fallback { void operator()(); }; struct _derived : T, _fallback {}; template<typename U, U> struct _check; template<typename> static ::std::true_type test(...); template<typename C> static ::std::false_type test( _check<void (_fallback::*)(), &C::operator()>*); public: static const bool value = ::std::is_same< decltype(test<_derived>(0)), ::std::true_type >::value; }; } // namespace detail template < typename T > struct is_callable_object : ::std::conditional< ::std::is_class< T >::value, detail::has_call_operator< T >, ::std::is_function<T> >::type { }; /** * Primary function_traits template */ template < typename ... T > struct function_traits; template < typename T > struct not_a_function { static const int arity = -1; }; /** * function_traits for a function pointer with argument count > 1 */ template < typename Return, typename ... Args > struct function_traits< Return(*)(Args...) > { enum { arity = sizeof...(Args) }; using result_type = Return; using args_tuple_type = ::std::tuple< Args ... >; using decayed_args_tuple_type = ::std::tuple< typename ::std::decay<Args>::type ... >; template < size_t n> struct arg { using type = typename ::std::tuple_element<n, args_tuple_type>::type; }; }; /** * function_traits for a function pointer with argument count == 1 */ template < typename Return, typename Arg > struct function_traits< Return(*)(Arg) > { enum { arity = 1 }; using result_type = Return; using args_tuple_type = Arg; using decayed_args_tuple_type = typename ::std::decay<Arg>::type; }; /** * function_traits for a function pointer with argument count == 0 */ template < typename Return > struct function_traits< Return(*)() > { enum { arity = 0 }; using result_type = Return; using args_tuple_type = void; using decayed_args_tuple_type = void; }; /** * function_traits for a class member const function with argument count > 1 */ template < typename Class, typename Return, typename ... Args > struct function_traits< Return(Class::*)(Args...) const> { enum { arity = sizeof...(Args) }; using class_type = Class; using result_type = Return; using args_tuple_type = ::std::tuple< Args ... >; using decayed_args_tuple_type = ::std::tuple< typename ::std::decay<Args>::type ... >; template < size_t n> struct arg { using type = typename ::std::tuple_element<n, args_tuple_type>::type; }; }; /** * function_traits for a class member const function with argument count == 1 */ template < typename Class, typename Return, typename Arg > struct function_traits< Return(Class::*)(Arg) const > { enum { arity = 1 }; using class_type = Class; using result_type = Return; using args_tuple_type = Arg; using decayed_args_tuple_type = typename ::std::decay<Arg>::type; }; /** * function_traits for a class member const function with argument count == 0 */ template < typename Class, typename Return > struct function_traits< Return(Class::*)() const> { enum { arity = 0 }; using class_type = Class; using result_type = Return; using args_tuple_type = void; using decayed_args_tuple_type = void; }; /** * function_traits for a class member non-const function with argument count > 1 */ template < typename Class, typename Return, typename ... Args > struct function_traits< Return(Class::*)(Args...) > { enum { arity = sizeof...(Args) }; using class_type = Class; using result_type = Return; using args_tuple_type = ::std::tuple< Args ... >; using decayed_args_tuple_type = ::std::tuple< typename ::std::decay<Args>::type ... >; template < size_t n> struct arg { using type = typename ::std::tuple_element<n, args_tuple_type>::type; }; }; /** * function_traits for a class member non-const function with argument count == 1 */ template < typename Class, typename Return, typename Arg > struct function_traits< Return(Class::*)(Arg) > { enum { arity = 1 }; using class_type = Class; using result_type = Return; using args_tuple_type = Arg; using decayed_args_tuple_type = typename ::std::decay<Arg>::type; }; /** * function_traits for a class member non-const function with argument count == 0 */ template < typename Class, typename Return > struct function_traits< Return(Class::*)() > { enum { arity = 0 }; using class_type = Class; using result_type = Return; using args_tuple_type = void; using decayed_args_tuple_type = void; }; template < typename T > struct call_operator_traits : function_traits< decltype(&T::operator()) > {}; template < typename T > struct function_traits<T> : ::std::conditional< is_callable_object< T >::value, call_operator_traits< T >, not_a_function<T> >::type {}; template < typename Func > struct is_func_void : ::std::conditional< ::std::is_same< typename function_traits< Func >::result_type, void >::value, ::std::true_type, ::std::false_type >::type {}; namespace detail { template < typename Func, size_t ... Indexes, typename ... T > typename function_traits<Func>::result_type invoke(Func func, indexes_tuple< Indexes ... >, ::std::tuple< T ... >& args) { return func(::std::get<Indexes>(args) ...); } template < typename Func, size_t ... Indexes, typename ... T > typename function_traits<Func>::result_type invoke(Func func, indexes_tuple< Indexes ... >, T&& ... args) { return func(::std::forward<T>(args) ... ); } } // namespace detail template < typename Func, typename ... T > typename function_traits<Func>::result_type invoke(Func func, ::std::tuple< T ... >& args) { using index_type = typename index_builder< sizeof ... (T) >::type; return detail::invoke(func, index_type(), args); } template < typename Func, typename ... T > typename function_traits<Func>::result_type invoke(Func func, T&& ... args) { using index_type = typename index_builder< sizeof ... (T)>::type; return detail::invoke(func, index_type{}, ::std::forward<T>(args) ...); } } // namespace meta } // namespace psst #endif /* PSST_META_FUNCTION_TRAITS_HPP_ */ <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/client.h> #include <rpc/protocol.h> #include <util/system.h> #include <set> #include <stdint.h> class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert std::string paramName; //!< parameter name }; // clang-format off /** * Specify a (method, idx, name) here if the argument is a non-string RPC * argument and needs to be converted from JSON. * * @note Parameter indexes start from 0. */ static const CRPCConvertParam vRPCConvertParams[] = { { "setmocktime", 0, "timestamp" }, { "generate", 0, "nblocks" }, { "generate", 1, "maxtries" }, { "generatetoaddress", 0, "nblocks" }, { "generatetoaddress", 2, "maxtries" }, { "getnetworkhashps", 0, "nblocks" }, { "getnetworkhashps", 1, "height" }, { "sendtoaddress", 1, "amount" }, { "sendtoaddress", 4, "subtractfeefromamount" }, { "sendtoaddress", 5 , "replaceable" }, { "sendtoaddress", 6 , "conf_target" }, { "settxfee", 0, "amount" }, { "sethdseed", 0, "newkeypool" }, { "getreceivedbyaddress", 1, "minconf" }, { "getreceivedbylabel", 1, "minconf" }, { "listreceivedbyaddress", 0, "minconf" }, { "listreceivedbyaddress", 1, "include_empty" }, { "listreceivedbyaddress", 2, "include_watchonly" }, { "listreceivedbylabel", 0, "minconf" }, { "listreceivedbylabel", 1, "include_empty" }, { "listreceivedbylabel", 2, "include_watchonly" }, { "getbalance", 1, "minconf" }, { "getbalance", 2, "include_watchonly" }, { "getblockhash", 0, "height" }, { "waitforblockheight", 0, "height" }, { "waitforblockheight", 1, "timeout" }, { "waitforblock", 1, "timeout" }, { "waitfornewblock", 0, "timeout" }, { "listtransactions", 1, "count" }, { "listtransactions", 2, "skip" }, { "listtransactions", 3, "include_watchonly" }, { "walletpassphrase", 1, "timeout" }, { "getblocktemplate", 0, "template_request" }, { "listsinceblock", 1, "target_confirmations" }, { "listsinceblock", 2, "include_watchonly" }, { "listsinceblock", 3, "include_removed" }, { "sendmany", 1, "amounts" }, { "sendmany", 2, "minconf" }, { "sendmany", 4, "subtractfeefrom" }, { "sendmany", 5 , "replaceable" }, { "sendmany", 6 , "conf_target" }, { "deriveaddresses", 1, "range" }, { "scantxoutset", 1, "scanobjects" }, { "addmultisigaddress", 0, "nrequired" }, { "addmultisigaddress", 1, "keys" }, { "createmultisig", 0, "nrequired" }, { "createmultisig", 1, "keys" }, { "listunspent", 0, "minconf" }, { "listunspent", 1, "maxconf" }, { "listunspent", 2, "addresses" }, { "listunspent", 3, "include_unsafe" }, { "listunspent", 4, "query_options" }, { "getblock", 1, "verbosity" }, { "getblock", 1, "verbose" }, { "getblockheader", 1, "verbose" }, { "getchaintxstats", 0, "nblocks" }, { "gettransaction", 1, "include_watchonly" }, { "getrawtransaction", 1, "verbose" }, { "createrawtransaction", 0, "inputs" }, { "createrawtransaction", 1, "outputs" }, { "createrawtransaction", 2, "locktime" }, { "createrawtransaction", 3, "replaceable" }, { "decoderawtransaction", 1, "iswitness" }, { "signrawtransactionwithkey", 1, "privkeys" }, { "signrawtransactionwithkey", 2, "prevtxs" }, { "signrawtransactionwithwallet", 1, "prevtxs" }, { "sendrawtransaction", 1, "allowhighfees" }, { "sendrawtransaction", 1, "maxfeerate" }, { "testmempoolaccept", 0, "rawtxs" }, { "testmempoolaccept", 1, "allowhighfees" }, { "testmempoolaccept", 1, "maxfeerate" }, { "combinerawtransaction", 0, "txs" }, { "fundrawtransaction", 1, "options" }, { "fundrawtransaction", 2, "iswitness" }, { "walletcreatefundedpsbt", 0, "inputs" }, { "walletcreatefundedpsbt", 1, "outputs" }, { "walletcreatefundedpsbt", 2, "locktime" }, { "walletcreatefundedpsbt", 3, "options" }, { "walletcreatefundedpsbt", 4, "bip32derivs" }, { "walletprocesspsbt", 1, "sign" }, { "walletprocesspsbt", 3, "bip32derivs" }, { "createpsbt", 0, "inputs" }, { "createpsbt", 1, "outputs" }, { "createpsbt", 2, "locktime" }, { "createpsbt", 3, "replaceable" }, { "combinepsbt", 0, "txs"}, { "joinpsbts", 0, "txs"}, { "finalizepsbt", 1, "extract"}, { "converttopsbt", 1, "permitsigdata"}, { "converttopsbt", 2, "iswitness"}, { "gettxout", 1, "n" }, { "gettxout", 2, "include_mempool" }, { "gettxoutproof", 0, "txids" }, { "lockunspent", 0, "unlock" }, { "lockunspent", 1, "transactions" }, { "importprivkey", 2, "rescan" }, { "importaddress", 2, "rescan" }, { "importaddress", 3, "p2sh" }, { "importpubkey", 2, "rescan" }, { "importmulti", 0, "requests" }, { "importmulti", 1, "options" }, { "verifychain", 0, "checklevel" }, { "verifychain", 1, "nblocks" }, { "getblockstats", 0, "hash_or_height" }, { "getblockstats", 1, "stats" }, { "pruneblockchain", 0, "height" }, { "keypoolrefill", 0, "newsize" }, { "getrawmempool", 0, "verbose" }, { "estimatesmartfee", 0, "conf_target" }, { "estimaterawfee", 0, "conf_target" }, { "estimaterawfee", 1, "threshold" }, { "prioritisetransaction", 1, "dummy" }, { "prioritisetransaction", 2, "fee_delta" }, { "setban", 2, "bantime" }, { "setban", 3, "absolute" }, { "setnetworkactive", 0, "state" }, { "getmempoolancestors", 1, "verbose" }, { "getmempooldescendants", 1, "verbose" }, { "bumpfee", 1, "options" }, { "logging", 0, "include" }, { "logging", 1, "exclude" }, { "disconnectnode", 1, "nodeid" }, // Echo with conversion (For testing only) { "echojson", 0, "arg0" }, { "echojson", 1, "arg1" }, { "echojson", 2, "arg2" }, { "echojson", 3, "arg3" }, { "echojson", 4, "arg4" }, { "echojson", 5, "arg5" }, { "echojson", 6, "arg6" }, { "echojson", 7, "arg7" }, { "echojson", 8, "arg8" }, { "echojson", 9, "arg9" }, { "rescanblockchain", 0, "start_height"}, { "rescanblockchain", 1, "stop_height"}, { "createwallet", 1, "disable_private_keys"}, { "createwallet", 2, "blank"}, { "getnodeaddresses", 0, "count"}, { "stop", 0, "wait" }, { "getsuperblockbudget", 0, "index" }, { "spork", 1, "value" }, { "voteraw", 1, "tx_index" }, { "voteraw", 5, "time" }, { "syscoinmint", 2, "blocknumber" }, { "syscointxfund", 2, "output_index" }, { "assetallocationlock", 0, "asset_guid" }, { "assetallocationlock", 3, "output_index" }, { "assetallocationsend", 0, "asset_guid" }, { "assetallocationsendmany", 0, "asset_guid" }, { "assetallocationsendmany", 2, "inputs" }, { "assetallocationburn", 0, "asset_guid" }, { "assetallocationmint", 0, "asset_guid" }, { "assetallocationmint", 3, "blocknumber" }, { "assetallocationinfo", 0, "asset_guid" }, { "assetallocationbalance", 0, "asset_guid" }, { "assetallocationsenderstatus", 0, "asset_guid" }, { "listassetallocations", 0, "count" }, { "listassetallocations", 1, "from" }, { "listassetallocations", 2, "options" }, { "listassetallocationmempoolbalances", 0, "count" }, { "listassetallocationmempoolbalances", 1, "from" }, { "listassetallocationmempoolbalances", 2, "options" }, { "assetnew", 3, "precision" }, { "assetnew", 6, "update_flags" }, { "assetupdate", 0, "asset_guid" }, { "assetupdate", 4, "update_flags" }, { "assettransfer", 0, "asset_guid" }, { "assetsend", 0, "asset_guid" }, { "assetsendmany", 0, "asset_guid" }, { "assetsendmany", 1, "inputs" }, { "assetinfo", 0, "asset_guid" }, { "sentinelping", 0, "version" }, { "listassets", 0, "count" }, { "listassets", 1, "from" }, { "listassets", 2, "options" }, { "tpstestadd", 0, "starttime" }, { "tpstestadd", 1, "rawtxs" }, { "tpstestsetenabled", 0, "enabled" }, { "syscoinsetethstatus", 1, "highestBlock" }, { "syscoinsetethheaders", 0, "headers" }, { "listassetindex", 0, "page" }, { "listassetindex", 1, "options" }, }; // clang-format on class CRPCConvertTable { private: std::set<std::pair<std::string, int>> members; std::set<std::pair<std::string, std::string>> membersByName; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } bool convert(const std::string& method, const std::string& name) { return (membersByName.count(std::make_pair(method, name)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramName)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw std::runtime_error(std::string("Error parsing JSON:")+strVal); return jVal[0]; } UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VOBJ); for (const std::string &s: strParams) { size_t pos = s.find('='); if (pos == std::string::npos) { throw(std::runtime_error("No '=' in named argument '"+s+"', this needs to be present for every argument (even if it is empty)")); } std::string name = s.substr(0, pos); std::string value = s.substr(pos+1); if (!rpcCvtTable.convert(strMethod, name)) { // insert string value directly params.pushKV(name, value); } else { // parse string as JSON, insert bool/number/object/etc. value params.pushKV(name, ParseNonRFCJSONValue(value)); } } return params; } <commit_msg>all amounts should be converted<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/client.h> #include <rpc/protocol.h> #include <util/system.h> #include <set> #include <stdint.h> class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert std::string paramName; //!< parameter name }; // clang-format off /** * Specify a (method, idx, name) here if the argument is a non-string RPC * argument and needs to be converted from JSON. * * @note Parameter indexes start from 0. */ static const CRPCConvertParam vRPCConvertParams[] = { { "setmocktime", 0, "timestamp" }, { "generate", 0, "nblocks" }, { "generate", 1, "maxtries" }, { "generatetoaddress", 0, "nblocks" }, { "generatetoaddress", 2, "maxtries" }, { "getnetworkhashps", 0, "nblocks" }, { "getnetworkhashps", 1, "height" }, { "sendtoaddress", 1, "amount" }, { "sendtoaddress", 4, "subtractfeefromamount" }, { "sendtoaddress", 5 , "replaceable" }, { "sendtoaddress", 6 , "conf_target" }, { "settxfee", 0, "amount" }, { "sethdseed", 0, "newkeypool" }, { "getreceivedbyaddress", 1, "minconf" }, { "getreceivedbylabel", 1, "minconf" }, { "listreceivedbyaddress", 0, "minconf" }, { "listreceivedbyaddress", 1, "include_empty" }, { "listreceivedbyaddress", 2, "include_watchonly" }, { "listreceivedbylabel", 0, "minconf" }, { "listreceivedbylabel", 1, "include_empty" }, { "listreceivedbylabel", 2, "include_watchonly" }, { "getbalance", 1, "minconf" }, { "getbalance", 2, "include_watchonly" }, { "getblockhash", 0, "height" }, { "waitforblockheight", 0, "height" }, { "waitforblockheight", 1, "timeout" }, { "waitforblock", 1, "timeout" }, { "waitfornewblock", 0, "timeout" }, { "listtransactions", 1, "count" }, { "listtransactions", 2, "skip" }, { "listtransactions", 3, "include_watchonly" }, { "walletpassphrase", 1, "timeout" }, { "getblocktemplate", 0, "template_request" }, { "listsinceblock", 1, "target_confirmations" }, { "listsinceblock", 2, "include_watchonly" }, { "listsinceblock", 3, "include_removed" }, { "sendmany", 1, "amounts" }, { "sendmany", 2, "minconf" }, { "sendmany", 4, "subtractfeefrom" }, { "sendmany", 5 , "replaceable" }, { "sendmany", 6 , "conf_target" }, { "deriveaddresses", 1, "range" }, { "scantxoutset", 1, "scanobjects" }, { "addmultisigaddress", 0, "nrequired" }, { "addmultisigaddress", 1, "keys" }, { "createmultisig", 0, "nrequired" }, { "createmultisig", 1, "keys" }, { "listunspent", 0, "minconf" }, { "listunspent", 1, "maxconf" }, { "listunspent", 2, "addresses" }, { "listunspent", 3, "include_unsafe" }, { "listunspent", 4, "query_options" }, { "getblock", 1, "verbosity" }, { "getblock", 1, "verbose" }, { "getblockheader", 1, "verbose" }, { "getchaintxstats", 0, "nblocks" }, { "gettransaction", 1, "include_watchonly" }, { "getrawtransaction", 1, "verbose" }, { "createrawtransaction", 0, "inputs" }, { "createrawtransaction", 1, "outputs" }, { "createrawtransaction", 2, "locktime" }, { "createrawtransaction", 3, "replaceable" }, { "decoderawtransaction", 1, "iswitness" }, { "signrawtransactionwithkey", 1, "privkeys" }, { "signrawtransactionwithkey", 2, "prevtxs" }, { "signrawtransactionwithwallet", 1, "prevtxs" }, { "sendrawtransaction", 1, "allowhighfees" }, { "sendrawtransaction", 1, "maxfeerate" }, { "testmempoolaccept", 0, "rawtxs" }, { "testmempoolaccept", 1, "allowhighfees" }, { "testmempoolaccept", 1, "maxfeerate" }, { "combinerawtransaction", 0, "txs" }, { "fundrawtransaction", 1, "options" }, { "fundrawtransaction", 2, "iswitness" }, { "walletcreatefundedpsbt", 0, "inputs" }, { "walletcreatefundedpsbt", 1, "outputs" }, { "walletcreatefundedpsbt", 2, "locktime" }, { "walletcreatefundedpsbt", 3, "options" }, { "walletcreatefundedpsbt", 4, "bip32derivs" }, { "walletprocesspsbt", 1, "sign" }, { "walletprocesspsbt", 3, "bip32derivs" }, { "createpsbt", 0, "inputs" }, { "createpsbt", 1, "outputs" }, { "createpsbt", 2, "locktime" }, { "createpsbt", 3, "replaceable" }, { "combinepsbt", 0, "txs"}, { "joinpsbts", 0, "txs"}, { "finalizepsbt", 1, "extract"}, { "converttopsbt", 1, "permitsigdata"}, { "converttopsbt", 2, "iswitness"}, { "gettxout", 1, "n" }, { "gettxout", 2, "include_mempool" }, { "gettxoutproof", 0, "txids" }, { "lockunspent", 0, "unlock" }, { "lockunspent", 1, "transactions" }, { "importprivkey", 2, "rescan" }, { "importaddress", 2, "rescan" }, { "importaddress", 3, "p2sh" }, { "importpubkey", 2, "rescan" }, { "importmulti", 0, "requests" }, { "importmulti", 1, "options" }, { "verifychain", 0, "checklevel" }, { "verifychain", 1, "nblocks" }, { "getblockstats", 0, "hash_or_height" }, { "getblockstats", 1, "stats" }, { "pruneblockchain", 0, "height" }, { "keypoolrefill", 0, "newsize" }, { "getrawmempool", 0, "verbose" }, { "estimatesmartfee", 0, "conf_target" }, { "estimaterawfee", 0, "conf_target" }, { "estimaterawfee", 1, "threshold" }, { "prioritisetransaction", 1, "dummy" }, { "prioritisetransaction", 2, "fee_delta" }, { "setban", 2, "bantime" }, { "setban", 3, "absolute" }, { "setnetworkactive", 0, "state" }, { "getmempoolancestors", 1, "verbose" }, { "getmempooldescendants", 1, "verbose" }, { "bumpfee", 1, "options" }, { "logging", 0, "include" }, { "logging", 1, "exclude" }, { "disconnectnode", 1, "nodeid" }, // Echo with conversion (For testing only) { "echojson", 0, "arg0" }, { "echojson", 1, "arg1" }, { "echojson", 2, "arg2" }, { "echojson", 3, "arg3" }, { "echojson", 4, "arg4" }, { "echojson", 5, "arg5" }, { "echojson", 6, "arg6" }, { "echojson", 7, "arg7" }, { "echojson", 8, "arg8" }, { "echojson", 9, "arg9" }, { "rescanblockchain", 0, "start_height"}, { "rescanblockchain", 1, "stop_height"}, { "createwallet", 1, "disable_private_keys"}, { "createwallet", 2, "blank"}, { "getnodeaddresses", 0, "count"}, { "stop", 0, "wait" }, { "getsuperblockbudget", 0, "index" }, { "spork", 1, "value" }, { "voteraw", 1, "tx_index" }, { "voteraw", 5, "time" }, { "syscoinmint", 1, "amount" }, { "syscoinmint", 2, "blocknumber" }, { "syscointxfund", 2, "output_index" }, { "assetallocationlock", 0, "asset_guid" }, { "assetallocationlock", 3, "output_index" }, { "assetallocationsend", 0, "asset_guid" }, { "assetallocationsend", 3, "amount" }, { "assetallocationsendmany", 0, "asset_guid" }, { "assetallocationsendmany", 2, "inputs" }, { "assetallocationburn", 0, "asset_guid" }, { "assetallocationburn", 2, "amount" }, { "assetallocationmint", 0, "asset_guid" }, { "assetallocationmint", 2, "amount" }, { "assetallocationmint", 3, "blocknumber" }, { "assetallocationinfo", 0, "asset_guid" }, { "assetallocationbalance", 0, "asset_guid" }, { "assetallocationsenderstatus", 0, "asset_guid" }, { "listassetallocations", 0, "count" }, { "listassetallocations", 1, "from" }, { "listassetallocations", 2, "options" }, { "listassetallocationmempoolbalances", 0, "count" }, { "listassetallocationmempoolbalances", 1, "from" }, { "listassetallocationmempoolbalances", 2, "options" }, { "assetnew", 3, "precision" }, { "assetnew", 6, "update_flags" }, { "assetupdate", 0, "asset_guid" }, { "assetupdate", 3, "supply" }, { "assetupdate", 4, "update_flags" }, { "assettransfer", 0, "asset_guid" }, { "assetsend", 0, "asset_guid" }, { "assetsend", 2, "amount" }, { "assetsendmany", 0, "asset_guid" }, { "assetsendmany", 1, "inputs" }, { "assetinfo", 0, "asset_guid" }, { "sentinelping", 0, "version" }, { "listassets", 0, "count" }, { "listassets", 1, "from" }, { "listassets", 2, "options" }, { "tpstestadd", 0, "starttime" }, { "tpstestadd", 1, "rawtxs" }, { "tpstestsetenabled", 0, "enabled" }, { "syscoinsetethstatus", 1, "highestBlock" }, { "syscoinsetethheaders", 0, "headers" }, { "listassetindex", 0, "page" }, { "listassetindex", 1, "options" }, }; // clang-format on class CRPCConvertTable { private: std::set<std::pair<std::string, int>> members; std::set<std::pair<std::string, std::string>> membersByName; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } bool convert(const std::string& method, const std::string& name) { return (membersByName.count(std::make_pair(method, name)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramName)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw std::runtime_error(std::string("Error parsing JSON:")+strVal); return jVal[0]; } UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VOBJ); for (const std::string &s: strParams) { size_t pos = s.find('='); if (pos == std::string::npos) { throw(std::runtime_error("No '=' in named argument '"+s+"', this needs to be present for every argument (even if it is empty)")); } std::string name = s.substr(0, pos); std::string value = s.substr(pos+1); if (!rpcCvtTable.convert(strMethod, name)) { // insert string value directly params.pushKV(name, value); } else { // parse string as JSON, insert bool/number/object/etc. value params.pushKV(name, ParseNonRFCJSONValue(value)); } } return params; } <|endoftext|>
<commit_before>/** @file A brief file description @section license License 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 "P_EventSystem.h" /* MAGIC_EDITING_TAG */ #include <sched.h> #if TS_USE_HWLOC #include <alloca.h> #include <hwloc.h> #endif #include "ts/ink_defs.h" EventType EventProcessor::spawn_event_threads(int n_threads, const char *et_name, size_t stacksize) { char thr_name[MAX_THREAD_NAME_LENGTH]; EventType new_thread_group_id; int i; ink_release_assert(n_threads > 0); ink_release_assert((n_ethreads + n_threads) <= MAX_EVENT_THREADS); ink_release_assert(n_thread_groups < MAX_EVENT_TYPES); new_thread_group_id = (EventType)n_thread_groups; for (i = 0; i < n_threads; i++) { EThread *t = new EThread(REGULAR, n_ethreads + i); all_ethreads[n_ethreads + i] = t; eventthread[new_thread_group_id][i] = t; t->set_event_type(new_thread_group_id); } n_threads_for_type[new_thread_group_id] = n_threads; for (i = 0; i < n_threads; i++) { snprintf(thr_name, MAX_THREAD_NAME_LENGTH, "[%s %d]", et_name, i); eventthread[new_thread_group_id][i]->start(thr_name, stacksize); } n_thread_groups++; n_ethreads += n_threads; Debug("iocore_thread", "Created thread group '%s' id %d with %d threads", et_name, new_thread_group_id, n_threads); return new_thread_group_id; } class EventProcessor eventProcessor; int EventProcessor::start(int n_event_threads, size_t stacksize) { char thr_name[MAX_THREAD_NAME_LENGTH]; int i; // do some sanity checking. static int started = 0; ink_release_assert(!started); ink_release_assert(n_event_threads > 0 && n_event_threads <= MAX_EVENT_THREADS); started = 1; n_ethreads = n_event_threads; n_thread_groups = 1; int first_thread = 1; for (i = 0; i < n_event_threads; i++) { EThread *t = new EThread(REGULAR, i); if (first_thread && !i) { ink_thread_setspecific(Thread::thread_data_key, t); global_mutex = t->mutex; t->cur_time = ink_get_based_hrtime_internal(); } all_ethreads[i] = t; eventthread[ET_CALL][i] = t; t->set_event_type((EventType)ET_CALL); } n_threads_for_type[ET_CALL] = n_event_threads; #if TS_USE_HWLOC int affinity = 1; REC_ReadConfigInteger(affinity, "proxy.config.exec_thread.affinity"); hwloc_obj_t obj; hwloc_obj_type_t obj_type; int obj_count = 0; char *obj_name; switch (affinity) { case 4: // assign threads to logical processing units // Older versions of libhwloc (eg. Ubuntu 10.04) don't have HWLOC_OBJ_PU. #if HAVE_HWLOC_OBJ_PU obj_type = HWLOC_OBJ_PU; obj_name = (char *)"Logical Processor"; break; #endif case 3: // assign threads to real cores obj_type = HWLOC_OBJ_CORE; obj_name = (char *)"Core"; break; case 1: // assign threads to NUMA nodes (often 1:1 with sockets) obj_type = HWLOC_OBJ_NODE; obj_name = (char *)"NUMA Node"; if (hwloc_get_nbobjs_by_type(ink_get_topology(), obj_type) > 0) { break; } case 2: // assign threads to sockets obj_type = HWLOC_OBJ_SOCKET; obj_name = (char *)"Socket"; break; default: // assign threads to the machine as a whole (a level below SYSTEM) obj_type = HWLOC_OBJ_MACHINE; obj_name = (char *)"Machine"; } obj_count = hwloc_get_nbobjs_by_type(ink_get_topology(), obj_type); Debug("iocore_thread", "Affinity: %d %ss: %d PU: %d", affinity, obj_name, obj_count, ink_number_of_processors()); #endif for (i = first_thread; i < n_ethreads; i++) { snprintf(thr_name, MAX_THREAD_NAME_LENGTH, "[ET_NET %d]", i); ink_thread tid = all_ethreads[i]->start(thr_name, stacksize); (void)tid; #if TS_USE_HWLOC if (obj_count > 0) { obj = hwloc_get_obj_by_type(ink_get_topology(), obj_type, i % obj_count); #if HWLOC_API_VERSION >= 0x00010100 int cpu_mask_len = hwloc_bitmap_snprintf(NULL, 0, obj->cpuset) + 1; char *cpu_mask = (char *)alloca(cpu_mask_len); hwloc_bitmap_snprintf(cpu_mask, cpu_mask_len, obj->cpuset); Debug("iocore_thread", "EThread: %d %s: %d CPU Mask: %s\n", i, obj_name, obj->logical_index, cpu_mask); #else Debug("iocore_thread", "EThread: %d %s: %d\n", i, obj_name, obj->logical_index); #endif // HWLOC_API_VERSION hwloc_set_thread_cpubind(ink_get_topology(), tid, obj->cpuset, HWLOC_CPUBIND_STRICT); } else { Warning("hwloc returned an unexpected value -- CPU affinity disabled"); } #endif // TS_USE_HWLOC } Debug("iocore_thread", "Created event thread group id %d with %d threads", ET_CALL, n_event_threads); return 0; } void EventProcessor::shutdown() { } Event * EventProcessor::spawn_thread(Continuation *cont, const char *thr_name, size_t stacksize) { ink_release_assert(n_dthreads < MAX_EVENT_THREADS); Event *e = eventAllocator.alloc(); e->init(cont, 0, 0); all_dthreads[n_dthreads] = new EThread(DEDICATED, e); e->ethread = all_dthreads[n_dthreads]; e->mutex = e->continuation->mutex = all_dthreads[n_dthreads]->mutex; n_dthreads++; e->ethread->start(thr_name, stacksize); return e; } <commit_msg>TS-3989: Set affinity for ET_NET 0<commit_after>/** @file A brief file description @section license License 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 "P_EventSystem.h" /* MAGIC_EDITING_TAG */ #include <sched.h> #if TS_USE_HWLOC #include <alloca.h> #include <hwloc.h> #endif #include "ts/ink_defs.h" EventType EventProcessor::spawn_event_threads(int n_threads, const char *et_name, size_t stacksize) { char thr_name[MAX_THREAD_NAME_LENGTH]; EventType new_thread_group_id; int i; ink_release_assert(n_threads > 0); ink_release_assert((n_ethreads + n_threads) <= MAX_EVENT_THREADS); ink_release_assert(n_thread_groups < MAX_EVENT_TYPES); new_thread_group_id = (EventType)n_thread_groups; for (i = 0; i < n_threads; i++) { EThread *t = new EThread(REGULAR, n_ethreads + i); all_ethreads[n_ethreads + i] = t; eventthread[new_thread_group_id][i] = t; t->set_event_type(new_thread_group_id); } n_threads_for_type[new_thread_group_id] = n_threads; for (i = 0; i < n_threads; i++) { snprintf(thr_name, MAX_THREAD_NAME_LENGTH, "[%s %d]", et_name, i); eventthread[new_thread_group_id][i]->start(thr_name, stacksize); } n_thread_groups++; n_ethreads += n_threads; Debug("iocore_thread", "Created thread group '%s' id %d with %d threads", et_name, new_thread_group_id, n_threads); return new_thread_group_id; } class EventProcessor eventProcessor; int EventProcessor::start(int n_event_threads, size_t stacksize) { char thr_name[MAX_THREAD_NAME_LENGTH]; int i; // do some sanity checking. static int started = 0; ink_release_assert(!started); ink_release_assert(n_event_threads > 0 && n_event_threads <= MAX_EVENT_THREADS); started = 1; n_ethreads = n_event_threads; n_thread_groups = 1; for (i = 0; i < n_event_threads; i++) { EThread *t = new EThread(REGULAR, i); if (i == 0) { ink_thread_setspecific(Thread::thread_data_key, t); global_mutex = t->mutex; t->cur_time = ink_get_based_hrtime_internal(); } all_ethreads[i] = t; eventthread[ET_CALL][i] = t; t->set_event_type((EventType)ET_CALL); } n_threads_for_type[ET_CALL] = n_event_threads; #if TS_USE_HWLOC int affinity = 1; REC_ReadConfigInteger(affinity, "proxy.config.exec_thread.affinity"); hwloc_obj_t obj; hwloc_obj_type_t obj_type; int obj_count = 0; char *obj_name; switch (affinity) { case 4: // assign threads to logical processing units // Older versions of libhwloc (eg. Ubuntu 10.04) don't have HWLOC_OBJ_PU. #if HAVE_HWLOC_OBJ_PU obj_type = HWLOC_OBJ_PU; obj_name = (char *)"Logical Processor"; break; #endif case 3: // assign threads to real cores obj_type = HWLOC_OBJ_CORE; obj_name = (char *)"Core"; break; case 1: // assign threads to NUMA nodes (often 1:1 with sockets) obj_type = HWLOC_OBJ_NODE; obj_name = (char *)"NUMA Node"; if (hwloc_get_nbobjs_by_type(ink_get_topology(), obj_type) > 0) { break; } case 2: // assign threads to sockets obj_type = HWLOC_OBJ_SOCKET; obj_name = (char *)"Socket"; break; default: // assign threads to the machine as a whole (a level below SYSTEM) obj_type = HWLOC_OBJ_MACHINE; obj_name = (char *)"Machine"; } obj_count = hwloc_get_nbobjs_by_type(ink_get_topology(), obj_type); Debug("iocore_thread", "Affinity: %d %ss: %d PU: %d", affinity, obj_name, obj_count, ink_number_of_processors()); #endif for (i = 0; i < n_ethreads; i++) { ink_thread tid; if (i > 0) { snprintf(thr_name, MAX_THREAD_NAME_LENGTH, "[ET_NET %d]", i); tid = all_ethreads[i]->start(thr_name, stacksize); } else { tid = ink_thread_self(); } #if TS_USE_HWLOC if (obj_count > 0) { obj = hwloc_get_obj_by_type(ink_get_topology(), obj_type, i % obj_count); #if HWLOC_API_VERSION >= 0x00010100 int cpu_mask_len = hwloc_bitmap_snprintf(NULL, 0, obj->cpuset) + 1; char *cpu_mask = (char *)alloca(cpu_mask_len); hwloc_bitmap_snprintf(cpu_mask, cpu_mask_len, obj->cpuset); Debug("iocore_thread", "EThread: %d %s: %d CPU Mask: %s\n", i, obj_name, obj->logical_index, cpu_mask); #else Debug("iocore_thread", "EThread: %d %s: %d\n", i, obj_name, obj->logical_index); #endif // HWLOC_API_VERSION hwloc_set_thread_cpubind(ink_get_topology(), tid, obj->cpuset, HWLOC_CPUBIND_STRICT); } else { Warning("hwloc returned an unexpected value -- CPU affinity disabled"); } #else (void)tid; #endif // TS_USE_HWLOC } Debug("iocore_thread", "Created event thread group id %d with %d threads", ET_CALL, n_event_threads); return 0; } void EventProcessor::shutdown() { } Event * EventProcessor::spawn_thread(Continuation *cont, const char *thr_name, size_t stacksize) { ink_release_assert(n_dthreads < MAX_EVENT_THREADS); Event *e = eventAllocator.alloc(); e->init(cont, 0, 0); all_dthreads[n_dthreads] = new EThread(DEDICATED, e); e->ethread = all_dthreads[n_dthreads]; e->mutex = e->continuation->mutex = all_dthreads[n_dthreads]->mutex; n_dthreads++; e->ethread->start(thr_name, stacksize); return e; } <|endoftext|>
<commit_before>#include "entity_groups.h" #include "core/blob.h" #include "core/string.h" #include "universe/universe.h" namespace Lumix { EntityGroups::EntityGroups(IAllocator& allocator) : m_groups(allocator) , m_group_names(allocator) , m_allocator(allocator) , m_universe(nullptr) { m_groups.emplace(allocator); auto& name = m_group_names.emplace(); copyString(name.name, "default"); } int EntityGroups::getGroup(const char* name) const { for(int i = 0, c = m_group_names.size(); i < c; ++i) { if(compareString(m_group_names[i].name, name) == 0) return i; } return -1; } void EntityGroups::allEntitiesToDefault() { ASSERT(m_groups.size() == 1); ASSERT(m_groups[0].empty()); ASSERT(m_universe); for (int i = 0, c = m_universe->getEntityCount(); i < c; ++i) { Entity entity = m_universe->getEntityFromDenseIdx(i); m_groups[0].push(entity); } } void EntityGroups::deleteGroup(int idx) { if (m_groups.size() == 1) return; int default_idx = idx == 0 ? 1 : 0; for (auto e : m_groups[idx]) { m_groups[default_idx].push(e); } m_groups.eraseFast(idx); m_group_names.eraseFast(idx); } void EntityGroups::createGroup(const char* name) { if (name[0] == 0) return; for (auto& i : m_group_names) { if (compareString(i.name, name) == 0) return; } m_groups.emplace(m_allocator); auto& group_name = m_group_names.emplace(); copyString(group_name.name, name); } void EntityGroups::setUniverse(Universe* universe) { if (m_universe) { m_universe->entityCreated().unbind<EntityGroups, &EntityGroups::onEntityCreated>(this); m_universe->entityDestroyed().unbind<EntityGroups, &EntityGroups::onEntityDestroyed>(this); } m_universe = universe; m_group_names.clear(); m_groups.clear(); m_groups.emplace(m_allocator); auto& name = m_group_names.emplace(); copyString(name.name, "default"); if (m_universe) { m_universe->entityCreated().bind<EntityGroups, &EntityGroups::onEntityCreated>(this); m_universe->entityDestroyed().bind<EntityGroups, &EntityGroups::onEntityDestroyed>(this); } } int EntityGroups::getGroupEntitiesCount(int idx) const { return m_groups[idx].size(); } void EntityGroups::onEntityCreated(Entity entity) { m_groups[0].push(entity); } void EntityGroups::onEntityDestroyed(Entity entity) { removeFromGroup(entity); } void EntityGroups::setGroup(Entity entity, int group) { removeFromGroup(entity); m_groups[group].push(entity); } void EntityGroups::removeFromGroup(Entity entity) { for (auto& g : m_groups) { for (int i = 0, c = g.size(); i < c; ++i) { if (g[i] == entity) { g.eraseFast(i); return; } } } } void EntityGroups::serialize(OutputBlob& blob) { ASSERT(sizeof(m_group_names[0]) == 20); blob.write(m_group_names.size()); blob.write(&m_group_names[0], m_group_names.size() * sizeof(m_group_names[0])); for(auto& i : m_groups) { blob.write(i.size()); blob.write(&i[0], i.size() * sizeof(i[0])); } } void EntityGroups::deserialize(InputBlob& blob) { int count; blob.read(count); m_group_names.resize(count); blob.read(&m_group_names[0], count * sizeof(m_group_names[0])); m_groups.clear(); for(int i = 0; i < count; ++i) { int group_size; auto& group = m_groups.emplace(m_allocator); blob.read(group_size); group.resize(group_size); blob.read(&group[0], group_size * sizeof(group[0])); } } const Entity* EntityGroups::getGroupEntities(int idx) const { return &m_groups[idx][0]; } int EntityGroups::getGroupCount() const { return m_groups.size(); } const char* EntityGroups::getGroupName(int idx) const { return m_group_names[idx].name; } void EntityGroups::setGroupName(int idx, const char* name) { copyString(m_group_names[idx].name, name); } } // namespace Lumix <commit_msg>fixed crash when saving/loading empty entity group<commit_after>#include "entity_groups.h" #include "core/blob.h" #include "core/string.h" #include "universe/universe.h" namespace Lumix { EntityGroups::EntityGroups(IAllocator& allocator) : m_groups(allocator) , m_group_names(allocator) , m_allocator(allocator) , m_universe(nullptr) { m_groups.emplace(allocator); auto& name = m_group_names.emplace(); copyString(name.name, "default"); } int EntityGroups::getGroup(const char* name) const { for(int i = 0, c = m_group_names.size(); i < c; ++i) { if(compareString(m_group_names[i].name, name) == 0) return i; } return -1; } void EntityGroups::allEntitiesToDefault() { ASSERT(m_groups.size() == 1); ASSERT(m_groups[0].empty()); ASSERT(m_universe); for (int i = 0, c = m_universe->getEntityCount(); i < c; ++i) { Entity entity = m_universe->getEntityFromDenseIdx(i); m_groups[0].push(entity); } } void EntityGroups::deleteGroup(int idx) { if (m_groups.size() == 1) return; int default_idx = idx == 0 ? 1 : 0; for (auto e : m_groups[idx]) { m_groups[default_idx].push(e); } m_groups.eraseFast(idx); m_group_names.eraseFast(idx); } void EntityGroups::createGroup(const char* name) { if (name[0] == 0) return; for (auto& i : m_group_names) { if (compareString(i.name, name) == 0) return; } m_groups.emplace(m_allocator); auto& group_name = m_group_names.emplace(); copyString(group_name.name, name); } void EntityGroups::setUniverse(Universe* universe) { if (m_universe) { m_universe->entityCreated().unbind<EntityGroups, &EntityGroups::onEntityCreated>(this); m_universe->entityDestroyed().unbind<EntityGroups, &EntityGroups::onEntityDestroyed>(this); } m_universe = universe; m_group_names.clear(); m_groups.clear(); m_groups.emplace(m_allocator); auto& name = m_group_names.emplace(); copyString(name.name, "default"); if (m_universe) { m_universe->entityCreated().bind<EntityGroups, &EntityGroups::onEntityCreated>(this); m_universe->entityDestroyed().bind<EntityGroups, &EntityGroups::onEntityDestroyed>(this); } } int EntityGroups::getGroupEntitiesCount(int idx) const { return m_groups[idx].size(); } void EntityGroups::onEntityCreated(Entity entity) { m_groups[0].push(entity); } void EntityGroups::onEntityDestroyed(Entity entity) { removeFromGroup(entity); } void EntityGroups::setGroup(Entity entity, int group) { removeFromGroup(entity); m_groups[group].push(entity); } void EntityGroups::removeFromGroup(Entity entity) { for (auto& g : m_groups) { for (int i = 0, c = g.size(); i < c; ++i) { if (g[i] == entity) { g.eraseFast(i); return; } } } } void EntityGroups::serialize(OutputBlob& blob) { ASSERT(sizeof(m_group_names[0]) == 20); blob.write(m_group_names.size()); blob.write(&m_group_names[0], m_group_names.size() * sizeof(m_group_names[0])); for(auto& i : m_groups) { blob.write(i.size()); if(!i.empty()) blob.write(&i[0], i.size() * sizeof(i[0])); } } void EntityGroups::deserialize(InputBlob& blob) { int count; blob.read(count); m_group_names.resize(count); blob.read(&m_group_names[0], count * sizeof(m_group_names[0])); m_groups.clear(); for(int i = 0; i < count; ++i) { int group_size; auto& group = m_groups.emplace(m_allocator); blob.read(group_size); group.resize(group_size); if(group_size > 0) blob.read(&group[0], group_size * sizeof(group[0])); } } const Entity* EntityGroups::getGroupEntities(int idx) const { return &m_groups[idx][0]; } int EntityGroups::getGroupCount() const { return m_groups.size(); } const char* EntityGroups::getGroupName(int idx) const { return m_group_names[idx].name; } void EntityGroups::setGroupName(int idx, const char* name) { copyString(m_group_names[idx].name, name); } } // namespace Lumix <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include <fstream> #include <signal.h> #include <cstdlib> #include <getopt.h> #include <string> #include "util/stackinfo.h" #include "util/debug.h" #include "util/interrupt.h" #include "util/script_state.h" #include "util/thread.h" #include "util/thread_script_state.h" #include "util/lean_path.h" #include "kernel/environment.h" #include "kernel/kernel_exception.h" #include "kernel/formatter.h" #include "library/standard_kernel.h" #include "library/module.h" #include "library/io_state_stream.h" #include "library/definition_cache.h" #include "library/declaration_index.h" #include "library/print.h" #include "library/error_handling/error_handling.h" #include "frontends/lean/parser.h" #include "frontends/lean/pp.h" #include "frontends/lean/server.h" #include "frontends/lean/dependencies.h" #include "frontends/lua/register_modules.h" #include "version.h" #include "githash.h" // NOLINT using lean::script_state; using lean::unreachable_reached; using lean::environment; using lean::io_state; using lean::io_state_stream; using lean::regular; using lean::mk_environment; using lean::set_environment; using lean::set_io_state; using lean::definition_cache; using lean::pos_info; using lean::pos_info_provider; using lean::optional; using lean::expr; using lean::declaration_index; enum class input_kind { Unspecified, Lean, Lua }; static void on_ctrl_c(int ) { lean::request_interrupt(); } static void display_header(std::ostream & out) { out << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ", commit " << std::string(g_githash).substr(0, 12) << ")\n"; } static void display_help(std::ostream & out) { display_header(out); std::cout << "Input format:\n"; std::cout << " --lean use parser for Lean default input format for files,\n"; std::cout << " with unknown extension (default)\n"; std::cout << " --lua use Lua parser for files with unknown extension\n"; std::cout << "Miscellaneous:\n"; std::cout << " --help -h display this message\n"; std::cout << " --version -v display version number\n"; std::cout << " --githash display the git commit hash number used to build this binary\n"; std::cout << " --path display the path used for finding Lean libraries and extensions\n"; std::cout << " --output=file -o save the final environment in binary format in the given file\n"; std::cout << " --luahook=num -k how often the Lua interpreter checks the interrupted flag,\n"; std::cout << " it is useful for interrupting non-terminating user scripts,\n"; std::cout << " 0 means 'do not check'.\n"; std::cout << " --trust=num -t trust level (default: 0) \n"; std::cout << " --quiet -q do not print verbose messages\n"; #if defined(LEAN_MULTI_THREAD) std::cout << " --server start Lean in 'server' mode\n"; std::cout << " --threads=num -j number of threads used to process lean files\n"; #endif std::cout << " --deps just print dependencies of a Lean input\n"; std::cout << " --flycheck print structured error message for flycheck\n"; std::cout << " --cache=file -c load/save cached definitions from/to the given file\n"; std::cout << " --index=file -i store index for declared symbols in the given file\n"; #if defined(LEAN_USE_BOOST) std::cout << " --tstack=num -s thread stack size in Kb\n"; #endif } static char const * get_file_extension(char const * fname) { if (fname == 0) return 0; char const * last_dot = 0; while (true) { char const * tmp = strchr(fname, '.'); if (tmp == 0) { return last_dot; } last_dot = tmp + 1; fname = last_dot; } } static struct option g_long_options[] = { {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {"lean", no_argument, 0, 'l'}, {"lua", no_argument, 0, 'u'}, {"path", no_argument, 0, 'p'}, {"luahook", required_argument, 0, 'k'}, {"githash", no_argument, 0, 'g'}, {"output", required_argument, 0, 'o'}, {"trust", required_argument, 0, 't'}, #if defined(LEAN_MULTI_THREAD) {"server", no_argument, 0, 'S'}, {"threads", required_argument, 0, 'j'}, #endif {"quiet", no_argument, 0, 'q'}, {"cache", required_argument, 0, 'c'}, {"deps", no_argument, 0, 'D'}, {"flycheck", no_argument, 0, 'F'}, {"index", no_argument, 0, 'i'}, #if defined(LEAN_USE_BOOST) {"tstack", required_argument, 0, 's'}, #endif {0, 0, 0, 0} }; #define BASIC_OPT_STR "FDqlupgvhk:012t:012o:c:i:" #if defined(LEAN_USE_BOOST) && defined(LEAN_MULTI_THREAD) static char const * g_opt_str = BASIC_OPT_STR "Sj:012s:012"; #elif !defined(LEAN_USE_BOOST) && defined(LEAN_MULTI_THREAD) static char const * g_opt_str = BASIC_OPT_STR "Sj:012"; #else static char const * g_opt_str = BASIC_OPT_STR; #endif class simple_pos_info_provider : public pos_info_provider { char const * m_fname; public: simple_pos_info_provider(char const * fname):m_fname(fname) {} virtual optional<pos_info> get_pos_info(expr const &) const { return optional<pos_info>(); } virtual char const * get_file_name() const { return m_fname; } virtual pos_info get_some_pos() const { return pos_info(-1, -1); } }; int main(int argc, char ** argv) { lean::save_stack_info(); lean::init_default_print_fn(); lean::register_modules(); bool export_objects = false; unsigned trust_lvl = 0; bool quiet = false; bool server = false; bool only_deps = false; bool flycheck = false; unsigned num_threads = 1; bool use_cache = false; bool gen_index = false; std::string output; std::string cache_name; std::string index_name; input_kind default_k = input_kind::Lean; // default while (true) { int c = getopt_long(argc, argv, g_opt_str, g_long_options, NULL); if (c == -1) break; // end of command line switch (c) { case 'j': num_threads = atoi(optarg); break; case 'S': server = true; break; case 'v': display_header(std::cout); return 0; case 'g': std::cout << g_githash << "\n"; return 0; case 'h': display_help(std::cout); return 0; case 'l': default_k = input_kind::Lean; break; case 'u': default_k = input_kind::Lua; break; case 'k': script_state::set_check_interrupt_freq(atoi(optarg)); break; case 'p': std::cout << lean::get_lean_path() << "\n"; return 0; case 's': lean::set_thread_stack_size(atoi(optarg)*1024); break; case 'o': output = optarg; export_objects = true; break; case 'c': cache_name = optarg; use_cache = true; break; case 'i': index_name = optarg; gen_index = true; case 't': trust_lvl = atoi(optarg); break; case 'q': quiet = true; break; case 'D': only_deps = true; break; case 'F': flycheck = true; break; default: std::cerr << "Unknown command line option\n"; display_help(std::cerr); return 1; } } #if !defined(LEAN_MULTI_THREAD) lean_assert(!server); lean_assert(num_threads == 1); #endif environment env = mk_environment(trust_lvl); io_state ios(lean::mk_pretty_formatter_factory()); if (quiet) ios.set_option("verbose", false); if (flycheck) ios.set_option("flycheck", true); script_state S = lean::get_thread_script_state(); set_environment set1(S, env); set_io_state set2(S, ios); definition_cache cache; definition_cache * cache_ptr = nullptr; if (use_cache) { cache_ptr = &cache; std::ifstream in(cache_name); if (!in.bad() && !in.fail()) cache.load(in); } declaration_index index; declaration_index * index_ptr = nullptr; if (gen_index) index_ptr = &index; try { bool ok = true; for (int i = optind; i < argc; i++) { try { char const * ext = get_file_extension(argv[i]); input_kind k = default_k; if (ext) { if (strcmp(ext, "lean") == 0) { k = input_kind::Lean; } else if (strcmp(ext, "lua") == 0) { k = input_kind::Lua; } } if (k == input_kind::Lean) { if (only_deps) { if (!display_deps(env, std::cout, std::cerr, argv[i])) ok = false; } else if (!parse_commands(env, ios, argv[i], false, num_threads, cache_ptr, index_ptr)) { ok = false; } } else if (k == input_kind::Lua) { lean::system_import(argv[i]); } else { lean_unreachable(); // LCOV_EXCL_LINE } } catch (lean::exception & ex) { simple_pos_info_provider pp(argv[i]); ok = false; lean::display_error(diagnostic(env, ios), &pp, ex); } } if (ok && server && default_k == input_kind::Lean) { signal(SIGINT, on_ctrl_c); lean::server Sv(env, ios, num_threads); if (!Sv(std::cin)) ok = false; } if (use_cache) { std::ofstream out(cache_name, std::ofstream::binary); cache.save(out); } if (gen_index) { std::shared_ptr<lean::file_output_channel> out(new lean::file_output_channel(index_name.c_str())); ios.set_regular_channel(out); index.save(regular(env, ios)); } if (export_objects && ok) { std::ofstream out(output, std::ofstream::binary); export_module(out, env); } return ok ? 0 : 1; } catch (lean::exception & ex) { lean::display_error(diagnostic(env, ios), nullptr, ex); } return 1; } <commit_msg>feat(shell): add -D command line option for setting configuration options, closes #130<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include <fstream> #include <signal.h> #include <cstdlib> #include <getopt.h> #include <string> #include "util/stackinfo.h" #include "util/debug.h" #include "util/sstream.h" #include "util/interrupt.h" #include "util/script_state.h" #include "util/thread.h" #include "util/thread_script_state.h" #include "util/lean_path.h" #include "util/sexpr/options.h" #include "util/sexpr/option_declarations.h" #include "kernel/environment.h" #include "kernel/kernel_exception.h" #include "kernel/formatter.h" #include "library/standard_kernel.h" #include "library/module.h" #include "library/io_state_stream.h" #include "library/definition_cache.h" #include "library/declaration_index.h" #include "library/print.h" #include "library/error_handling/error_handling.h" #include "frontends/lean/parser.h" #include "frontends/lean/pp.h" #include "frontends/lean/server.h" #include "frontends/lean/dependencies.h" #include "frontends/lua/register_modules.h" #include "version.h" #include "githash.h" // NOLINT using lean::script_state; using lean::unreachable_reached; using lean::environment; using lean::io_state; using lean::io_state_stream; using lean::regular; using lean::mk_environment; using lean::set_environment; using lean::set_io_state; using lean::definition_cache; using lean::pos_info; using lean::pos_info_provider; using lean::optional; using lean::expr; using lean::options; using lean::declaration_index; enum class input_kind { Unspecified, Lean, Lua }; static void on_ctrl_c(int ) { lean::request_interrupt(); } static void display_header(std::ostream & out) { out << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ", commit " << std::string(g_githash).substr(0, 12) << ")\n"; } static void display_help(std::ostream & out) { display_header(out); std::cout << "Input format:\n"; std::cout << " --lean use parser for Lean default input format for files,\n"; std::cout << " with unknown extension (default)\n"; std::cout << " --lua use Lua parser for files with unknown extension\n"; std::cout << "Miscellaneous:\n"; std::cout << " --help -h display this message\n"; std::cout << " --version -v display version number\n"; std::cout << " --githash display the git commit hash number used to build this binary\n"; std::cout << " --path display the path used for finding Lean libraries and extensions\n"; std::cout << " --output=file -o save the final environment in binary format in the given file\n"; std::cout << " --luahook=num -k how often the Lua interpreter checks the interrupted flag,\n"; std::cout << " it is useful for interrupting non-terminating user scripts,\n"; std::cout << " 0 means 'do not check'.\n"; std::cout << " --trust=num -t trust level (default: 0) \n"; std::cout << " --quiet -q do not print verbose messages\n"; #if defined(LEAN_MULTI_THREAD) std::cout << " --server start Lean in 'server' mode\n"; std::cout << " --threads=num -j number of threads used to process lean files\n"; #endif std::cout << " --deps just print dependencies of a Lean input\n"; std::cout << " --flycheck print structured error message for flycheck\n"; std::cout << " --cache=file -c load/save cached definitions from/to the given file\n"; std::cout << " --index=file -i store index for declared symbols in the given file\n"; #if defined(LEAN_USE_BOOST) std::cout << " --tstack=num -s thread stack size in Kb\n"; #endif std::cout << " -D name=value set a configuration option (see set_option command)\n"; } static char const * get_file_extension(char const * fname) { if (fname == 0) return 0; char const * last_dot = 0; while (true) { char const * tmp = strchr(fname, '.'); if (tmp == 0) { return last_dot; } last_dot = tmp + 1; fname = last_dot; } } static struct option g_long_options[] = { {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {"lean", no_argument, 0, 'l'}, {"lua", no_argument, 0, 'u'}, {"path", no_argument, 0, 'p'}, {"luahook", required_argument, 0, 'k'}, {"githash", no_argument, 0, 'g'}, {"output", required_argument, 0, 'o'}, {"trust", required_argument, 0, 't'}, #if defined(LEAN_MULTI_THREAD) {"server", no_argument, 0, 'S'}, {"threads", required_argument, 0, 'j'}, #endif {"quiet", no_argument, 0, 'q'}, {"cache", required_argument, 0, 'c'}, {"deps", no_argument, 0, 'd'}, {"flycheck", no_argument, 0, 'F'}, {"index", no_argument, 0, 'i'}, #if defined(LEAN_USE_BOOST) {"tstack", required_argument, 0, 's'}, #endif {0, 0, 0, 0} }; #define BASIC_OPT_STR "FdD:qlupgvhk:012t:012o:c:i:" #if defined(LEAN_USE_BOOST) && defined(LEAN_MULTI_THREAD) static char const * g_opt_str = BASIC_OPT_STR "Sj:012s:012"; #elif !defined(LEAN_USE_BOOST) && defined(LEAN_MULTI_THREAD) static char const * g_opt_str = BASIC_OPT_STR "Sj:012"; #else static char const * g_opt_str = BASIC_OPT_STR; #endif class simple_pos_info_provider : public pos_info_provider { char const * m_fname; public: simple_pos_info_provider(char const * fname):m_fname(fname) {} virtual optional<pos_info> get_pos_info(expr const &) const { return optional<pos_info>(); } virtual char const * get_file_name() const { return m_fname; } virtual pos_info get_some_pos() const { return pos_info(-1, -1); } }; options set_config_option(options const & opts, char const * in) { std::string in_str(in); auto pos = in_str.find('='); if (pos == std::string::npos) throw lean::exception("invalid -D parameter, argument must contain '='"); lean::name opt = lean::string_to_name(in_str.substr(0, pos)); std::string val = in_str.substr(pos+1); auto decls = lean::get_option_declarations(); auto it = decls.find(opt); if (it != decls.end()) { switch (it->second.kind()) { case lean::BoolOption: if (val == "true") return opts.update(opt, true); else if (val == "false") return opts.update(opt, false); else throw lean::exception(lean::sstream() << "invalid -D parameter, invalid configuration option '" << opt << "' value, it must be true/false"); case lean::IntOption: case lean::UnsignedOption: return opts.update(opt, atoi(val.c_str())); default: throw lean::exception(lean::sstream() << "invalid -D parameter, configuration option '" << opt << "' cannot be set in the command line, use set_option command"); } } else { throw lean::exception(lean::sstream() << "invalid -D parameter, unknown configuration option '" << opt << "'"); } } int main(int argc, char ** argv) { lean::save_stack_info(); lean::init_default_print_fn(); lean::register_modules(); bool export_objects = false; unsigned trust_lvl = 0; bool server = false; bool only_deps = false; unsigned num_threads = 1; bool use_cache = false; bool gen_index = false; options opts; std::string output; std::string cache_name; std::string index_name; input_kind default_k = input_kind::Lean; // default while (true) { int c = getopt_long(argc, argv, g_opt_str, g_long_options, NULL); if (c == -1) break; // end of command line switch (c) { case 'j': num_threads = atoi(optarg); break; case 'S': server = true; break; case 'v': display_header(std::cout); return 0; case 'g': std::cout << g_githash << "\n"; return 0; case 'h': display_help(std::cout); return 0; case 'l': default_k = input_kind::Lean; break; case 'u': default_k = input_kind::Lua; break; case 'k': script_state::set_check_interrupt_freq(atoi(optarg)); break; case 'p': std::cout << lean::get_lean_path() << "\n"; return 0; case 's': lean::set_thread_stack_size(atoi(optarg)*1024); break; case 'o': output = optarg; export_objects = true; break; case 'c': cache_name = optarg; use_cache = true; break; case 'i': index_name = optarg; gen_index = true; case 't': trust_lvl = atoi(optarg); break; case 'q': opts = opts.update("verbose", false); break; case 'd': only_deps = true; break; case 'D': try { opts = set_config_option(opts, optarg); } catch (lean::exception & ex) { std::cerr << ex.what() << std::endl; return 1; } break; case 'F': opts = opts.update("flycheck", true); break; default: std::cerr << "Unknown command line option\n"; display_help(std::cerr); return 1; } } #if !defined(LEAN_MULTI_THREAD) lean_assert(!server); lean_assert(num_threads == 1); #endif environment env = mk_environment(trust_lvl); io_state ios(opts, lean::mk_pretty_formatter_factory()); script_state S = lean::get_thread_script_state(); set_environment set1(S, env); set_io_state set2(S, ios); definition_cache cache; definition_cache * cache_ptr = nullptr; if (use_cache) { cache_ptr = &cache; std::ifstream in(cache_name); if (!in.bad() && !in.fail()) cache.load(in); } declaration_index index; declaration_index * index_ptr = nullptr; if (gen_index) index_ptr = &index; try { bool ok = true; for (int i = optind; i < argc; i++) { try { char const * ext = get_file_extension(argv[i]); input_kind k = default_k; if (ext) { if (strcmp(ext, "lean") == 0) { k = input_kind::Lean; } else if (strcmp(ext, "lua") == 0) { k = input_kind::Lua; } } if (k == input_kind::Lean) { if (only_deps) { if (!display_deps(env, std::cout, std::cerr, argv[i])) ok = false; } else if (!parse_commands(env, ios, argv[i], false, num_threads, cache_ptr, index_ptr)) { ok = false; } } else if (k == input_kind::Lua) { lean::system_import(argv[i]); } else { lean_unreachable(); // LCOV_EXCL_LINE } } catch (lean::exception & ex) { simple_pos_info_provider pp(argv[i]); ok = false; lean::display_error(diagnostic(env, ios), &pp, ex); } } if (ok && server && default_k == input_kind::Lean) { signal(SIGINT, on_ctrl_c); lean::server Sv(env, ios, num_threads); if (!Sv(std::cin)) ok = false; } if (use_cache) { std::ofstream out(cache_name, std::ofstream::binary); cache.save(out); } if (gen_index) { std::shared_ptr<lean::file_output_channel> out(new lean::file_output_channel(index_name.c_str())); ios.set_regular_channel(out); index.save(regular(env, ios)); } if (export_objects && ok) { std::ofstream out(output, std::ofstream::binary); export_module(out, env); } return ok ? 0 : 1; } catch (lean::exception & ex) { lean::display_error(diagnostic(env, ios), nullptr, ex); } return 1; } <|endoftext|>
<commit_before>#include <cthun-agent/configuration.hpp> #include <leatherman/file_util/file.hpp> #include "version-inl.hpp" #include <boost/filesystem/operations.hpp> namespace CthunAgent { namespace fs = boost::filesystem; namespace lth_file = leatherman::file_util; const std::string DEFAULT_MODULES_DIR { "/usr/share/cthun-agent/modules" }; // // Private // Configuration::Configuration() : initialized_ { false }, defaults_ {}, config_file_ { "" }, start_function_ {} { defineDefaultValues(); } void Configuration::defineDefaultValues() { HW::SetAppName("cthun-agent"); HW::SetHelpBanner("Usage: cthun-agent [options]"); HW::SetVersion(CTHUN_AGENT_VERSION); // start setting the config file path to known existent locations; // HW will overwrite it with the one parsed from CLI, if specified if (lth_file::file_readable(lth_file::tilde_expand("~/.cthun-agent"))) { config_file_ = lth_file::tilde_expand("~/.cthun-agent"); // TODO(ploubser): This will have to changed when the AIO agent is done } else if (lth_file::file_readable("/etc/puppetlabs/agent/cthun.cfg")) { config_file_ = "/etc/puppetlabs/agent/cthun.cfg"; } std::string modules_dir { "" }; if (fs::is_directory(DEFAULT_MODULES_DIR)) { modules_dir = DEFAULT_MODULES_DIR; } defaults_.insert(std::pair<std::string, Base_ptr>("server", Base_ptr( new Entry<std::string>("server", "s", "Cthun server URL", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("ca", Base_ptr( new Entry<std::string>("ca", "", "CA certificate", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("cert", Base_ptr( new Entry<std::string>("cert", "", "cthun-agent certificate", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("key", Base_ptr( new Entry<std::string>("key", "", "cthun-agent private key", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("logfile", Base_ptr( new Entry<std::string>("logfile", "", "Log file (defaults to console logging)", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("config-file", Base_ptr( new Entry<std::string>("config-file", "", "Specify a non default config file to use", Types::String, config_file_)))); defaults_.insert(std::pair<std::string, Base_ptr>("spool-dir", Base_ptr( new Entry<std::string>("spool-dir", "", "Specify directory to spool delayed results to", Types::String, DEFAULT_ACTION_RESULTS_DIR)))); defaults_.insert(std::pair<std::string, Base_ptr>("modules-dir", Base_ptr( new Entry<std::string>("modules-dir", "", "Specify directory containing external modules", Types::String, modules_dir)))); } void Configuration::setDefaultValues() { for (const auto& entry : defaults_) { std::string flag_names = entry.second->name; if (!entry.second->aliases.empty()) { flag_names += " " + entry.second->aliases; } switch (entry.second->type) { case Integer: { Entry<int>* entry_ptr = (Entry<int>*) entry.second.get(); HW::DefineGlobalFlag<int>(flag_names, entry_ptr->help, entry_ptr->value, [entry_ptr] (int v) { entry_ptr->configured = true; }); } break; case Bool: { Entry<bool>* entry_ptr = (Entry<bool>*) entry.second.get(); HW::DefineGlobalFlag<bool>(flag_names, entry_ptr->help, entry_ptr->value, [entry_ptr] (bool v) { entry_ptr->configured = true; }); } break; case Double: { Entry<double>* entry_ptr = (Entry<double>*) entry.second.get(); HW::DefineGlobalFlag<double>(flag_names, entry_ptr->help, entry_ptr->value, [entry_ptr] (double v) { entry_ptr->configured = true; }); } break; default: { Entry<std::string>* entry_ptr = (Entry<std::string>*) entry.second.get(); HW::DefineGlobalFlag<std::string>(flag_names, entry_ptr->help, entry_ptr->value, [entry_ptr] (std::string v) { entry_ptr->configured = true; }); } } } } void Configuration::parseConfigFile() { if (!lth_file::file_readable(config_file_)) { throw configuration_entry_error { config_file_ + " does not exist" }; } INIReader reader { config_file_ }; for (const auto& entry : defaults_) { // skip config entry if flag was set if (entry.second->configured) { continue; } switch (entry.second->type) { case Integer: { Entry<int>* entry_ptr = (Entry<int>*) entry.second.get(); HW::SetFlag<int>(entry_ptr->name, reader.GetInteger("", entry_ptr->name, entry_ptr->value)); } break; case Bool: { Entry<bool>* entry_ptr = (Entry<bool>*) entry.second.get(); HW::SetFlag<bool>(entry_ptr->name, reader.GetBoolean("", entry_ptr->name, entry_ptr->value)); } break; case Double: { Entry<double>* entry_ptr = (Entry<double>*) entry.second.get(); HW::SetFlag<double>(entry_ptr->name, reader.GetReal("", entry_ptr->name, entry_ptr->value)); } break; default: { Entry<std::string>* entry_ptr = (Entry<std::string>*) entry.second.get(); HW::SetFlag<std::string>(entry_ptr->name, reader.Get("", entry_ptr->name, entry_ptr->value)); } } } } // // Public interface // void Configuration::reset() { HW::Reset(); setDefaultValues(); initialized_ = false; } HW::ParseResult Configuration::initialize(int argc, char *argv[]) { setDefaultValues(); HW::DefineAction("start", 0, false, "Start the agent (Default)", "Start the agent", start_function_); // manipulate argc and v to make start the default action. // TODO(ploubser): Add ability to specify default action to HorseWhisperer int modified_argc = argc + 1; char* modified_argv[modified_argc]; char action[] = "start"; for (int i = 0; i < argc; i++) { modified_argv[i] = argv[i]; } modified_argv[modified_argc - 1] = action; auto parse_result = HW::Parse(modified_argc, modified_argv); if (parse_result == HW::ParseResult::ERROR || parse_result == HW::ParseResult::INVALID_FLAG) { throw cli_parse_error { "An error occurred while parsing cli options"}; } config_file_ = HW::GetFlag<std::string>("config-file"); if (!config_file_.empty()) { parseConfigFile(); } validateAndNormalizeConfiguration(); initialized_ = true; return parse_result; } void Configuration::setStartFunction(std::function<int(std::vector<std::string>)> start_function) { start_function_ = start_function; } void Configuration::validateAndNormalizeConfiguration() { // determine which of your values must be initalised if (HW::GetFlag<std::string>("server").empty()) { throw required_not_set_error { "server value must be defined" }; } else if (HW::GetFlag<std::string>("server").find("wss://") != 0) { throw configuration_entry_error { "server value must start with wss://" }; } if (HW::GetFlag<std::string>("ca").empty()) { throw required_not_set_error { "ca value must be defined" }; } else if (!lth_file::file_readable(HW::GetFlag<std::string>("ca"))) { throw configuration_entry_error { "ca file not found" }; } if (HW::GetFlag<std::string>("cert").empty()) { throw required_not_set_error { "cert value must be defined" }; } else if (!lth_file::file_readable(HW::GetFlag<std::string>("cert"))) { throw configuration_entry_error { "cert file not found" }; } if (HW::GetFlag<std::string>("key").empty()) { throw required_not_set_error { "key value must be defined" }; } else if (!lth_file::file_readable(HW::GetFlag<std::string>("key"))) { throw configuration_entry_error { "key file not found" }; } for (const auto& flag_name : std::vector<std::string> { "ca", "cert", "key" }) { const auto& path = HW::GetFlag<std::string>(flag_name); HW::SetFlag<std::string>(flag_name, lth_file::tilde_expand(path)); } if (HW::GetFlag<std::string>("spool-dir").empty()) { // Unexpected, since we have a default value for spool-dir throw required_not_set_error { "spool-dir must be defined" }; } else { // TODO(ale): ensure that spool_dir_ is a directory, once we // have leatherman::file_util std::string spool_dir = lth_file::tilde_expand(HW::GetFlag<std::string>("spool-dir")); if (spool_dir.back() != '/') { HW::SetFlag<std::string>("spool-dir", spool_dir + "/"); } } if (!HW::GetFlag<std::string>("logfile").empty()) { auto path = FileUtils::shellExpand(HW::GetFlag<std::string>("logfile")); HW::SetFlag<std::string>("logfile", path); } } } // namespace CthunAgent <commit_msg>(maint) Replace FileUtils::shellExpand with leatherman's shell_quote<commit_after>#include <cthun-agent/configuration.hpp> #include <leatherman/file_util/file.hpp> #include "version-inl.hpp" #include <boost/filesystem/operations.hpp> namespace CthunAgent { namespace fs = boost::filesystem; namespace lth_file = leatherman::file_util; const std::string DEFAULT_MODULES_DIR { "/usr/share/cthun-agent/modules" }; // // Private // Configuration::Configuration() : initialized_ { false }, defaults_ {}, config_file_ { "" }, start_function_ {} { defineDefaultValues(); } void Configuration::defineDefaultValues() { HW::SetAppName("cthun-agent"); HW::SetHelpBanner("Usage: cthun-agent [options]"); HW::SetVersion(CTHUN_AGENT_VERSION); // start setting the config file path to known existent locations; // HW will overwrite it with the one parsed from CLI, if specified if (lth_file::file_readable(lth_file::tilde_expand("~/.cthun-agent"))) { config_file_ = lth_file::tilde_expand("~/.cthun-agent"); // TODO(ploubser): This will have to changed when the AIO agent is done } else if (lth_file::file_readable("/etc/puppetlabs/agent/cthun.cfg")) { config_file_ = "/etc/puppetlabs/agent/cthun.cfg"; } std::string modules_dir { "" }; if (fs::is_directory(DEFAULT_MODULES_DIR)) { modules_dir = DEFAULT_MODULES_DIR; } defaults_.insert(std::pair<std::string, Base_ptr>("server", Base_ptr( new Entry<std::string>("server", "s", "Cthun server URL", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("ca", Base_ptr( new Entry<std::string>("ca", "", "CA certificate", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("cert", Base_ptr( new Entry<std::string>("cert", "", "cthun-agent certificate", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("key", Base_ptr( new Entry<std::string>("key", "", "cthun-agent private key", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("logfile", Base_ptr( new Entry<std::string>("logfile", "", "Log file (defaults to console logging)", Types::String, "")))); defaults_.insert(std::pair<std::string, Base_ptr>("config-file", Base_ptr( new Entry<std::string>("config-file", "", "Specify a non default config file to use", Types::String, config_file_)))); defaults_.insert(std::pair<std::string, Base_ptr>("spool-dir", Base_ptr( new Entry<std::string>("spool-dir", "", "Specify directory to spool delayed results to", Types::String, DEFAULT_ACTION_RESULTS_DIR)))); defaults_.insert(std::pair<std::string, Base_ptr>("modules-dir", Base_ptr( new Entry<std::string>("modules-dir", "", "Specify directory containing external modules", Types::String, modules_dir)))); } void Configuration::setDefaultValues() { for (const auto& entry : defaults_) { std::string flag_names = entry.second->name; if (!entry.second->aliases.empty()) { flag_names += " " + entry.second->aliases; } switch (entry.second->type) { case Integer: { Entry<int>* entry_ptr = (Entry<int>*) entry.second.get(); HW::DefineGlobalFlag<int>(flag_names, entry_ptr->help, entry_ptr->value, [entry_ptr] (int v) { entry_ptr->configured = true; }); } break; case Bool: { Entry<bool>* entry_ptr = (Entry<bool>*) entry.second.get(); HW::DefineGlobalFlag<bool>(flag_names, entry_ptr->help, entry_ptr->value, [entry_ptr] (bool v) { entry_ptr->configured = true; }); } break; case Double: { Entry<double>* entry_ptr = (Entry<double>*) entry.second.get(); HW::DefineGlobalFlag<double>(flag_names, entry_ptr->help, entry_ptr->value, [entry_ptr] (double v) { entry_ptr->configured = true; }); } break; default: { Entry<std::string>* entry_ptr = (Entry<std::string>*) entry.second.get(); HW::DefineGlobalFlag<std::string>(flag_names, entry_ptr->help, entry_ptr->value, [entry_ptr] (std::string v) { entry_ptr->configured = true; }); } } } } void Configuration::parseConfigFile() { if (!lth_file::file_readable(config_file_)) { throw configuration_entry_error { config_file_ + " does not exist" }; } INIReader reader { config_file_ }; for (const auto& entry : defaults_) { // skip config entry if flag was set if (entry.second->configured) { continue; } switch (entry.second->type) { case Integer: { Entry<int>* entry_ptr = (Entry<int>*) entry.second.get(); HW::SetFlag<int>(entry_ptr->name, reader.GetInteger("", entry_ptr->name, entry_ptr->value)); } break; case Bool: { Entry<bool>* entry_ptr = (Entry<bool>*) entry.second.get(); HW::SetFlag<bool>(entry_ptr->name, reader.GetBoolean("", entry_ptr->name, entry_ptr->value)); } break; case Double: { Entry<double>* entry_ptr = (Entry<double>*) entry.second.get(); HW::SetFlag<double>(entry_ptr->name, reader.GetReal("", entry_ptr->name, entry_ptr->value)); } break; default: { Entry<std::string>* entry_ptr = (Entry<std::string>*) entry.second.get(); HW::SetFlag<std::string>(entry_ptr->name, reader.Get("", entry_ptr->name, entry_ptr->value)); } } } } // // Public interface // void Configuration::reset() { HW::Reset(); setDefaultValues(); initialized_ = false; } HW::ParseResult Configuration::initialize(int argc, char *argv[]) { setDefaultValues(); HW::DefineAction("start", 0, false, "Start the agent (Default)", "Start the agent", start_function_); // manipulate argc and v to make start the default action. // TODO(ploubser): Add ability to specify default action to HorseWhisperer int modified_argc = argc + 1; char* modified_argv[modified_argc]; char action[] = "start"; for (int i = 0; i < argc; i++) { modified_argv[i] = argv[i]; } modified_argv[modified_argc - 1] = action; auto parse_result = HW::Parse(modified_argc, modified_argv); if (parse_result == HW::ParseResult::ERROR || parse_result == HW::ParseResult::INVALID_FLAG) { throw cli_parse_error { "An error occurred while parsing cli options"}; } config_file_ = HW::GetFlag<std::string>("config-file"); if (!config_file_.empty()) { parseConfigFile(); } validateAndNormalizeConfiguration(); initialized_ = true; return parse_result; } void Configuration::setStartFunction(std::function<int(std::vector<std::string>)> start_function) { start_function_ = start_function; } void Configuration::validateAndNormalizeConfiguration() { // determine which of your values must be initalised if (HW::GetFlag<std::string>("server").empty()) { throw required_not_set_error { "server value must be defined" }; } else if (HW::GetFlag<std::string>("server").find("wss://") != 0) { throw configuration_entry_error { "server value must start with wss://" }; } if (HW::GetFlag<std::string>("ca").empty()) { throw required_not_set_error { "ca value must be defined" }; } else if (!lth_file::file_readable(HW::GetFlag<std::string>("ca"))) { throw configuration_entry_error { "ca file not found" }; } if (HW::GetFlag<std::string>("cert").empty()) { throw required_not_set_error { "cert value must be defined" }; } else if (!lth_file::file_readable(HW::GetFlag<std::string>("cert"))) { throw configuration_entry_error { "cert file not found" }; } if (HW::GetFlag<std::string>("key").empty()) { throw required_not_set_error { "key value must be defined" }; } else if (!lth_file::file_readable(HW::GetFlag<std::string>("key"))) { throw configuration_entry_error { "key file not found" }; } for (const auto& flag_name : std::vector<std::string> { "ca", "cert", "key" }) { const auto& path = HW::GetFlag<std::string>(flag_name); HW::SetFlag<std::string>(flag_name, lth_file::tilde_expand(path)); } if (HW::GetFlag<std::string>("spool-dir").empty()) { // Unexpected, since we have a default value for spool-dir throw required_not_set_error { "spool-dir must be defined" }; } else { // TODO(ale): ensure that spool_dir_ is a directory, once we // have leatherman::file_util std::string spool_dir = lth_file::tilde_expand(HW::GetFlag<std::string>("spool-dir")); if (spool_dir.back() != '/') { HW::SetFlag<std::string>("spool-dir", spool_dir + "/"); } } if (!HW::GetFlag<std::string>("logfile").empty()) { auto path = lth_file::shell_quote(HW::GetFlag<std::string>("logfile")); HW::SetFlag<std::string>("logfile", path); } } } // namespace CthunAgent <|endoftext|>
<commit_before><commit_msg>bug: remove possible race condition crash; nullptr access<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2011, Nathan Rajlich <nathan@tootallnate.net> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <v8.h> #include <node.h> #include <mpg123.h> using namespace v8; using namespace node; namespace nodelame { /* Wrapper ObjectTemplate to hold `mpg123_handle` instances */ Persistent<ObjectTemplate> mhClass; Handle<Value> node_mpg123_init (const Arguments& args) { HandleScope scope; return scope.Close(Integer::New(mpg123_init())); } Handle<Value> node_mpg123_exit (const Arguments& args) { HandleScope scope; mpg123_exit(); return Undefined(); } Handle<Value> node_mpg123_new (const Arguments& args) { HandleScope scope; int error = 0; mpg123_handle *mh = mpg123_new(NULL, &error); Handle<Value> rtn; if (error == MPG123_OK) { Persistent<Object> o = Persistent<Object>::New(mhClass->NewInstance()); o->SetPointerInInternalField(0, mh); rtn = o; } else { rtn = Integer::New(error); } return scope.Close(rtn); } Handle<Value> node_mpg123_supported_decoders (const Arguments& args) { HandleScope scope; const char **decoders = mpg123_supported_decoders(); int i = 0; Handle<Array> rtn = Array::New(); while (*decoders != NULL) { rtn->Set(Integer::New(i++), String::New(*decoders)); decoders++; } return scope.Close(rtn); } Handle<Value> node_mpg123_decoders (const Arguments& args) { HandleScope scope; const char **decoders = mpg123_decoders(); int i = 0; Handle<Array> rtn = Array::New(); while (*decoders != NULL) { rtn->Set(Integer::New(i++), String::New(*decoders)); decoders++; } return scope.Close(rtn); } void InitMPG123(Handle<Object> target) { HandleScope scope; mhClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); mhClass->SetInternalFieldCount(1); NODE_SET_METHOD(target, "mpg123_init", node_mpg123_init); NODE_SET_METHOD(target, "mpg123_exit", node_mpg123_exit); NODE_SET_METHOD(target, "mpg123_new", node_mpg123_new); NODE_SET_METHOD(target, "mpg123_decoders", node_mpg123_decoders); NODE_SET_METHOD(target, "mpg123_supported_decoders", node_mpg123_supported_decoders); } } // nodelame namespace <commit_msg>Add a weak callback to the mh handles and automatically call delete on them.<commit_after>/* * Copyright (c) 2011, Nathan Rajlich <nathan@tootallnate.net> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <v8.h> #include <node.h> #include <mpg123.h> using namespace v8; using namespace node; namespace nodelame { /* Wrapper ObjectTemplate to hold `mpg123_handle` instances */ Persistent<ObjectTemplate> mhClass; Handle<Value> node_mpg123_init (const Arguments& args) { HandleScope scope; return scope.Close(Integer::New(mpg123_init())); } Handle<Value> node_mpg123_exit (const Arguments& args) { HandleScope scope; mpg123_exit(); return Undefined(); } void mh_weak_callback (Persistent<Value> wrapper, void *arg) { HandleScope scope; mpg123_handle *mh = (mpg123_handle *)arg; mpg123_delete(mh); wrapper.Dispose(); } Handle<Value> node_mpg123_new (const Arguments& args) { HandleScope scope; int error = 0; mpg123_handle *mh = mpg123_new(NULL, &error); Handle<Value> rtn; if (error == MPG123_OK) { Persistent<Object> o = Persistent<Object>::New(mhClass->NewInstance()); o->SetPointerInInternalField(0, mh); o.MakeWeak(mh, mh_weak_callback); rtn = o; } else { rtn = Integer::New(error); } return scope.Close(rtn); } Handle<Value> node_mpg123_supported_decoders (const Arguments& args) { HandleScope scope; const char **decoders = mpg123_supported_decoders(); int i = 0; Handle<Array> rtn = Array::New(); while (*decoders != NULL) { rtn->Set(Integer::New(i++), String::New(*decoders)); decoders++; } return scope.Close(rtn); } Handle<Value> node_mpg123_decoders (const Arguments& args) { HandleScope scope; const char **decoders = mpg123_decoders(); int i = 0; Handle<Array> rtn = Array::New(); while (*decoders != NULL) { rtn->Set(Integer::New(i++), String::New(*decoders)); decoders++; } return scope.Close(rtn); } void InitMPG123(Handle<Object> target) { HandleScope scope; mhClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); mhClass->SetInternalFieldCount(1); NODE_SET_METHOD(target, "mpg123_init", node_mpg123_init); NODE_SET_METHOD(target, "mpg123_exit", node_mpg123_exit); NODE_SET_METHOD(target, "mpg123_new", node_mpg123_new); NODE_SET_METHOD(target, "mpg123_decoders", node_mpg123_decoders); NODE_SET_METHOD(target, "mpg123_supported_decoders", node_mpg123_supported_decoders); } } // nodelame namespace <|endoftext|>
<commit_before>// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2013 Michael Fink // //! \file StandardPhotoModeView.cpp View for taking standard photos // // includes #include "stdafx.h" #include "resource.h" #include "StandardPhotoModeView.hpp" #include "IPhotoModeViewHost.hpp" #include "ImageFileManager.hpp" #include "CameraErrorDlg.hpp" #include "ShutterReleaseSettings.hpp" #include <boost/bind.hpp> StandardPhotoModeView::StandardPhotoModeView(IPhotoModeViewHost& host) throw() :m_host(host), m_cbShootingMode(propShootingMode), m_cbAperture(propAv), m_cbShutterSpeed(propTv), m_cbExposureComp(propExposureCompensation), m_cbWhiteBalance(propWhiteBalance), m_iPropertyHandlerId(-1) { } LRESULT StandardPhotoModeView::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { DoDataExchange(DDX_LOAD); m_spRemoteReleaseControl = m_host.StartRemoteReleaseControl(true); SetupImagePropertyManager(); // shooting mode change supported? if (!m_spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capChangeShootingMode)) { // no: disable shooting mode combobox m_cbShootingMode.EnableWindow(FALSE); } else { // yes: wait for changes in shooting mode property m_iPropertyHandlerId = m_spRemoteReleaseControl->AddPropertyEventHandler( boost::bind(&StandardPhotoModeView::OnUpdatedProperty, this, _1, _2)); } // set default release settings try { ShutterReleaseSettings settings(ShutterReleaseSettings::saveToBoth, boost::bind(&StandardPhotoModeView::OnFinishedTransfer, this, _1)); CString cszFilename = m_host.GetImageFileManager().NextFilename(imageTypeNormal); settings.Filename(cszFilename); m_spRemoteReleaseControl->SetDefaultReleaseSettings(settings); } catch(CameraException& ex) { CameraErrorDlg dlg(_T("Error while setting default shooting settings"), ex); dlg.DoModal(); return FALSE; } return TRUE; } LRESULT StandardPhotoModeView::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { // reset default release settings if (m_spRemoteReleaseControl != nullptr) { ShutterReleaseSettings settings(ShutterReleaseSettings::saveToBoth); try { m_spRemoteReleaseControl->SetDefaultReleaseSettings(settings); } catch(CameraException& /*ex*/) { } } if (m_iPropertyHandlerId != -1) m_spRemoteReleaseControl->RemovePropertyEventHandler(m_iPropertyHandlerId); m_upImagePropertyValueManager.reset(); return 0; } LRESULT StandardPhotoModeView::OnShootingModeSelChange(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { UpdateShootingModeDependentValues(); return 0; } LRESULT StandardPhotoModeView::OnButtonRelease(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { ShutterReleaseSettings settings(ShutterReleaseSettings::saveToBoth, boost::bind(&StandardPhotoModeView::OnFinishedTransfer, this, _1)); CString cszFilename = m_host.GetImageFileManager().NextFilename(imageTypeNormal); settings.Filename(cszFilename); try { m_spRemoteReleaseControl->Release(settings); } catch(CameraException& ex) { CameraErrorDlg dlg(_T("Couldn't release shutter"), ex); dlg.DoModal(); } return 0; } void StandardPhotoModeView::OnUpdatedProperty(RemoteReleaseControl::T_enPropertyEvent enPropertyEvent, unsigned int uiValue) { if (enPropertyEvent == RemoteReleaseControl::propEventPropertyChanged && uiValue == m_spRemoteReleaseControl->MapImagePropertyTypeToId(propShootingMode)) { // shooting mode has changed; update some fields UpdateShootingModeDependentValues(); } } void StandardPhotoModeView::OnFinishedTransfer(const ShutterReleaseSettings& settings) { CString cszText; cszText.Format(_T("Finished transfer: %s"), settings.Filename()); m_host.SetStatusText(cszText); } void StandardPhotoModeView::SetupImagePropertyManager() { m_upImagePropertyValueManager.reset(new ImagePropertyValueManager(*m_spRemoteReleaseControl)); m_cbShootingMode.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_cbAperture.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_cbShutterSpeed.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_cbExposureComp.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_cbWhiteBalance.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_upImagePropertyValueManager->AddControl(m_cbShootingMode); m_upImagePropertyValueManager->AddControl(m_cbAperture); m_upImagePropertyValueManager->AddControl(m_cbShutterSpeed); m_upImagePropertyValueManager->AddControl(m_cbExposureComp); m_upImagePropertyValueManager->AddControl(m_cbWhiteBalance); m_upImagePropertyValueManager->UpdateControls(); m_upImagePropertyValueManager->UpdateProperty( m_spRemoteReleaseControl->MapImagePropertyTypeToId(propShootingMode)); } void StandardPhotoModeView::UpdateShootingModeDependentValues() { unsigned int uiShootingModeId = m_spRemoteReleaseControl->MapImagePropertyTypeToId(propShootingMode); ImageProperty shootingMode = m_spRemoteReleaseControl->GetImageProperty(uiShootingModeId); unsigned int uiShootingMode = shootingMode.Value().Get<unsigned int>(); unsigned int uiM = m_spRemoteReleaseControl->MapShootingModeToImagePropertyValue(RemoteReleaseControl::shootingModeM).Value().Get<unsigned int>(); unsigned int uiAv = m_spRemoteReleaseControl->MapShootingModeToImagePropertyValue(RemoteReleaseControl::shootingModeAv).Value().Get<unsigned int>(); unsigned int uiTv = m_spRemoteReleaseControl->MapShootingModeToImagePropertyValue(RemoteReleaseControl::shootingModeTv).Value().Get<unsigned int>(); unsigned int uiP = m_spRemoteReleaseControl->MapShootingModeToImagePropertyValue(RemoteReleaseControl::shootingModeP).Value().Get<unsigned int>(); bool bReadOnlyAv = (uiShootingMode != uiM) && (uiShootingMode == uiTv || uiShootingMode == uiP); bool bReadOnlyTv = (uiShootingMode != uiM) && (uiShootingMode == uiAv || uiShootingMode == uiP); bool bReadOnlyExp = uiShootingMode == uiM; m_cbAperture.UpdateValuesList(); m_cbAperture.UpdateValue(); m_cbAperture.EnableWindow(!bReadOnlyAv); m_cbShutterSpeed.UpdateValuesList(); m_cbShutterSpeed.UpdateValue(); m_cbShutterSpeed.EnableWindow(!bReadOnlyTv); m_cbExposureComp.UpdateValuesList(); m_cbExposureComp.UpdateValue(); m_cbExposureComp.EnableWindow(!bReadOnlyExp); } <commit_msg>simplified comparing which shooting mode is used, in standard photo mode<commit_after>// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2013 Michael Fink // //! \file StandardPhotoModeView.cpp View for taking standard photos // // includes #include "stdafx.h" #include "resource.h" #include "StandardPhotoModeView.hpp" #include "IPhotoModeViewHost.hpp" #include "ImageFileManager.hpp" #include "CameraErrorDlg.hpp" #include "ShutterReleaseSettings.hpp" #include "ShootingMode.hpp" #include <boost/bind.hpp> StandardPhotoModeView::StandardPhotoModeView(IPhotoModeViewHost& host) throw() :m_host(host), m_cbShootingMode(propShootingMode), m_cbAperture(propAv), m_cbShutterSpeed(propTv), m_cbExposureComp(propExposureCompensation), m_cbWhiteBalance(propWhiteBalance), m_iPropertyHandlerId(-1) { } LRESULT StandardPhotoModeView::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { DoDataExchange(DDX_LOAD); m_spRemoteReleaseControl = m_host.StartRemoteReleaseControl(true); SetupImagePropertyManager(); // shooting mode change supported? if (!m_spRemoteReleaseControl->GetCapability(RemoteReleaseControl::capChangeShootingMode)) { // no: disable shooting mode combobox m_cbShootingMode.EnableWindow(FALSE); } else { // yes: wait for changes in shooting mode property m_iPropertyHandlerId = m_spRemoteReleaseControl->AddPropertyEventHandler( boost::bind(&StandardPhotoModeView::OnUpdatedProperty, this, _1, _2)); } // set default release settings try { ShutterReleaseSettings settings(ShutterReleaseSettings::saveToBoth, boost::bind(&StandardPhotoModeView::OnFinishedTransfer, this, _1)); CString cszFilename = m_host.GetImageFileManager().NextFilename(imageTypeNormal); settings.Filename(cszFilename); m_spRemoteReleaseControl->SetDefaultReleaseSettings(settings); } catch(CameraException& ex) { CameraErrorDlg dlg(_T("Error while setting default shooting settings"), ex); dlg.DoModal(); return FALSE; } return TRUE; } LRESULT StandardPhotoModeView::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { // reset default release settings if (m_spRemoteReleaseControl != nullptr) { ShutterReleaseSettings settings(ShutterReleaseSettings::saveToBoth); try { m_spRemoteReleaseControl->SetDefaultReleaseSettings(settings); } catch(CameraException& /*ex*/) { } } if (m_iPropertyHandlerId != -1) m_spRemoteReleaseControl->RemovePropertyEventHandler(m_iPropertyHandlerId); m_upImagePropertyValueManager.reset(); return 0; } LRESULT StandardPhotoModeView::OnShootingModeSelChange(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { UpdateShootingModeDependentValues(); return 0; } LRESULT StandardPhotoModeView::OnButtonRelease(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { ShutterReleaseSettings settings(ShutterReleaseSettings::saveToBoth, boost::bind(&StandardPhotoModeView::OnFinishedTransfer, this, _1)); CString cszFilename = m_host.GetImageFileManager().NextFilename(imageTypeNormal); settings.Filename(cszFilename); try { m_spRemoteReleaseControl->Release(settings); } catch(CameraException& ex) { CameraErrorDlg dlg(_T("Couldn't release shutter"), ex); dlg.DoModal(); } return 0; } void StandardPhotoModeView::OnUpdatedProperty(RemoteReleaseControl::T_enPropertyEvent enPropertyEvent, unsigned int uiValue) { if (enPropertyEvent == RemoteReleaseControl::propEventPropertyChanged && uiValue == m_spRemoteReleaseControl->MapImagePropertyTypeToId(propShootingMode)) { // shooting mode has changed; update some fields UpdateShootingModeDependentValues(); } } void StandardPhotoModeView::OnFinishedTransfer(const ShutterReleaseSettings& settings) { CString cszText; cszText.Format(_T("Finished transfer: %s"), settings.Filename()); m_host.SetStatusText(cszText); } void StandardPhotoModeView::SetupImagePropertyManager() { m_upImagePropertyValueManager.reset(new ImagePropertyValueManager(*m_spRemoteReleaseControl)); m_cbShootingMode.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_cbAperture.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_cbShutterSpeed.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_cbExposureComp.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_cbWhiteBalance.SetRemoteReleaseControl(m_spRemoteReleaseControl); m_upImagePropertyValueManager->AddControl(m_cbShootingMode); m_upImagePropertyValueManager->AddControl(m_cbAperture); m_upImagePropertyValueManager->AddControl(m_cbShutterSpeed); m_upImagePropertyValueManager->AddControl(m_cbExposureComp); m_upImagePropertyValueManager->AddControl(m_cbWhiteBalance); m_upImagePropertyValueManager->UpdateControls(); m_upImagePropertyValueManager->UpdateProperty( m_spRemoteReleaseControl->MapImagePropertyTypeToId(propShootingMode)); } void StandardPhotoModeView::UpdateShootingModeDependentValues() { ShootingMode shootingMode(m_spRemoteReleaseControl); ImageProperty currentMode = shootingMode.Current(); bool bIsM = currentMode.Value() == shootingMode.Manual().Value(); bool bIsAv = currentMode.Value() == shootingMode.Av().Value(); bool bIsTv = currentMode.Value() == shootingMode.Tv().Value(); bool bIsP = currentMode.Value() == shootingMode.Program().Value(); bool bReadOnlyAv = !bIsM && (bIsTv || bIsP); bool bReadOnlyTv = !bIsM && (bIsAv || bIsP); bool bReadOnlyExp = bIsM; m_cbAperture.UpdateValuesList(); m_cbAperture.UpdateValue(); m_cbAperture.EnableWindow(!bReadOnlyAv); m_cbShutterSpeed.UpdateValuesList(); m_cbShutterSpeed.UpdateValue(); m_cbShutterSpeed.EnableWindow(!bReadOnlyTv); m_cbExposureComp.UpdateValuesList(); m_cbExposureComp.UpdateValue(); m_cbExposureComp.EnableWindow(!bReadOnlyExp); } <|endoftext|>
<commit_before>/* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for licence. */ #include "../../include/obj/NiNode.h" #include "../../include/obj/NiAVObject.h" #include "../../include/obj/NiDynamicEffect.h" #include "../../include/obj/NiSkinInstance.h" #include "../../include/obj/NiSkinData.h" #include "../../include/obj/NiTriBasedGeom.h" using namespace Niflib; //Definition of TYPE constant const Type NiNode::TYPE("NiNode", &NI_NODE_PARENT::TypeConst() ); NiNode::NiNode() NI_NODE_CONSTRUCT { //Set flag to default of 8: not a skin influence flags = 8; } NiNode::~NiNode() { //Unbind any attached skins - must happen before children are cleared for ( list<NiSkinInstance*>::iterator it = skins.begin(); it != skins.end(); ++it ) { (*it)->SkeletonLost(); } //Clear Children ClearChildren(); } void NiNode::Read( istream& in, list<unsigned int> & link_stack, unsigned int version, unsigned int user_version ) { InternalRead( in, link_stack, version, user_version ); } void NiNode::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, unsigned int version, unsigned int user_version ) const { InternalWrite( out, link_map, version, user_version ); } string NiNode::asString( bool verbose ) const { return InternalAsString( verbose ); } void NiNode::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, unsigned int version, unsigned int user_version ) { InternalFixLinks( objects, link_stack, version, user_version ); //Connect children to their parents and remove any NULL ones for ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) { if ( *it == NULL) { it = children.erase( it ); } else { (*it)->SetParent(this); ++it; } } } list<NiObjectRef> NiNode::GetRefs() const { return InternalGetRefs(); } const Type & NiNode::GetType() const { return TYPE; }; void NiNode::AddChild( Ref<NiAVObject> obj ) { if ( obj->GetParent() != NULL ) { throw runtime_error( "You have attempted to add a child to a NiNode which already is the child of another NiNode." ); } obj->SetParent( this ); children.push_back( obj ); } void NiNode::RemoveChild( Ref<NiAVObject> obj ) { //Search child list for the one to remove for ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) { if ( *it == obj ) { //Ensure that this child is not a skin influence NiNodeRef niNode = DynamicCast<NiNode>((*it)); if ( niNode != NULL && niNode->IsSkinInfluence() == true ) { throw runtime_error("You cannot remove a node child that is a skin influence. Detatch the skin first."); } (*it)->SetParent(NULL); it = children.erase( it ); } else { ++it; } } } void NiNode::ClearChildren() { for ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ++it) { if ( *it != NULL ) { (*it)->SetParent(NULL); } } children.clear(); } vector< Ref<NiAVObject> > NiNode::GetChildren() const { return children; } void NiNode::AddEffect( Ref<NiDynamicEffect> obj ) { obj->SetParent( this ); effects.push_back( obj ); } void NiNode::RemoveEffect( Ref<NiDynamicEffect> obj ) { //Search Effect list for the one to remove for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ) { if ( *it == obj ) { (*it)->SetParent(NULL); it = effects.erase( it ); } else { ++it; } } } void NiNode::ClearEffects() { for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ++it) { if (*it) (*it)->SetParent(NULL); } effects.clear(); } vector< Ref<NiDynamicEffect> > NiNode::GetEffects() const { return effects; } bool NiNode::IsSkeletonRoot() const { return ( skins.size() > 0 ); } bool NiNode::IsSkinInfluence() const { return ((flags & 8) == 0); } void NiNode::AddSkin( NiSkinInstance * skin_inst ) { skins.push_back( skin_inst ); } void NiNode::RemoveSkin( NiSkinInstance * skin_inst ) { //Remove the reference skins.remove( skin_inst); //Ensure that any multiply referenced bone nodes still //have their skin flag set vector<NiNodeRef> bones; for ( list<NiSkinInstance*>::iterator it = skins.begin(); it != skins.end(); ++it ) { bones = (*it)->GetBones(); for ( unsigned int i = 0; i < bones.size(); ++i ) { bones[i]->SetSkinFlag(true); } } } void NiNode::SetSkinFlag( bool n ) { if ( IsSkinInfluence() == n ) { //Already set to the requested value return; } else { //Requested value is different, flip bit flags ^= 8; } } void NiNode::GoToSkeletonBindPosition() { //map<NiNodeRef, Matrix44> world_positions; //Loop through all attached skins, straightening the skeleton on each for ( list<NiSkinInstance*>::iterator it = skins.begin(); it != skins.end(); ++it ) { //Get Bone list and Skin Data vector<NiNodeRef> bone_nodes = (*it)->GetBones(); NiSkinDataRef skin_data = (*it)->GetSkinData(); if ( skin_data == NULL ) { //There's no skin data for this skin instance; skip it. continue; } //Make sure the counts match if ( bone_nodes.size() != skin_data->GetBoneCount() ) { throw runtime_error( "Bone counts in NiSkinInstance and attached NiSkinData must match" ); } //Loop through all bones influencing this skin for ( unsigned int i = 0; i < bone_nodes.size(); ++i ) { //Get current offset Matrix for this bone Matrix44 parent_offset = skin_data->GetBoneTransform(i); //Loop through all bones again, checking for any that have this bone as a parent for ( unsigned int j = 0; j < bone_nodes.size(); ++j ) { if ( bone_nodes[j]->GetParent() == bone_nodes[i] ) { //Node 2 has node 1 as a parent //Get child offset Matrix33 Matrix44 child_offset = skin_data->GetBoneTransform(j); //Do calculation to get correct bone postion in relation to parent Matrix44 child_pos = child_offset.Inverse() * parent_offset; //bones[j]->SetWorldBindPos( child_pos ); bone_nodes[j]->SetLocalRotation( child_pos.GetRotation() ); bone_nodes[j]->SetLocalScale( 1.0f ); bone_nodes[j]->SetLocalTranslation( child_pos.GetTranslation() ); } } } } } void NiNode::PropagateTransform() { Matrix44 par_trans = this->GetLocalTransform(); //Loop through each child and apply this node's transform to it for ( unsigned i = 0; i < children.size(); ++i ) { children[i]->SetLocalTransform( children[i]->GetLocalTransform() * par_trans ); } //Nowthat the transforms have been propogated, clear them out this->SetLocalTransform( Matrix44::Identity() ); } bool NiNode::IsSplitMeshProxy() const { //Let us guess that a node is a split mesh proxy if: // 1) It is not a skin influence // 2) All its children are NiTriBasedGeom derived objects. // 3) All its children have identity transforms. // 4) It has more than one child // 5) All meshes are visible // 6) ???? May need more criteria as time goes on. if ( this->IsSkinInfluence() ) { return false; } if ( children.size() < 2 ) { return false; } for ( unsigned i = 0; i < children.size(); ++i ) { if ( children[i]->IsDerivedType( NiTriBasedGeom::TypeConst() ) == false ) { return false; } if ( children[i]->GetLocalTransform() != Matrix44::Identity() ) { return false; } if ( children[i]->GetVisibility() == false ) { return false; } } //Made it all the way through the loop without returning false return true; } const Type & NiNode::TypeConst() { return TYPE; } <commit_msg>Changed NiNode AddChild function to keep NiTriBasedGeom-derived objects at the top of the list. Fixes issue with Oblivion flattened skin file hierarchies where the NiTriBasedGeom skin was appearing after the NiNode bones that it used in the child list of their mutual parent.<commit_after>/* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for licence. */ #include "../../include/obj/NiNode.h" #include "../../include/obj/NiAVObject.h" #include "../../include/obj/NiDynamicEffect.h" #include "../../include/obj/NiSkinInstance.h" #include "../../include/obj/NiSkinData.h" #include "../../include/obj/NiTriBasedGeom.h" using namespace Niflib; //Definition of TYPE constant const Type NiNode::TYPE("NiNode", &NI_NODE_PARENT::TypeConst() ); NiNode::NiNode() NI_NODE_CONSTRUCT { //Set flag to default of 8: not a skin influence flags = 8; } NiNode::~NiNode() { //Unbind any attached skins - must happen before children are cleared for ( list<NiSkinInstance*>::iterator it = skins.begin(); it != skins.end(); ++it ) { (*it)->SkeletonLost(); } //Clear Children ClearChildren(); } void NiNode::Read( istream& in, list<unsigned int> & link_stack, unsigned int version, unsigned int user_version ) { InternalRead( in, link_stack, version, user_version ); } void NiNode::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, unsigned int version, unsigned int user_version ) const { InternalWrite( out, link_map, version, user_version ); } string NiNode::asString( bool verbose ) const { return InternalAsString( verbose ); } void NiNode::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, unsigned int version, unsigned int user_version ) { InternalFixLinks( objects, link_stack, version, user_version ); //Connect children to their parents and remove any NULL ones for ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) { if ( *it == NULL) { it = children.erase( it ); } else { (*it)->SetParent(this); ++it; } } } list<NiObjectRef> NiNode::GetRefs() const { return InternalGetRefs(); } const Type & NiNode::GetType() const { return TYPE; }; void NiNode::AddChild( Ref<NiAVObject> obj ) { if ( obj->GetParent() != NULL ) { throw runtime_error( "You have attempted to add a child to a NiNode which already is the child of another NiNode." ); } obj->SetParent( this ); //Sometimes NiTriBasedGeom with skins can be siblings of NiNodes that //represent joints for that same skin. This is not allowed, so we have //to prevent it by always adding NiTriBasedGeom to the begining of the child list. NiTriBasedGeomRef niGeom = DynamicCast<NiTriBasedGeom>(obj); if ( niGeom != NULL ) { //This is a NiTriBasedGeom, so shift all children to the right size_t old_size = children.size(); children.resize( children.size() + 1 ); for ( size_t i = children.size() - 1; i >= 1; --i ) { children[i] = children[i-1]; } //Now add the new child to the begining of the list children[0] = obj; } else { //This is some other type of object. Just add it to the end of the list. children.push_back( obj ); } } void NiNode::RemoveChild( Ref<NiAVObject> obj ) { //Search child list for the one to remove for ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ) { if ( *it == obj ) { //Ensure that this child is not a skin influence NiNodeRef niNode = DynamicCast<NiNode>((*it)); if ( niNode != NULL && niNode->IsSkinInfluence() == true ) { throw runtime_error("You cannot remove a node child that is a skin influence. Detatch the skin first."); } (*it)->SetParent(NULL); it = children.erase( it ); } else { ++it; } } } void NiNode::ClearChildren() { for ( vector< NiAVObjectRef >::iterator it = children.begin(); it != children.end(); ++it) { if ( *it != NULL ) { (*it)->SetParent(NULL); } } children.clear(); } vector< Ref<NiAVObject> > NiNode::GetChildren() const { return children; } void NiNode::AddEffect( Ref<NiDynamicEffect> obj ) { obj->SetParent( this ); effects.push_back( obj ); } void NiNode::RemoveEffect( Ref<NiDynamicEffect> obj ) { //Search Effect list for the one to remove for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ) { if ( *it == obj ) { (*it)->SetParent(NULL); it = effects.erase( it ); } else { ++it; } } } void NiNode::ClearEffects() { for ( vector< NiDynamicEffectRef >::iterator it = effects.begin(); it != effects.end(); ++it) { if (*it) (*it)->SetParent(NULL); } effects.clear(); } vector< Ref<NiDynamicEffect> > NiNode::GetEffects() const { return effects; } bool NiNode::IsSkeletonRoot() const { return ( skins.size() > 0 ); } bool NiNode::IsSkinInfluence() const { return ((flags & 8) == 0); } void NiNode::AddSkin( NiSkinInstance * skin_inst ) { skins.push_back( skin_inst ); } void NiNode::RemoveSkin( NiSkinInstance * skin_inst ) { //Remove the reference skins.remove( skin_inst); //Ensure that any multiply referenced bone nodes still //have their skin flag set vector<NiNodeRef> bones; for ( list<NiSkinInstance*>::iterator it = skins.begin(); it != skins.end(); ++it ) { bones = (*it)->GetBones(); for ( unsigned int i = 0; i < bones.size(); ++i ) { bones[i]->SetSkinFlag(true); } } } void NiNode::SetSkinFlag( bool n ) { if ( IsSkinInfluence() == n ) { //Already set to the requested value return; } else { //Requested value is different, flip bit flags ^= 8; } } void NiNode::GoToSkeletonBindPosition() { //map<NiNodeRef, Matrix44> world_positions; //Loop through all attached skins, straightening the skeleton on each for ( list<NiSkinInstance*>::iterator it = skins.begin(); it != skins.end(); ++it ) { //Get Bone list and Skin Data vector<NiNodeRef> bone_nodes = (*it)->GetBones(); NiSkinDataRef skin_data = (*it)->GetSkinData(); if ( skin_data == NULL ) { //There's no skin data for this skin instance; skip it. continue; } //Make sure the counts match if ( bone_nodes.size() != skin_data->GetBoneCount() ) { throw runtime_error( "Bone counts in NiSkinInstance and attached NiSkinData must match" ); } //Loop through all bones influencing this skin for ( unsigned int i = 0; i < bone_nodes.size(); ++i ) { //Get current offset Matrix for this bone Matrix44 parent_offset = skin_data->GetBoneTransform(i); //Loop through all bones again, checking for any that have this bone as a parent for ( unsigned int j = 0; j < bone_nodes.size(); ++j ) { if ( bone_nodes[j]->GetParent() == bone_nodes[i] ) { //Node 2 has node 1 as a parent //Get child offset Matrix33 Matrix44 child_offset = skin_data->GetBoneTransform(j); //Do calculation to get correct bone postion in relation to parent Matrix44 child_pos = child_offset.Inverse() * parent_offset; //bones[j]->SetWorldBindPos( child_pos ); bone_nodes[j]->SetLocalRotation( child_pos.GetRotation() ); bone_nodes[j]->SetLocalScale( 1.0f ); bone_nodes[j]->SetLocalTranslation( child_pos.GetTranslation() ); } } } } } void NiNode::PropagateTransform() { Matrix44 par_trans = this->GetLocalTransform(); //Loop through each child and apply this node's transform to it for ( unsigned i = 0; i < children.size(); ++i ) { children[i]->SetLocalTransform( children[i]->GetLocalTransform() * par_trans ); } //Nowthat the transforms have been propogated, clear them out this->SetLocalTransform( Matrix44::Identity() ); } bool NiNode::IsSplitMeshProxy() const { //Let us guess that a node is a split mesh proxy if: // 1) It is not a skin influence // 2) All its children are NiTriBasedGeom derived objects. // 3) All its children have identity transforms. // 4) It has more than one child // 5) All meshes are visible // 6) ???? May need more criteria as time goes on. if ( this->IsSkinInfluence() ) { return false; } if ( children.size() < 2 ) { return false; } for ( unsigned i = 0; i < children.size(); ++i ) { if ( children[i]->IsDerivedType( NiTriBasedGeom::TypeConst() ) == false ) { return false; } if ( children[i]->GetLocalTransform() != Matrix44::Identity() ) { return false; } if ( children[i]->GetVisibility() == false ) { return false; } } //Made it all the way through the loop without returning false return true; } const Type & NiNode::TypeConst() { return TYPE; } <|endoftext|>
<commit_before>// Copyright (c) 2015-2017 William W. Fisher (at gmail dot com) // This file is distributed under the MIT License. #include "ofp/libofp.h" #include <stdlib.h> #include <string> #include "ofp/log.h" #include "ofp/yaml/decoder.h" #include "ofp/yaml/encoder.h" static void buf_set(libofp_buffer *buf, const void *data, size_t len) { char *newbuf = static_cast<char *>(malloc(len + 1)); ofp::log::fatal_if_null(newbuf); memcpy(newbuf, data, len); newbuf[len] = 0; buf->data = newbuf; buf->length = len; } static void buf_set(libofp_buffer *buf, const llvm::StringRef &val) { buf_set(buf, val.data(), val.size()); } void libofp_version(libofp_buffer *result) { std::string libofpCommit{LIBOFP_GIT_COMMIT_LIBOFP}; std::string buf; llvm::raw_string_ostream oss{buf}; oss << LIBOFP_VERSION_STRING << " (" << libofpCommit.substr(0, 7) << ")"; oss << " <" << LIBOFP_GITHUB_URL << ">"; buf_set(result, oss.str()); } int libofp_encode(libofp_buffer *result, const char *yaml_input, uint32_t flags) { // `flags` unused for now llvm::StringRef text{yaml_input}; ofp::yaml::Encoder encoder{text, false, 1, 0}; auto err = encoder.error(); if (!err.empty()) { buf_set(result, err); return -1; } buf_set(result, encoder.data(), encoder.size()); return 0; } int libofp_decode(libofp_buffer *result, const libofp_buffer *input, uint32_t flags) { // `flags` unused for now if (input->length < sizeof(ofp::Header)) { buf_set(result, "Buffer size < 8 bytes"); return -1; } if (input->length > 0xffff) { buf_set(result, "Buffer size > 65535 bytes"); return -1; } if (ofp::Big16_unaligned(ofp::BytePtr(input->data) + 2) != input->length) { buf_set(result, "Message length does not match buffer size"); return -1; } ofp::Message message{input->data, input->length}; message.normalize(); ofp::yaml::Decoder decoder{&message, false, false}; auto err = decoder.error(); if (!err.empty()) { buf_set(result, err); return -1; } buf_set(result, decoder.result()); return 0; } void libofp_buffer_free(libofp_buffer *buffer) { if (buffer->data) { free(buffer->data); buffer->data = nullptr; buffer->length = 0; } } const uint32_t kMaxSupportedLen = 1073741823; const int32_t kInvalidArgumentsError = -1; const int32_t kInternalError = -2; static int32_t buf_copy(char *output, size_t output_len, const void *data, size_t len, bool error) { if (len > kMaxSupportedLen) { return kInternalError; } int32_t result = static_cast<int32_t>(len); if (len > output_len) { return -result; } assert(len <= output_len); std::memcpy(output, data, len); if (error) { return -result; } return result; } static int32_t buf_copy(char *output, size_t output_len, const char *str, bool error) { return buf_copy(output, output_len, str, strlen(str), error); } static int32_t oftr_version(char *output, size_t output_len) { std::string libofpCommit{LIBOFP_GIT_COMMIT_LIBOFP}; std::string buf; llvm::raw_string_ostream oss{buf}; oss << LIBOFP_VERSION_STRING << " (" << libofpCommit.substr(0, 7) << ")"; oss << " <" << LIBOFP_GITHUB_URL << ">"; oss.flush(); return buf_copy(output, output_len, buf.data(), buf.size(), false); } static int32_t oftr_encode(const char *input, size_t input_len, uint8_t version, char *output, size_t output_len) { llvm::StringRef text{input, input_len}; ofp::yaml::Encoder encoder{text, true, 1, version}; auto err = encoder.error(); if (!err.empty()) { return buf_copy(output, output_len, err.data(), err.size(), true); } return buf_copy(output, output_len, encoder.data(), encoder.size(), false); } static int32_t oftr_decode(const char *input, size_t input_len, char *output, size_t output_len) { if (input_len < sizeof(ofp::Header)) { return buf_copy(output, output_len, "Buffer size < 8 bytes", true); } if (input_len > 0xffff) { return buf_copy(output, output_len, "Buffer size > 65535 bytes", true); } if (ofp::Big16_unaligned(ofp::BytePtr(input) + 2) != input_len) { return buf_copy(output, output_len, "Message length does not match buffer size", true); } ofp::Message message{input, input_len}; message.normalize(); ofp::yaml::Decoder decoder{&message, false, false}; auto err = decoder.error(); if (!err.empty()) { return buf_copy(output, output_len, err.data(), err.size(), true); } auto result = decoder.result(); return buf_copy(output, output_len, result.data(), result.size(), false); } int32_t oftr_call(uint32_t opcode, const char *input, size_t input_len, char *output, size_t output_len) { if ((input_len > kMaxSupportedLen) || (output_len > kMaxSupportedLen) || (!input && input_len > 0) || (!output && output_len > 0)) { return kInvalidArgumentsError; } switch (opcode & 0x00FF) { case OFTR_VERSION: return oftr_version(output, output_len); case OFTR_ENCODE: return oftr_encode(input, input_len, (opcode >> 24), output, output_len); case OFTR_DECODE: return oftr_decode(input, input_len, output, output_len); default: return kInvalidArgumentsError; } } <commit_msg>Fix coverity error.<commit_after>// Copyright (c) 2015-2017 William W. Fisher (at gmail dot com) // This file is distributed under the MIT License. #include "ofp/libofp.h" #include <stdlib.h> #include <string> #include "ofp/log.h" #include "ofp/yaml/decoder.h" #include "ofp/yaml/encoder.h" static void buf_set(libofp_buffer *buf, const void *data, size_t len) { char *newbuf = static_cast<char *>(malloc(len + 1)); ofp::log::fatal_if_null(newbuf); memcpy(newbuf, data, len); newbuf[len] = 0; buf->data = newbuf; buf->length = len; } static void buf_set(libofp_buffer *buf, const llvm::StringRef &val) { buf_set(buf, val.data(), val.size()); } void libofp_version(libofp_buffer *result) { std::string libofpCommit{LIBOFP_GIT_COMMIT_LIBOFP}; std::string buf; llvm::raw_string_ostream oss{buf}; oss << LIBOFP_VERSION_STRING << " (" << libofpCommit.substr(0, 7) << ")"; oss << " <" << LIBOFP_GITHUB_URL << ">"; buf_set(result, oss.str()); } int libofp_encode(libofp_buffer *result, const char *yaml_input, uint32_t flags) { // `flags` unused for now llvm::StringRef text{yaml_input}; ofp::yaml::Encoder encoder{text, false, 1, 0}; auto err = encoder.error(); if (!err.empty()) { buf_set(result, err); return -1; } buf_set(result, encoder.data(), encoder.size()); return 0; } int libofp_decode(libofp_buffer *result, const libofp_buffer *input, uint32_t flags) { // `flags` unused for now if (input->length < sizeof(ofp::Header)) { buf_set(result, "Buffer size < 8 bytes"); return -1; } if (input->length > 0xffff) { buf_set(result, "Buffer size > 65535 bytes"); return -1; } if (ofp::Big16_unaligned(ofp::BytePtr(input->data) + 2) != input->length) { buf_set(result, "Message length does not match buffer size"); return -1; } ofp::Message message{input->data, input->length}; message.normalize(); ofp::yaml::Decoder decoder{&message, false, false}; auto err = decoder.error(); if (!err.empty()) { buf_set(result, err); return -1; } buf_set(result, decoder.result()); return 0; } void libofp_buffer_free(libofp_buffer *buffer) { if (buffer->data) { free(buffer->data); buffer->data = nullptr; buffer->length = 0; } } const uint32_t kMaxSupportedLen = 1073741823; const int32_t kInvalidArgumentsError = -1; const int32_t kInternalError = -2; static int32_t buf_copy(char *output, size_t output_len, const void *data, size_t len, bool error) { if (len > kMaxSupportedLen) { return kInternalError; } int32_t result = static_cast<int32_t>(len); if (len > output_len) { return -result; } assert(len <= output_len); if (len > 0) { std::memcpy(output, data, len); } if (error) { return -result; } return result; } static int32_t buf_copy(char *output, size_t output_len, const char *str, bool error) { return buf_copy(output, output_len, str, strlen(str), error); } static int32_t oftr_version(char *output, size_t output_len) { std::string libofpCommit{LIBOFP_GIT_COMMIT_LIBOFP}; std::string buf; llvm::raw_string_ostream oss{buf}; oss << LIBOFP_VERSION_STRING << " (" << libofpCommit.substr(0, 7) << ")"; oss << " <" << LIBOFP_GITHUB_URL << ">"; oss.flush(); return buf_copy(output, output_len, buf.data(), buf.size(), false); } static int32_t oftr_encode(const char *input, size_t input_len, uint8_t version, char *output, size_t output_len) { llvm::StringRef text{input, input_len}; ofp::yaml::Encoder encoder{text, true, 1, version}; auto err = encoder.error(); if (!err.empty()) { return buf_copy(output, output_len, err.data(), err.size(), true); } return buf_copy(output, output_len, encoder.data(), encoder.size(), false); } static int32_t oftr_decode(const char *input, size_t input_len, char *output, size_t output_len) { if (input_len < sizeof(ofp::Header)) { return buf_copy(output, output_len, "Buffer size < 8 bytes", true); } if (input_len > 0xffff) { return buf_copy(output, output_len, "Buffer size > 65535 bytes", true); } if (ofp::Big16_unaligned(ofp::BytePtr(input) + 2) != input_len) { return buf_copy(output, output_len, "Message length does not match buffer size", true); } ofp::Message message{input, input_len}; message.normalize(); ofp::yaml::Decoder decoder{&message, false, false}; auto err = decoder.error(); if (!err.empty()) { return buf_copy(output, output_len, err.data(), err.size(), true); } auto result = decoder.result(); return buf_copy(output, output_len, result.data(), result.size(), false); } int32_t oftr_call(uint32_t opcode, const char *input, size_t input_len, char *output, size_t output_len) { if ((input_len > kMaxSupportedLen) || (output_len > kMaxSupportedLen) || (!input && input_len > 0) || (!output && output_len > 0)) { return kInvalidArgumentsError; } switch (opcode & 0x00FF) { case OFTR_VERSION: return oftr_version(output, output_len); case OFTR_ENCODE: return oftr_encode(input, input_len, (opcode >> 24), output, output_len); case OFTR_DECODE: return oftr_decode(input, input_len, output, output_len); default: return kInvalidArgumentsError; } } <|endoftext|>
<commit_before>#include "tile.h" #include "framework/framework.h" namespace OpenApoc { TileMap::TileMap(Framework &fw, Vec3<int> size) : fw(fw), size(size) { tiles.resize(size.z); for (int z = 0; z < size.z; z++) { tiles[z].resize(size.y); for (int y = 0; y < size.y; y++) { tiles[z][y].reserve(size.x); for (int x = 0; x < size.x; x++) { tiles[z][y].emplace_back(*this, Vec3<int>{x,y,z}); } } } } void TileMap::update(unsigned int ticks) { //Default tilemap update calls update(ticks) on all tiles //Subclasses can optimise this if they know which tiles might be 'active' for (auto& object : this->activeObjects) object->update(ticks); } TileMap::~TileMap() { } Tile::Tile(TileMap &map, Vec3<int> position) : map(map), position(position) { } TileObject::TileObject(Tile *owningTile, Vec3<float> position, Vec3<float> size, bool visible, bool collides, std::shared_ptr<Image> sprite) : owningTile(owningTile), position(position), size(size), visible(visible), collides(collides), sprite(sprite) { } TileObject::~TileObject() { } Cubeoid<int> TileObject::getBoundingBox() { Vec3<int> p1 {(int)floor((float)position.x), (int)floor((float)position.y), (int)floor((float)position.z)}; Vec3<int> p2 {(int)ceil((float)position.x + size.x), (int)ceil((float)position.y + size.y), (int)ceil((float)position.z + size.z)}; return Cubeoid<int>{p1,p2}; } Vec3<float> TileObject::getSize() { return this->size; } Vec3<float> TileObject::getPosition() { return this->position; } Image& TileObject::getSprite() { return *this->sprite; } TileObjectCollisionVoxels& TileObject::getCollisionVoxels() { return this->collisionVoxels; } class PathComparer { public: Vec3<float> dest; Vec3<float> origin; PathComparer(Vec3<int> d) : dest{d.x, d.y, d.z}{} bool operator() (Tile* t1, Tile* t2) { Vec3<float> t1Pos {t1->position.x, t1->position.y, t1->position.z}; Vec3<float> t2Pos {t2->position.x, t2->position.y, t2->position.z}; Vec3<float> t1tod = dest - t1Pos; Vec3<float> t2tod = dest - t2Pos; float t1cost = glm::length(t1tod); float t2cost = glm::length(t2tod); t1cost += glm::length(t1Pos-origin); t2cost += glm::length(t2Pos-origin); return (t1cost < t2cost); } }; #define THRESHOLD_ITERATIONS 2000 static bool findNextNodeOnPath(PathComparer &comparer, TileMap &map, std::list<Tile*> &currentPath, Vec3<int> destination, volatile unsigned long *numIterations) { if (currentPath.back()->position == destination) return true; if (*numIterations > THRESHOLD_ITERATIONS) return false; *numIterations = (*numIterations)+1; std::vector<Tile*> fringe; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { Vec3<int> currentPosition = currentPath.back()->position; if (z == 0 && y == 0 && x == 0) continue; Vec3<int> nextPosition = currentPosition; nextPosition.x += x; nextPosition.y += y; nextPosition.z += z; if (nextPosition.z < 0 || nextPosition.z >= map.size.z || nextPosition.y < 0 || nextPosition.y >= map.size.y || nextPosition.x < 0 || nextPosition.x >= map.size.x) continue; Tile *tile = &map.tiles[nextPosition.z][nextPosition.y][nextPosition.x]; //FIXME: Make 'blocked' tiles cleverer (e.g. don't plan around objects that will move anyway?) if (!tile->objects.empty()) continue; //Already visited this tile if (std::find(currentPath.begin(), currentPath.end(), tile) != currentPath.end()) continue; fringe.push_back(tile); } } } std::sort(fringe.begin(), fringe.end(), comparer); for (auto tile : fringe) { currentPath.push_back(tile); comparer.origin = {tile->position.x, tile->position.y, tile->position.z}; if (findNextNodeOnPath(comparer, map, currentPath, destination, numIterations)) return true; currentPath.pop_back(); } return false; } std::list<Tile*> TileMap::findShortestPath(Vec3<int> origin, Vec3<int> destination) { volatile unsigned long numIterations = 0; std::list<Tile*> path; PathComparer pc(destination); if (origin.x < 0 || origin.x >= this->size.x || origin.y < 0 || origin.y >= this->size.y || origin.z < 0 || origin.z >= this->size.z) { std::cerr << __func__ << " Bad origin: {" << origin.x << "," << origin.y << "," << origin.z << "}\n"; return path; } if (destination.x < 0 || destination.x >= this->size.x || destination.y < 0 || destination.y >= this->size.y || destination.z < 0 || destination.z >= this->size.z) { std::cerr << __func__ << " Bad destination: {" << destination.x << "," << destination.y << "," << destination.z << "}\n"; return path; } path.push_back(&this->tiles[origin.z][origin.y][origin.x]); if (!findNextNodeOnPath(pc, *this, path, destination, &numIterations)) { std::cerr << __func__ << " No route found from origin: {" << origin.x << "," << origin.y << "," << origin.z << "} to destination: {" << destination.x << "," << destination.y << "," << destination.z << "}\n"; path.clear(); return path; } return path; } }; //namespace OpenApoc <commit_msg>2000 iterations is still a long time... reduce to 500<commit_after>#include "tile.h" #include "framework/framework.h" namespace OpenApoc { TileMap::TileMap(Framework &fw, Vec3<int> size) : fw(fw), size(size) { tiles.resize(size.z); for (int z = 0; z < size.z; z++) { tiles[z].resize(size.y); for (int y = 0; y < size.y; y++) { tiles[z][y].reserve(size.x); for (int x = 0; x < size.x; x++) { tiles[z][y].emplace_back(*this, Vec3<int>{x,y,z}); } } } } void TileMap::update(unsigned int ticks) { //Default tilemap update calls update(ticks) on all tiles //Subclasses can optimise this if they know which tiles might be 'active' for (auto& object : this->activeObjects) object->update(ticks); } TileMap::~TileMap() { } Tile::Tile(TileMap &map, Vec3<int> position) : map(map), position(position) { } TileObject::TileObject(Tile *owningTile, Vec3<float> position, Vec3<float> size, bool visible, bool collides, std::shared_ptr<Image> sprite) : owningTile(owningTile), position(position), size(size), visible(visible), collides(collides), sprite(sprite) { } TileObject::~TileObject() { } Cubeoid<int> TileObject::getBoundingBox() { Vec3<int> p1 {(int)floor((float)position.x), (int)floor((float)position.y), (int)floor((float)position.z)}; Vec3<int> p2 {(int)ceil((float)position.x + size.x), (int)ceil((float)position.y + size.y), (int)ceil((float)position.z + size.z)}; return Cubeoid<int>{p1,p2}; } Vec3<float> TileObject::getSize() { return this->size; } Vec3<float> TileObject::getPosition() { return this->position; } Image& TileObject::getSprite() { return *this->sprite; } TileObjectCollisionVoxels& TileObject::getCollisionVoxels() { return this->collisionVoxels; } class PathComparer { public: Vec3<float> dest; Vec3<float> origin; PathComparer(Vec3<int> d) : dest{d.x, d.y, d.z}{} bool operator() (Tile* t1, Tile* t2) { Vec3<float> t1Pos {t1->position.x, t1->position.y, t1->position.z}; Vec3<float> t2Pos {t2->position.x, t2->position.y, t2->position.z}; Vec3<float> t1tod = dest - t1Pos; Vec3<float> t2tod = dest - t2Pos; float t1cost = glm::length(t1tod); float t2cost = glm::length(t2tod); t1cost += glm::length(t1Pos-origin); t2cost += glm::length(t2Pos-origin); return (t1cost < t2cost); } }; #define THRESHOLD_ITERATIONS 500 static bool findNextNodeOnPath(PathComparer &comparer, TileMap &map, std::list<Tile*> &currentPath, Vec3<int> destination, volatile unsigned long *numIterations) { if (currentPath.back()->position == destination) return true; if (*numIterations > THRESHOLD_ITERATIONS) return false; *numIterations = (*numIterations)+1; std::vector<Tile*> fringe; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { Vec3<int> currentPosition = currentPath.back()->position; if (z == 0 && y == 0 && x == 0) continue; Vec3<int> nextPosition = currentPosition; nextPosition.x += x; nextPosition.y += y; nextPosition.z += z; if (nextPosition.z < 0 || nextPosition.z >= map.size.z || nextPosition.y < 0 || nextPosition.y >= map.size.y || nextPosition.x < 0 || nextPosition.x >= map.size.x) continue; Tile *tile = &map.tiles[nextPosition.z][nextPosition.y][nextPosition.x]; //FIXME: Make 'blocked' tiles cleverer (e.g. don't plan around objects that will move anyway?) if (!tile->objects.empty()) continue; //Already visited this tile if (std::find(currentPath.begin(), currentPath.end(), tile) != currentPath.end()) continue; fringe.push_back(tile); } } } std::sort(fringe.begin(), fringe.end(), comparer); for (auto tile : fringe) { currentPath.push_back(tile); comparer.origin = {tile->position.x, tile->position.y, tile->position.z}; if (findNextNodeOnPath(comparer, map, currentPath, destination, numIterations)) return true; currentPath.pop_back(); } return false; } std::list<Tile*> TileMap::findShortestPath(Vec3<int> origin, Vec3<int> destination) { volatile unsigned long numIterations = 0; std::list<Tile*> path; PathComparer pc(destination); if (origin.x < 0 || origin.x >= this->size.x || origin.y < 0 || origin.y >= this->size.y || origin.z < 0 || origin.z >= this->size.z) { std::cerr << __func__ << " Bad origin: {" << origin.x << "," << origin.y << "," << origin.z << "}\n"; return path; } if (destination.x < 0 || destination.x >= this->size.x || destination.y < 0 || destination.y >= this->size.y || destination.z < 0 || destination.z >= this->size.z) { std::cerr << __func__ << " Bad destination: {" << destination.x << "," << destination.y << "," << destination.z << "}\n"; return path; } path.push_back(&this->tiles[origin.z][origin.y][origin.x]); if (!findNextNodeOnPath(pc, *this, path, destination, &numIterations)) { std::cerr << __func__ << " No route found from origin: {" << origin.x << "," << origin.y << "," << origin.z << "} to destination: {" << destination.x << "," << destination.y << "," << destination.z << "}\n"; path.clear(); return path; } return path; } }; //namespace OpenApoc <|endoftext|>
<commit_before>// Copyright (c) 2007-2010 Paul Hodge. All rights reserved. #include "evaluation.h" #include "circa.h" #include "importing_macros.h" namespace circa { namespace subroutine_t { void format_source(StyledSource* source, Term* term) { append_phrase(source, "def ", term, token::DEF); function_t::format_header_source(source, term); append_phrase(source, term->stringPropOptional("syntax:postHeadingWs", "\n"), term, token::WHITESPACE); if (!is_native_function(term)) format_branch_source(source, term->nestedContents, term); } CA_FUNCTION(evaluate) { EvalContext context; Term* function = FUNCTION; Branch& functionBranch = function->nestedContents; // Copy inputs to a new stack List stack; stack.resize(NUM_INPUTS); for (int i=0; i < NUM_INPUTS; i++) { TaggedValue* input = INPUT(i); if (input != NULL) { Term* inputTypeTerm = function_t::get_input_type(function, i); Type* inputType = type_contents(inputTypeTerm); cast(inputType, input, stack.get(i)); } } if (!functionBranch._bytecode.inuse) bytecode::update_bytecode(functionBranch); evaluate_bytecode(&context, &functionBranch._bytecode, &stack); if (OUTPUT != NULL) { swap(&context.subroutineOutput, OUTPUT); } // Copy state (if any) if (is_function_stateful(function)) { swap(&context.topLevelState, INPUT(0)); } } } bool is_subroutine(Term* term) { if (term->type != FUNCTION_TYPE) return false; if (term->nestedContents.length() < 1) return false; if (term->nestedContents[0]->type != FUNCTION_ATTRS_TYPE) return false; return function_t::get_evaluate(term) == subroutine_t::evaluate; } void finish_building_subroutine(Term* sub, Term* outputType) { // Install evaluate function function_t::get_evaluate(sub) = subroutine_t::evaluate; subroutine_update_state_type_from_contents(sub); } void subroutine_update_state_type_from_contents(Term* func) { // Check if a stateful argument was declared Term* firstInput = function_t::get_input_placeholder(func, 0); if (firstInput != NULL && firstInput->boolPropOptional("state", false)) { // already updated state return; } bool hasState = false; Branch& contents = func->nestedContents; for (int i=0; i < contents.length(); i++) { if (contents[i] == NULL) continue; if (is_get_state(contents[i])) { hasState = true; break; } if (is_subroutine(contents[i]->function)) { if (is_function_stateful(contents[i]->function)) { hasState = true; break; } } } if (hasState) subroutine_change_state_type(func, LIST_TYPE); } void subroutine_change_state_type(Term* func, Term* newType) { Term* previousType = function_t::get_inline_state_type(func); if (previousType == newType) return; Branch& contents = func->nestedContents; function_t::get_attrs(func).implicitStateType = newType; bool hasStateInput = (function_t::num_inputs(func) > 0) && (function_t::get_input_name(func, 0) == "#state"); // create a stateful input if needed if (newType != VOID_TYPE && !hasStateInput) { contents.insert(1, alloc_term()); rewrite(contents[1], INPUT_PLACEHOLDER_FUNC, RefList()); contents.bindName(contents[1], "#state"); } // If state was added, find all the recursive calls to this function and // insert a state argument. if (previousType == VOID_TYPE && newType != VOID_TYPE) { for (BranchIterator it(contents); !it.finished(); ++it) { Term* term = *it; if (term->function == func) { Branch* branch = term->owningBranch; Term* stateType = function_t::get_inline_state_type(func); std::string name = default_name_for_hidden_state(term->name); Term* stateContainer = create_stateful_value(*branch, stateType, NULL, name); branch->move(stateContainer, term->index); RefList inputs = term->inputs; inputs.prepend(stateContainer); set_inputs(term, inputs); // We just inserted a term, so the next iteration will hit the // term we just checked. So, advance past this. ++it; } } } } void store_locals(Branch& branch, TaggedValue* storageTv) { touch(storageTv); make_list(storageTv); List* storage = List::checkCast(storageTv); storage->resize(branch.length()); for (int i=0; i < branch.length(); i++) { Term* term = branch[i]; if (term == NULL) continue; if (term->type == FUNCTION_ATTRS_TYPE) continue; if (is_branch(term)) store_locals(term->nestedContents, storage->get(i)); else copy(term, storage->get(i)); } } void restore_locals(TaggedValue* storageTv, Branch& branch) { if (!list_t::is_list(storageTv)) internal_error("storageTv is not a list"); List* storage = List::checkCast(storageTv); // The function branch may be longer than our list of locals. int numItems = storage->length(); for (int i=0; i < numItems; i++) { Term* term = branch[i]; if (term == NULL) continue; if (term->type == FUNCTION_ATTRS_TYPE) continue; if (is_branch(term)) restore_locals(storage->get(i), term->nestedContents); else copy(storage->get(i), term); } } } // namespace circa <commit_msg>Fix interpreted subroutine eval<commit_after>// Copyright (c) 2007-2010 Paul Hodge. All rights reserved. #include "evaluation.h" #include "circa.h" #include "importing_macros.h" namespace circa { namespace subroutine_t { void format_source(StyledSource* source, Term* term) { append_phrase(source, "def ", term, token::DEF); function_t::format_header_source(source, term); append_phrase(source, term->stringPropOptional("syntax:postHeadingWs", "\n"), term, token::WHITESPACE); if (!is_native_function(term)) format_branch_source(source, term->nestedContents, term); } CA_FUNCTION(evaluate) { Term* function = FUNCTION; Branch& contents = function->nestedContents; List* frame = push_stack_frame(STACK, contents.registerCount); // Copy inputs to stack frame for (int i=0; i < NUM_INPUTS; i++) { TaggedValue* input = INPUT(i); if (input == NULL) continue; Term* inputTypeTerm = function_t::get_input_type(function, i); Type* inputType = type_contents(inputTypeTerm); cast(inputType, input, frame->get(i)); } // Evaluate each term evaluate_branch_existing_frame(CONTEXT, STACK, contents); frame = get_stack_frame(STACK, 0); TaggedValue output; if (frame->length() > 0) swap(frame->get(frame->length() - 1), &output); pop_stack_frame(STACK); if (OUTPUT != NULL) { swap(&output, OUTPUT); } #if 0 EvalContext context; Term* function = FUNCTION; Branch& functionBranch = function->nestedContents; // Copy inputs to a new stack List stack; stack.resize(NUM_INPUTS); for (int i=0; i < NUM_INPUTS; i++) { TaggedValue* input = INPUT(i); if (input != NULL) { Term* inputTypeTerm = function_t::get_input_type(function, i); Type* inputType = type_contents(inputTypeTerm); cast(inputType, input, stack.get(i)); } } if (!functionBranch._bytecode.inuse) bytecode::update_bytecode(functionBranch); evaluate_bytecode(&context, &functionBranch._bytecode, &stack); if (OUTPUT != NULL) { swap(&context.subroutineOutput, OUTPUT); } // Copy state (if any) if (is_function_stateful(function)) { swap(&context.topLevelState, INPUT(0)); } #endif } } bool is_subroutine(Term* term) { if (term->type != FUNCTION_TYPE) return false; if (term->nestedContents.length() < 1) return false; if (term->nestedContents[0]->type != FUNCTION_ATTRS_TYPE) return false; return function_t::get_evaluate(term) == subroutine_t::evaluate; } void finish_building_subroutine(Term* sub, Term* outputType) { // Install evaluate function function_t::get_evaluate(sub) = subroutine_t::evaluate; subroutine_update_state_type_from_contents(sub); } void subroutine_update_state_type_from_contents(Term* func) { // Check if a stateful argument was declared Term* firstInput = function_t::get_input_placeholder(func, 0); if (firstInput != NULL && firstInput->boolPropOptional("state", false)) { // already updated state return; } bool hasState = false; Branch& contents = func->nestedContents; for (int i=0; i < contents.length(); i++) { if (contents[i] == NULL) continue; if (is_get_state(contents[i])) { hasState = true; break; } if (is_subroutine(contents[i]->function)) { if (is_function_stateful(contents[i]->function)) { hasState = true; break; } } } if (hasState) subroutine_change_state_type(func, LIST_TYPE); } void subroutine_change_state_type(Term* func, Term* newType) { Term* previousType = function_t::get_inline_state_type(func); if (previousType == newType) return; Branch& contents = func->nestedContents; function_t::get_attrs(func).implicitStateType = newType; bool hasStateInput = (function_t::num_inputs(func) > 0) && (function_t::get_input_name(func, 0) == "#state"); // create a stateful input if needed if (newType != VOID_TYPE && !hasStateInput) { contents.insert(1, alloc_term()); rewrite(contents[1], INPUT_PLACEHOLDER_FUNC, RefList()); contents.bindName(contents[1], "#state"); } // If state was added, find all the recursive calls to this function and // insert a state argument. if (previousType == VOID_TYPE && newType != VOID_TYPE) { for (BranchIterator it(contents); !it.finished(); ++it) { Term* term = *it; if (term->function == func) { Branch* branch = term->owningBranch; Term* stateType = function_t::get_inline_state_type(func); std::string name = default_name_for_hidden_state(term->name); Term* stateContainer = create_stateful_value(*branch, stateType, NULL, name); branch->move(stateContainer, term->index); RefList inputs = term->inputs; inputs.prepend(stateContainer); set_inputs(term, inputs); // We just inserted a term, so the next iteration will hit the // term we just checked. So, advance past this. ++it; } } } } void store_locals(Branch& branch, TaggedValue* storageTv) { touch(storageTv); make_list(storageTv); List* storage = List::checkCast(storageTv); storage->resize(branch.length()); for (int i=0; i < branch.length(); i++) { Term* term = branch[i]; if (term == NULL) continue; if (term->type == FUNCTION_ATTRS_TYPE) continue; if (is_branch(term)) store_locals(term->nestedContents, storage->get(i)); else copy(term, storage->get(i)); } } void restore_locals(TaggedValue* storageTv, Branch& branch) { if (!list_t::is_list(storageTv)) internal_error("storageTv is not a list"); List* storage = List::checkCast(storageTv); // The function branch may be longer than our list of locals. int numItems = storage->length(); for (int i=0; i < numItems; i++) { Term* term = branch[i]; if (term == NULL) continue; if (term->type == FUNCTION_ATTRS_TYPE) continue; if (is_branch(term)) restore_locals(storage->get(i), term->nestedContents); else copy(storage->get(i), term); } } } // namespace circa <|endoftext|>
<commit_before>/* * DSA * (C) 1999-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/dsa.h> #include <botan/numthry.h> #include <botan/keypair.h> #include <stdio.h> namespace Botan { /* * DSA_PublicKey Constructor */ DSA_PublicKey::DSA_PublicKey(const DL_Group& grp, const BigInt& y1) { group = grp; y = y1; } /* * Create a DSA private key */ DSA_PrivateKey::DSA_PrivateKey(RandomNumberGenerator& rng, const DL_Group& grp, const BigInt& x_arg) { group = grp; x = x_arg; if(x == 0) x = BigInt::random_integer(rng, 2, group_q() - 1); y = power_mod(group_g(), x, group_p()); if(x_arg == 0) gen_check(rng); else load_check(rng); } DSA_PrivateKey::DSA_PrivateKey(const AlgorithmIdentifier& alg_id, const MemoryRegion<byte>& key_bits, RandomNumberGenerator& rng) : DL_Scheme_PrivateKey(alg_id, key_bits, DL_Group::ANSI_X9_57) { y = power_mod(group_g(), x, group_p()); load_check(rng); } /* * Check Private DSA Parameters */ bool DSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const { if(!DL_Scheme_PrivateKey::check_key(rng, strong) || x >= group_q()) return false; if(!strong) return true; try { PK_Signer this_signer(*this, "EMSA1(SHA-1)"); PK_Verifier this_verifier(*this, "EMSA1(SHA-1)"); KeyPair::check_key(rng, this_signer, this_verifier); } catch(Self_Test_Failure) { return false; } return true; } DSA_Signature_Operation::DSA_Signature_Operation(const DSA_PrivateKey& dsa) : q(dsa.group_q()), x(dsa.get_x()), powermod_g_p(dsa.group_g(), dsa.group_p()), mod_q(dsa.group_q()) { } SecureVector<byte> DSA_Signature_Operation::sign(const byte msg[], u32bit msg_len, RandomNumberGenerator& rng) { rng.add_entropy(msg, msg_len); BigInt i(msg, msg_len); BigInt r = 0, s = 0; while(r == 0 || s == 0) { BigInt k; do k.randomize(rng, q.bits()); while(k >= q); r = mod_q.reduce(powermod_g_p(k)); s = mod_q.multiply(inverse_mod(k, q), mul_add(x, r, i)); } SecureVector<byte> output(2*q.bytes()); r.binary_encode(output + (output.size() / 2 - r.bytes())); s.binary_encode(output + (output.size() - s.bytes())); return output; } DSA_Verification_Operation::DSA_Verification_Operation(const DSA_PublicKey& dsa) : q(dsa.group_q()), y(dsa.get_y()) { powermod_g_p = Fixed_Base_Power_Mod(dsa.group_g(), dsa.group_p()); powermod_y_p = Fixed_Base_Power_Mod(y, dsa.group_p()); mod_p = Modular_Reducer(dsa.group_p()); mod_q = Modular_Reducer(dsa.group_q()); } bool DSA_Verification_Operation::verify(const byte msg[], u32bit msg_len, const byte sig[], u32bit sig_len) { const BigInt& q = mod_q.get_modulus(); if(sig_len != 2*q.bytes() || msg_len > q.bytes()) return false; BigInt r(sig, q.bytes()); BigInt s(sig + q.bytes(), q.bytes()); BigInt i(msg, msg_len); if(r <= 0 || r >= q || s <= 0 || s >= q) return false; s = inverse_mod(s, q); s = mod_p.multiply(powermod_g_p(mod_q.multiply(s, i)), powermod_y_p(mod_q.multiply(s, r))); return (mod_q.reduce(s) == r); } } <commit_msg>Remove stdio include<commit_after>/* * DSA * (C) 1999-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/dsa.h> #include <botan/numthry.h> #include <botan/keypair.h> namespace Botan { /* * DSA_PublicKey Constructor */ DSA_PublicKey::DSA_PublicKey(const DL_Group& grp, const BigInt& y1) { group = grp; y = y1; } /* * Create a DSA private key */ DSA_PrivateKey::DSA_PrivateKey(RandomNumberGenerator& rng, const DL_Group& grp, const BigInt& x_arg) { group = grp; x = x_arg; if(x == 0) x = BigInt::random_integer(rng, 2, group_q() - 1); y = power_mod(group_g(), x, group_p()); if(x_arg == 0) gen_check(rng); else load_check(rng); } DSA_PrivateKey::DSA_PrivateKey(const AlgorithmIdentifier& alg_id, const MemoryRegion<byte>& key_bits, RandomNumberGenerator& rng) : DL_Scheme_PrivateKey(alg_id, key_bits, DL_Group::ANSI_X9_57) { y = power_mod(group_g(), x, group_p()); load_check(rng); } /* * Check Private DSA Parameters */ bool DSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const { if(!DL_Scheme_PrivateKey::check_key(rng, strong) || x >= group_q()) return false; if(!strong) return true; try { PK_Signer this_signer(*this, "EMSA1(SHA-1)"); PK_Verifier this_verifier(*this, "EMSA1(SHA-1)"); KeyPair::check_key(rng, this_signer, this_verifier); } catch(Self_Test_Failure) { return false; } return true; } DSA_Signature_Operation::DSA_Signature_Operation(const DSA_PrivateKey& dsa) : q(dsa.group_q()), x(dsa.get_x()), powermod_g_p(dsa.group_g(), dsa.group_p()), mod_q(dsa.group_q()) { } SecureVector<byte> DSA_Signature_Operation::sign(const byte msg[], u32bit msg_len, RandomNumberGenerator& rng) { rng.add_entropy(msg, msg_len); BigInt i(msg, msg_len); BigInt r = 0, s = 0; while(r == 0 || s == 0) { BigInt k; do k.randomize(rng, q.bits()); while(k >= q); r = mod_q.reduce(powermod_g_p(k)); s = mod_q.multiply(inverse_mod(k, q), mul_add(x, r, i)); } SecureVector<byte> output(2*q.bytes()); r.binary_encode(output + (output.size() / 2 - r.bytes())); s.binary_encode(output + (output.size() - s.bytes())); return output; } DSA_Verification_Operation::DSA_Verification_Operation(const DSA_PublicKey& dsa) : q(dsa.group_q()), y(dsa.get_y()) { powermod_g_p = Fixed_Base_Power_Mod(dsa.group_g(), dsa.group_p()); powermod_y_p = Fixed_Base_Power_Mod(y, dsa.group_p()); mod_p = Modular_Reducer(dsa.group_p()); mod_q = Modular_Reducer(dsa.group_q()); } bool DSA_Verification_Operation::verify(const byte msg[], u32bit msg_len, const byte sig[], u32bit sig_len) { const BigInt& q = mod_q.get_modulus(); if(sig_len != 2*q.bytes() || msg_len > q.bytes()) return false; BigInt r(sig, q.bytes()); BigInt s(sig + q.bytes(), q.bytes()); BigInt i(msg, msg_len); if(r <= 0 || r >= q || s <= 0 || s >= q) return false; s = inverse_mod(s, q); s = mod_p.multiply(powermod_g_p(mod_q.multiply(s, i)), powermod_y_p(mod_q.multiply(s, r))); return (mod_q.reduce(s) == r); } } <|endoftext|>
<commit_before>/* * File: dom.hpp * Author: ivan * * Created on October 8, 2015, 3:15 PM */ #pragma once #include <vector> #include <memory> #include <ostream> #include <map> #include <utki/Unique.hpp> #include <utki/Void.hpp> #include <papki/File.hpp> #include "config.hpp" namespace svgdom{ struct Length{ enum class EUnit{ UNKNOWN, NUMBER, PERCENT, EM, EX, PX, CM, IN, PT, PC }; real value; EUnit unit; static Length parse(const std::string& str); static Length make(real value, EUnit unit); }; class Renderer; struct Container; struct Element; enum class EStyleProperty{ UNKNOWN, FONT, FONT_FAMILY, FONT_SIZE, FONT_SIZE_ADJUST, FONT_STRETCH, FONT_STYLE, FONT_VARIANT, FONT_WEIGHT, DIRECTION, LETTER_SPACING, TEXT_DECORATION, UNICODE_BIDI, WORD_SPACING, CLIP, COLOR, CURSOR, DISPLAY, OVERFLOW, VISIBILITY, CLIP_PATH, CLIP_RULE, MASK, OPACITY, ENABLE_BACKGROUND, FILTER, FLOOD_COLOR, FLOOD_OPACITY, LIGHTING_COLOR, STOP_COLOR, STOP_OPACITY, POINTER_EVENTS, COLOR_INTERPOLATION, COLOR_INTERPOLATION_FILTERS, COLOR_PROFILE, COLOR_RENDERING, FILL, FILL_OPACITY, FILL_RULE, IMAGE_RENDERING, MARKER, MARKER_END, MARKER_MID, MARKER_START, SHAPE_RENDERING, STROKE, STROKE_DASHARRAY, STROKE_DASHOFFSET, STROKE_LINECAP, STROKE_LINEJOIN, STROKE_MITERLIMIT, STROKE_OPACITY, STROKE_WIDTH, TEXT_RENDERING, ALIGNMENT_BASELINE, BASELINE_SHIFT, DOMINANT_BASELINE, GLYPH_ORIENTATION_HORIZONTAL, GLYPH_ORIENTATION_VERTICAL, KERNING, TEXT_ANCHOR, WRITING_MODE }; struct Rgb{ real r, g, b; }; enum class EStrokeLineCap{ BUTT, ROUND, SQUARE }; struct StylePropertyValue{ enum class ERule{ NORMAL, NONE, INHERIT, URL } rule = ERule::NORMAL; bool isNormal()const noexcept{ return this->rule == ERule::NORMAL; } bool isNone()const noexcept{ return this->rule == ERule::NONE; } bool isUrl()const noexcept{ return this->rule == ERule::URL; } union{ std::uint32_t color; real opacity; Length length; EStrokeLineCap strokeLineCap; Element* url; }; std::string str; static StylePropertyValue parsePaint(const std::string& str); std::string paintToString()const; Rgb getRgb()const; }; struct Element : public utki::Unique{ Container* parent; std::string id; virtual ~Element()noexcept{} void attribsToStream(std::ostream& s)const; virtual void toStream(std::ostream& s, unsigned indent = 0)const = 0; std::string toString()const; virtual void render(Renderer& renderer)const{} const StylePropertyValue* getStyleProperty(EStyleProperty property, bool explicitInherit = false)const; virtual Element* findById(const std::string& elementId); }; struct Container : public Element{ std::vector<std::unique_ptr<Element>> children; void childrenToStream(std::ostream& s, unsigned indent)const; void render(Renderer& renderer)const; Element* findById(const std::string& elementId) override; }; struct Referencing{ Element* ref = nullptr; std::string iri; void attribsToStream(std::ostream& s)const; }; struct Transformable{ struct Transformation{ enum class EType{ MATRIX, TRANSLATE, SCALE, ROTATE, SKEWX, SKEWY } type; union{ real a; real angle; }; union{ real b; real x; }; union{ real c; real y; }; real d, e, f; }; std::vector<Transformation> transformations; void attribsToStream(std::ostream& s)const; static decltype(Transformable::transformations) parse(const std::string& str); }; struct Styleable{ std::map<EStyleProperty, StylePropertyValue> styles; void attribsToStream(std::ostream& s)const; static decltype(styles) parse(const std::string& str); static std::string propertyToString(EStyleProperty p); static EStyleProperty stringToProperty(std::string str); }; struct GElement : public Container, public Transformable, public Styleable{ void toStream(std::ostream& s, unsigned indent = 0)const override; void render(Renderer& renderer)const override; }; struct DefsElement : public Container, public Transformable, public Styleable{ void toStream(std::ostream& s, unsigned indent = 0)const override; }; struct Rectangle{ Length x = Length::make(0, Length::EUnit::PERCENT); Length y = Length::make(0, Length::EUnit::PERCENT); Length width = Length::make(100, Length::EUnit::PERCENT); Length height = Length::make(100, Length::EUnit::PERCENT); void attribsToStream(std::ostream& s)const; }; struct SvgElement : public Container, public Rectangle{ void toStream(std::ostream& s, unsigned indent = 0)const override; void render(Renderer& renderer) const override; }; struct Shape : public Element, public Styleable, public Transformable{ void attribsToStream(std::ostream& s)const; }; struct PathElement : public Shape{ struct Step{ enum class EType{ UNKNOWN, CLOSE, MOVE_ABS, MOVE_REL, LINE_ABS, LINE_REL, HORIZONTAL_LINE_ABS, HORIZONTAL_LINE_REL, VERTICAL_LINE_ABS, VERTICAL_LINE_REL, CUBIC_ABS, CUBIC_REL, CUBIC_SMOOTH_ABS, CUBIC_SMOOTH_REL, QUADRATIC_ABS, QUADRATIC_REL, QUADRATIC_SMOOTH_ABS, QUADRATIC_SMOOTH_REL, ARC_ABS, ARC_REL } type; real x, y; union{ real x1; real rx; }; union{ real y1; real ry; }; union{ real x2; real xAxisRotation; }; union{ real y2; struct{ bool largeArc; bool sweep; } flags; }; static EType charToType(char c); static char typeToChar(EType t); }; std::vector<Step> path; void attribsToStream(std::ostream& s)const; void toStream(std::ostream& s, unsigned indent = 0)const override; static decltype(path) parse(const std::string& str); void render(Renderer& renderer) const override; }; struct RectElement : public Shape, public Rectangle{ Length rx = Length::make(0, Length::EUnit::UNKNOWN); Length ry = Length::make(0, Length::EUnit::UNKNOWN); void attribsToStream(std::ostream& s)const; void toStream(std::ostream& s, unsigned indent) const override; void render(Renderer& renderer) const override; }; struct Gradient : public Container, public Referencing, public Styleable{ enum class ESpreadMethod{ DEFAULT, PAD, REFLECT, REPEAT } spreadMethod = ESpreadMethod::DEFAULT; static std::string spreadMethodToString(ESpreadMethod sm); static ESpreadMethod stringToSpreadMethod(const std::string& str); ESpreadMethod getSpreadMethod()const noexcept; struct StopElement : public Styleable, public Element{ real offset; void toStream(std::ostream& s, unsigned indent)const override; }; const decltype(Container::children)& getStops()const noexcept; void attribsToStream(std::ostream& s)const; }; struct LinearGradientElement : public Gradient{ Length x1 = Length::make(0, Length::EUnit::UNKNOWN); Length y1 = Length::make(0, Length::EUnit::UNKNOWN); Length x2 = Length::make(100, Length::EUnit::UNKNOWN); Length y2 = Length::make(0, Length::EUnit::UNKNOWN); Length getX1()const noexcept; Length getY1()const noexcept; Length getX2()const noexcept; Length getY2()const noexcept; void toStream(std::ostream& s, unsigned indent) const override; }; struct RadialGradientElement : public Gradient{ Length cx = Length::make(50, Length::EUnit::UNKNOWN); Length cy = Length::make(50, Length::EUnit::UNKNOWN); Length r = Length::make(50, Length::EUnit::UNKNOWN); Length fx = Length::make(50, Length::EUnit::UNKNOWN); Length fy = Length::make(50, Length::EUnit::UNKNOWN); Length getCx()const noexcept; Length getCy()const noexcept; Length getR()const noexcept; Length getFx()const noexcept; Length getFy()const noexcept; void toStream(std::ostream& s, unsigned indent) const override; }; class Renderer{ public: virtual void render(const PathElement& e){} virtual void render(const RectElement& e){} virtual void render(const GElement& e){} virtual void render(const SvgElement& e){} virtual ~Renderer()noexcept{} }; std::unique_ptr<SvgElement> load(const papki::File& f); }//~namespace std::ostream& operator<<(std::ostream& s, const svgdom::Length& l); <commit_msg>stuff<commit_after>/* * File: dom.hpp * Author: ivan * * Created on October 8, 2015, 3:15 PM */ #pragma once #include <vector> #include <memory> #include <ostream> #include <map> #include <utki/Unique.hpp> #include <utki/Void.hpp> #include <papki/File.hpp> #include "config.hpp" namespace svgdom{ struct Length{ enum class EUnit{ UNKNOWN, NUMBER, PERCENT, EM, EX, PX, CM, IN, PT, PC }; real value; EUnit unit; static Length parse(const std::string& str); static Length make(real value, EUnit unit); }; class Renderer; struct Container; struct Element; enum class EStyleProperty{ UNKNOWN, FONT, FONT_FAMILY, FONT_SIZE, FONT_SIZE_ADJUST, FONT_STRETCH, FONT_STYLE, FONT_VARIANT, FONT_WEIGHT, DIRECTION, LETTER_SPACING, TEXT_DECORATION, UNICODE_BIDI, WORD_SPACING, CLIP, COLOR, CURSOR, DISPLAY, OVERFLOW, VISIBILITY, CLIP_PATH, CLIP_RULE, MASK, OPACITY, ENABLE_BACKGROUND, FILTER, FLOOD_COLOR, FLOOD_OPACITY, LIGHTING_COLOR, STOP_COLOR, STOP_OPACITY, POINTER_EVENTS, COLOR_INTERPOLATION, COLOR_INTERPOLATION_FILTERS, COLOR_PROFILE, COLOR_RENDERING, FILL, FILL_OPACITY, FILL_RULE, IMAGE_RENDERING, MARKER, MARKER_END, MARKER_MID, MARKER_START, SHAPE_RENDERING, STROKE, STROKE_DASHARRAY, STROKE_DASHOFFSET, STROKE_LINECAP, STROKE_LINEJOIN, STROKE_MITERLIMIT, STROKE_OPACITY, STROKE_WIDTH, TEXT_RENDERING, ALIGNMENT_BASELINE, BASELINE_SHIFT, DOMINANT_BASELINE, GLYPH_ORIENTATION_HORIZONTAL, GLYPH_ORIENTATION_VERTICAL, KERNING, TEXT_ANCHOR, WRITING_MODE }; struct Rgb{ real r, g, b; }; enum class EStrokeLineCap{ BUTT, ROUND, SQUARE }; struct StylePropertyValue{ enum class ERule{ NORMAL, NONE, //for color property (e.g. fill, stroke, etc.) means that color is 'none' INHERIT, //means that property inheritance was explicitly stated URL //means that "str" member holds URL } rule = ERule::NORMAL; bool isNormal()const noexcept{ return this->rule == ERule::NORMAL; } bool isNone()const noexcept{ return this->rule == ERule::NONE; } bool isUrl()const noexcept{ return this->rule == ERule::URL; } union{ std::uint32_t color; real opacity; Length length; EStrokeLineCap strokeLineCap; Element* url; //used if rule is URL }; std::string str; static StylePropertyValue parsePaint(const std::string& str); std::string paintToString()const; Rgb getRgb()const; }; struct Element : public utki::Unique{ Container* parent; std::string id; virtual ~Element()noexcept{} void attribsToStream(std::ostream& s)const; virtual void toStream(std::ostream& s, unsigned indent = 0)const = 0; std::string toString()const; virtual void render(Renderer& renderer)const{} const StylePropertyValue* getStyleProperty(EStyleProperty property, bool explicitInherit = false)const; virtual Element* findById(const std::string& elementId); }; struct Container : public Element{ std::vector<std::unique_ptr<Element>> children; void childrenToStream(std::ostream& s, unsigned indent)const; void render(Renderer& renderer)const; Element* findById(const std::string& elementId) override; }; struct Referencing{ Element* ref = nullptr; std::string iri; void attribsToStream(std::ostream& s)const; }; struct Transformable{ struct Transformation{ enum class EType{ MATRIX, TRANSLATE, SCALE, ROTATE, SKEWX, SKEWY } type; union{ real a; real angle; }; union{ real b; real x; }; union{ real c; real y; }; real d, e, f; }; std::vector<Transformation> transformations; void attribsToStream(std::ostream& s)const; static decltype(Transformable::transformations) parse(const std::string& str); }; struct Styleable{ std::map<EStyleProperty, StylePropertyValue> styles; void attribsToStream(std::ostream& s)const; static decltype(styles) parse(const std::string& str); static std::string propertyToString(EStyleProperty p); static EStyleProperty stringToProperty(std::string str); }; struct GElement : public Container, public Transformable, public Styleable{ void toStream(std::ostream& s, unsigned indent = 0)const override; void render(Renderer& renderer)const override; }; struct DefsElement : public Container, public Transformable, public Styleable{ void toStream(std::ostream& s, unsigned indent = 0)const override; }; struct Rectangle{ Length x = Length::make(0, Length::EUnit::PERCENT); Length y = Length::make(0, Length::EUnit::PERCENT); Length width = Length::make(100, Length::EUnit::PERCENT); Length height = Length::make(100, Length::EUnit::PERCENT); void attribsToStream(std::ostream& s)const; }; struct SvgElement : public Container, public Rectangle{ void toStream(std::ostream& s, unsigned indent = 0)const override; void render(Renderer& renderer) const override; }; struct Shape : public Element, public Styleable, public Transformable{ void attribsToStream(std::ostream& s)const; }; struct PathElement : public Shape{ struct Step{ enum class EType{ UNKNOWN, CLOSE, MOVE_ABS, MOVE_REL, LINE_ABS, LINE_REL, HORIZONTAL_LINE_ABS, HORIZONTAL_LINE_REL, VERTICAL_LINE_ABS, VERTICAL_LINE_REL, CUBIC_ABS, CUBIC_REL, CUBIC_SMOOTH_ABS, CUBIC_SMOOTH_REL, QUADRATIC_ABS, QUADRATIC_REL, QUADRATIC_SMOOTH_ABS, QUADRATIC_SMOOTH_REL, ARC_ABS, ARC_REL } type; real x, y; union{ real x1; real rx; }; union{ real y1; real ry; }; union{ real x2; real xAxisRotation; }; union{ real y2; struct{ bool largeArc; bool sweep; } flags; }; static EType charToType(char c); static char typeToChar(EType t); }; std::vector<Step> path; void attribsToStream(std::ostream& s)const; void toStream(std::ostream& s, unsigned indent = 0)const override; static decltype(path) parse(const std::string& str); void render(Renderer& renderer) const override; }; struct RectElement : public Shape, public Rectangle{ Length rx = Length::make(0, Length::EUnit::UNKNOWN); Length ry = Length::make(0, Length::EUnit::UNKNOWN); void attribsToStream(std::ostream& s)const; void toStream(std::ostream& s, unsigned indent) const override; void render(Renderer& renderer) const override; }; struct Gradient : public Container, public Referencing, public Styleable{ enum class ESpreadMethod{ DEFAULT, PAD, REFLECT, REPEAT } spreadMethod = ESpreadMethod::DEFAULT; static std::string spreadMethodToString(ESpreadMethod sm); static ESpreadMethod stringToSpreadMethod(const std::string& str); ESpreadMethod getSpreadMethod()const noexcept; struct StopElement : public Styleable, public Element{ real offset; void toStream(std::ostream& s, unsigned indent)const override; }; const decltype(Container::children)& getStops()const noexcept; void attribsToStream(std::ostream& s)const; }; struct LinearGradientElement : public Gradient{ Length x1 = Length::make(0, Length::EUnit::UNKNOWN); Length y1 = Length::make(0, Length::EUnit::UNKNOWN); Length x2 = Length::make(100, Length::EUnit::UNKNOWN); Length y2 = Length::make(0, Length::EUnit::UNKNOWN); Length getX1()const noexcept; Length getY1()const noexcept; Length getX2()const noexcept; Length getY2()const noexcept; void toStream(std::ostream& s, unsigned indent) const override; }; struct RadialGradientElement : public Gradient{ Length cx = Length::make(50, Length::EUnit::UNKNOWN); Length cy = Length::make(50, Length::EUnit::UNKNOWN); Length r = Length::make(50, Length::EUnit::UNKNOWN); Length fx = Length::make(50, Length::EUnit::UNKNOWN); Length fy = Length::make(50, Length::EUnit::UNKNOWN); Length getCx()const noexcept; Length getCy()const noexcept; Length getR()const noexcept; Length getFx()const noexcept; Length getFy()const noexcept; void toStream(std::ostream& s, unsigned indent) const override; }; class Renderer{ public: virtual void render(const PathElement& e){} virtual void render(const RectElement& e){} virtual void render(const GElement& e){} virtual void render(const SvgElement& e){} virtual ~Renderer()noexcept{} }; std::unique_ptr<SvgElement> load(const papki::File& f); }//~namespace std::ostream& operator<<(std::ostream& s, const svgdom::Length& l); <|endoftext|>
<commit_before>/* * This file is part of the beirdobot package * Copyright (C) 2010 Gavin Hurlbut * * beirdobot is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*HEADER--------------------------------------------------- * $Id$ * * Copyright 2010 Gavin Hurlbut * All rights reserved * */ #include "environment.h" #include "clucene.h" #include <CLucene.h> #include <CLucene/config/repl_tchar.h> #include <string.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #ifndef WEBSERVICE #include "protos.h" #include "logging.h" #include "queue.h" #endif using namespace std; using namespace lucene::index; using namespace lucene::analysis; using namespace lucene::util; using namespace lucene::store; using namespace lucene::queryParser; using namespace lucene::document; using namespace lucene::search; static char ident[] _UNUSED_= "$Id$"; #define MAX_STRING_LEN 1024 #ifndef WEBSERVICE typedef struct { unsigned long id; int chanid; char *nick; char *text; unsigned long timestamp; } IndexItem_t; pthread_t cluceneThreadId; pthread_t kickerThreadId; int docmax = 0; void addLogentry( Document *doc, unsigned long *tb, IndexItem_t *item ); int loadLogentry( Document *doc, unsigned long tb ); void *clucene_thread( void *arg ); void *kicker_thread( void *arg ); IndexWriter *getWriter( int clear ); void closeWriter( IndexWriter *writer ); #endif char *clucene_escape( char *text ); /* The C interface portion */ extern "C" { #ifndef WEBSERVICE QueueObject_t *IndexQ; void clucene_init(int clear) { int *clr; clr = (int *)malloc(sizeof(int)); *clr = clear; IndexQ = QueueCreate( 1024 ); versionAdd( (char *)"CLucene", (char *)_CL_VERSION ); /* Start the threads */ thread_create( &cluceneThreadId, clucene_thread, clr, (char *)"thread_clucene", NULL ); if( !clear ) { thread_create( &kickerThreadId, kicker_thread, NULL, (char *)"thread_kicker", NULL ); } } #endif void clucene_shutdown(void) { _lucene_shutdown(); } #ifndef WEBSERVICE void clucene_add( int chanid, char *nick, char *text, unsigned long timestamp ) { IndexItem_t *item; item = (IndexItem_t *)malloc(sizeof(IndexItem_t)); memset( item, 0, sizeof(IndexItem_t) ); item->chanid = chanid; item->nick = nick ? strdup(nick) : NULL; item->text = text ? strdup(text) : NULL; item->timestamp = (timestamp / SEARCH_WINDOW); QueueEnqueueItem( IndexQ, item ); } #endif SearchResults_t *clucene_search( int chanid, char *text, int *count, int max ) { IndexReader *reader; WhitespaceAnalyzer an; IndexSearcher *s; Query *q; Hits *h; Document *d; static TCHAR query[MAX_STRING_LEN]; char *esctext; SearchResults_t *results; int i; char *ts; reader = IndexReader::open(CLUCENE_INDEX_DIR); s = _CLNEW IndexSearcher(reader); esctext = clucene_escape(text); _sntprintf( query, MAX_STRING_LEN, _T("chanid:%ld AND (text:\"%s\" OR nick:\"%s\")"), chanid, esctext, esctext ); #ifndef WEBSERVICE LogPrint(LOG_INFO, "Query: %ls", query); #endif q = QueryParser::parse(query, _T("text"), &an); h = s->search(q); if( h->length() == 0 ) { *count = 0; reader->close(); _CLDELETE(h); _CLDELETE(q); _CLDELETE(s); _CLDELETE(reader); return( NULL ); } *count = (h->length() > max ? max : h->length()); results = (SearchResults_t *)malloc(*count * sizeof(SearchResults_t)); for( i = 0; i < *count; i++ ) { d = &h->doc(i); ts = STRDUP_TtoA(d->get(_T("timestamp"))); results[i].timestamp = atoi(ts) * SEARCH_WINDOW; results[i].score = h->score(i); free( ts ); } reader->close(); _CLDELETE(h); _CLDELETE(q); _CLDELETE(s); _CLDELETE(reader); return( results ); } } /* C++ internals */ char *clucene_escape( char *text ) { static char buf[MAX_STRING_LEN]; static const char chars[] = "+-&|!(){}[]^\"~*?:\\"; int len; int i; int j; len = strlen(text); for( i = 0, j = 0; i < len && j < MAX_STRING_LEN - 1; i++ ) { if( strchr( chars, (int)text[i] ) ) { buf[j++] = '\\'; } buf[j++] = text[i]; } buf[j] = '\0'; return( buf ); } #ifndef WEBSERVICE void addLogentry( Document *doc, unsigned long *tb, IndexItem_t *item ) { static TCHAR buf[MAX_STRING_LEN]; IndexWriter *writer; if( *tb != item->timestamp ) { if( *tb != 0 ) { writer = getWriter(false); writer->addDocument( doc ); closeWriter( writer ); doc->clear(); } if( item->text == NULL ) { /* Keepalive */ *tb = 0; return; } if( !loadLogentry( doc, item->timestamp ) ) { _sntprintf( buf, MAX_STRING_LEN, _T("%ld"), item->timestamp ); doc->add( *_CLNEW Field( _T("timestamp"), buf, Field::STORE_YES | Field::INDEX_TOKENIZED ) ); _sntprintf( buf, MAX_STRING_LEN, _T("%ld"), item->chanid ); doc->add( *_CLNEW Field( _T("chanid"), buf, Field::STORE_YES | Field::INDEX_TOKENIZED ) ); } *tb = item->timestamp; } STRCPY_AtoT(buf, item->nick, MAX_STRING_LEN); doc->add( *_CLNEW Field( _T("nick"), buf, Field::STORE_YES | Field::INDEX_TOKENIZED ) ); STRCPY_AtoT(buf, item->text, MAX_STRING_LEN); doc->add( *_CLNEW Field( _T("text"), buf, Field::STORE_YES | Field::INDEX_TOKENIZED ) ); } int loadLogentry( Document *doc, unsigned long tb ) { IndexReader *reader; WhitespaceAnalyzer an; IndexSearcher *s; Query *q; Hits *h; Document *d; DocumentFieldEnumeration *fields; Field *field; static TCHAR query[80]; int len; reader = IndexReader::open(CLUCENE_INDEX_DIR); s = _CLNEW IndexSearcher(reader); _sntprintf( query, 80, _T("%ld"), tb ); q = QueryParser::parse(query, _T("timestamp"), &an); h = s->search(q); len = h->length(); #if 0 LogPrint( LOG_INFO, "Q: %ls len: %d", q->toString(), len ); #endif if( h->length() == 0 ) { reader->close(); _CLDELETE(h); _CLDELETE(q); _CLDELETE(s); _CLDELETE(reader); return( 0 ); } d = &h->doc(0); fields = d->fields(); doc->clear(); /* Recreate the current document */ while( (field = fields->nextElement()) ) { doc->add( *_CLNEW Field( field->name(), field->stringValue(), Field::STORE_YES | Field::INDEX_TOKENIZED ) ); } LogPrint( LOG_INFO, "Deleting document %lld", h->id(0) ); reader->deleteDocument( h->id(0) ); reader->close(); _CLDELETE(h); _CLDELETE(q); _CLDELETE(s); _CLDELETE(reader); return( 1 ); } IndexWriter *getWriter( int clear ) { WhitespaceAnalyzer *an; IndexWriter *writer = NULL; #if 0 LogPrintNoArg(LOG_INFO, "Opening writer"); #endif an = _CLNEW WhitespaceAnalyzer; if ( !clear && IndexReader::indexExists(CLUCENE_INDEX_DIR) ){ if ( IndexReader::isLocked(CLUCENE_INDEX_DIR) ){ LogPrintNoArg( LOG_INFO, "Index was locked... unlocking it."); IndexReader::unlock(CLUCENE_INDEX_DIR); } writer = _CLNEW IndexWriter( CLUCENE_INDEX_DIR, an, false); } else { writer = _CLNEW IndexWriter( CLUCENE_INDEX_DIR, an, true); } writer->setMaxFieldLength(1000000); return( writer ); } void closeWriter( IndexWriter *writer ) { WhitespaceAnalyzer *an; #if 0 LogPrintNoArg( LOG_INFO, "Closing Writer" ); #endif an = (WhitespaceAnalyzer *)writer->getAnalyzer(); writer->close(); _CLDELETE(an); _CLDELETE(writer); } void *kicker_thread( void *arg ) { struct timeval tv; unsigned long now; unsigned long target; int i; LogPrintNoArg( LOG_INFO, "Starting CLucene Kicker thread" ); while( !GlobalAbort ) { gettimeofday( &tv, NULL ); now = tv.tv_sec; target = ((now / SEARCH_WINDOW) + 1) * SEARCH_WINDOW; sleep( target - now ); LogPrint( LOG_INFO, "Kicking %d channel indexes", docmax ); for( i = 0; i < docmax; i++ ) { clucene_add( i + 1, NULL, NULL, target / SEARCH_WINDOW ); } } LogPrintNoArg( LOG_INFO, "Ending CLucene Kicker thread" ); return( NULL ); } void *clucene_thread( void *arg ) { IndexItem_t *item; IndexWriter *writer = NULL; Document **doc = NULL; unsigned long *lasttb = NULL; int i; int clear; clear = *(int *)arg; LogPrint(LOG_INFO, "Clear: %d", clear ); LogPrintNoArg( LOG_NOTICE, "Starting CLucene thread" ); LogPrint( LOG_INFO, "Using CLucene v%s index in %s", _CL_VERSION, CLUCENE_INDEX_DIR ); writer = getWriter(clear); LogPrint( LOG_INFO, "%ld documents indexed", (long int)writer->docCount() ); if( optimize ) { LogPrintNoArg( LOG_INFO, "Optimizing index" ); writer->optimize(); LogPrintNoArg( LOG_INFO, "Finished optimizing index" ); } closeWriter( writer ); while( !GlobalAbort ) { item = (IndexItem_t *)QueueDequeueItem( IndexQ, 1000 ); if( !item ) { continue; } if( item->chanid > docmax ) { doc = (Document **)realloc(doc, item->chanid * sizeof(Document *)); lasttb = (unsigned long *)realloc(lasttb, item->chanid * sizeof(unsigned long )); for( i = docmax; i < item->chanid; i++ ) { doc[i] = new Document; doc[i]->clear(); lasttb[i] = 0; } docmax = item->chanid; } addLogentry( doc[item->chanid - 1], &lasttb[item->chanid - 1], item ); if( item->nick ) { free( item->nick ); } if( item->text ) { free( item->text ); } free( item ); } LogPrintNoArg( LOG_NOTICE, "Ending CLucene thread" ); writer = getWriter(0); for( i = 0; i < docmax; i++ ) { if( lasttb[i] != 0 ) { writer->addDocument( doc[i] ); _CLDELETE( doc[i] ); } } closeWriter( writer ); free( lasttb ); free( doc ); return(NULL); } #endif /* * vim:ts=4:sw=4:ai:et:si:sts=4 */ <commit_msg>Make the document id in cluced be forced to 64bit<commit_after>/* * This file is part of the beirdobot package * Copyright (C) 2010 Gavin Hurlbut * * beirdobot is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*HEADER--------------------------------------------------- * $Id$ * * Copyright 2010 Gavin Hurlbut * All rights reserved * */ #include "environment.h" #include "clucene.h" #include <CLucene.h> #include <CLucene/config/repl_tchar.h> #include <string.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #ifndef WEBSERVICE #include "protos.h" #include "logging.h" #include "queue.h" #endif using namespace std; using namespace lucene::index; using namespace lucene::analysis; using namespace lucene::util; using namespace lucene::store; using namespace lucene::queryParser; using namespace lucene::document; using namespace lucene::search; static char ident[] _UNUSED_= "$Id$"; #define MAX_STRING_LEN 1024 #ifndef WEBSERVICE typedef struct { unsigned long id; int chanid; char *nick; char *text; unsigned long timestamp; } IndexItem_t; pthread_t cluceneThreadId; pthread_t kickerThreadId; int docmax = 0; void addLogentry( Document *doc, unsigned long *tb, IndexItem_t *item ); int loadLogentry( Document *doc, unsigned long tb ); void *clucene_thread( void *arg ); void *kicker_thread( void *arg ); IndexWriter *getWriter( int clear ); void closeWriter( IndexWriter *writer ); #endif char *clucene_escape( char *text ); /* The C interface portion */ extern "C" { #ifndef WEBSERVICE QueueObject_t *IndexQ; void clucene_init(int clear) { int *clr; clr = (int *)malloc(sizeof(int)); *clr = clear; IndexQ = QueueCreate( 1024 ); versionAdd( (char *)"CLucene", (char *)_CL_VERSION ); /* Start the threads */ thread_create( &cluceneThreadId, clucene_thread, clr, (char *)"thread_clucene", NULL ); if( !clear ) { thread_create( &kickerThreadId, kicker_thread, NULL, (char *)"thread_kicker", NULL ); } } #endif void clucene_shutdown(void) { _lucene_shutdown(); } #ifndef WEBSERVICE void clucene_add( int chanid, char *nick, char *text, unsigned long timestamp ) { IndexItem_t *item; item = (IndexItem_t *)malloc(sizeof(IndexItem_t)); memset( item, 0, sizeof(IndexItem_t) ); item->chanid = chanid; item->nick = nick ? strdup(nick) : NULL; item->text = text ? strdup(text) : NULL; item->timestamp = (timestamp / SEARCH_WINDOW); QueueEnqueueItem( IndexQ, item ); } #endif SearchResults_t *clucene_search( int chanid, char *text, int *count, int max ) { IndexReader *reader; WhitespaceAnalyzer an; IndexSearcher *s; Query *q; Hits *h; Document *d; static TCHAR query[MAX_STRING_LEN]; char *esctext; SearchResults_t *results; int i; char *ts; reader = IndexReader::open(CLUCENE_INDEX_DIR); s = _CLNEW IndexSearcher(reader); esctext = clucene_escape(text); _sntprintf( query, MAX_STRING_LEN, _T("chanid:%ld AND (text:\"%s\" OR nick:\"%s\")"), chanid, esctext, esctext ); #ifndef WEBSERVICE LogPrint(LOG_INFO, "Query: %ls", query); #endif q = QueryParser::parse(query, _T("text"), &an); h = s->search(q); if( h->length() == 0 ) { *count = 0; reader->close(); _CLDELETE(h); _CLDELETE(q); _CLDELETE(s); _CLDELETE(reader); return( NULL ); } *count = (h->length() > max ? max : h->length()); results = (SearchResults_t *)malloc(*count * sizeof(SearchResults_t)); for( i = 0; i < *count; i++ ) { d = &h->doc(i); ts = STRDUP_TtoA(d->get(_T("timestamp"))); results[i].timestamp = atoi(ts) * SEARCH_WINDOW; results[i].score = h->score(i); free( ts ); } reader->close(); _CLDELETE(h); _CLDELETE(q); _CLDELETE(s); _CLDELETE(reader); return( results ); } } /* C++ internals */ char *clucene_escape( char *text ) { static char buf[MAX_STRING_LEN]; static const char chars[] = "+-&|!(){}[]^\"~*?:\\"; int len; int i; int j; len = strlen(text); for( i = 0, j = 0; i < len && j < MAX_STRING_LEN - 1; i++ ) { if( strchr( chars, (int)text[i] ) ) { buf[j++] = '\\'; } buf[j++] = text[i]; } buf[j] = '\0'; return( buf ); } #ifndef WEBSERVICE void addLogentry( Document *doc, unsigned long *tb, IndexItem_t *item ) { static TCHAR buf[MAX_STRING_LEN]; IndexWriter *writer; if( *tb != item->timestamp ) { if( *tb != 0 ) { writer = getWriter(false); writer->addDocument( doc ); closeWriter( writer ); doc->clear(); } if( item->text == NULL ) { /* Keepalive */ *tb = 0; return; } if( !loadLogentry( doc, item->timestamp ) ) { _sntprintf( buf, MAX_STRING_LEN, _T("%ld"), item->timestamp ); doc->add( *_CLNEW Field( _T("timestamp"), buf, Field::STORE_YES | Field::INDEX_TOKENIZED ) ); _sntprintf( buf, MAX_STRING_LEN, _T("%ld"), item->chanid ); doc->add( *_CLNEW Field( _T("chanid"), buf, Field::STORE_YES | Field::INDEX_TOKENIZED ) ); } *tb = item->timestamp; } STRCPY_AtoT(buf, item->nick, MAX_STRING_LEN); doc->add( *_CLNEW Field( _T("nick"), buf, Field::STORE_YES | Field::INDEX_TOKENIZED ) ); STRCPY_AtoT(buf, item->text, MAX_STRING_LEN); doc->add( *_CLNEW Field( _T("text"), buf, Field::STORE_YES | Field::INDEX_TOKENIZED ) ); } int loadLogentry( Document *doc, unsigned long tb ) { IndexReader *reader; WhitespaceAnalyzer an; IndexSearcher *s; Query *q; Hits *h; Document *d; DocumentFieldEnumeration *fields; Field *field; static TCHAR query[80]; int len; reader = IndexReader::open(CLUCENE_INDEX_DIR); s = _CLNEW IndexSearcher(reader); _sntprintf( query, 80, _T("%ld"), tb ); q = QueryParser::parse(query, _T("timestamp"), &an); h = s->search(q); len = h->length(); #if 0 LogPrint( LOG_INFO, "Q: %ls len: %d", q->toString(), len ); #endif if( h->length() == 0 ) { reader->close(); _CLDELETE(h); _CLDELETE(q); _CLDELETE(s); _CLDELETE(reader); return( 0 ); } d = &h->doc(0); fields = d->fields(); doc->clear(); /* Recreate the current document */ while( (field = fields->nextElement()) ) { doc->add( *_CLNEW Field( field->name(), field->stringValue(), Field::STORE_YES | Field::INDEX_TOKENIZED ) ); } LogPrint( LOG_INFO, "Deleting document %lld", (uint64)(h->id(0)) ); reader->deleteDocument( h->id(0) ); reader->close(); _CLDELETE(h); _CLDELETE(q); _CLDELETE(s); _CLDELETE(reader); return( 1 ); } IndexWriter *getWriter( int clear ) { WhitespaceAnalyzer *an; IndexWriter *writer = NULL; #if 0 LogPrintNoArg(LOG_INFO, "Opening writer"); #endif an = _CLNEW WhitespaceAnalyzer; if ( !clear && IndexReader::indexExists(CLUCENE_INDEX_DIR) ){ if ( IndexReader::isLocked(CLUCENE_INDEX_DIR) ){ LogPrintNoArg( LOG_INFO, "Index was locked... unlocking it."); IndexReader::unlock(CLUCENE_INDEX_DIR); } writer = _CLNEW IndexWriter( CLUCENE_INDEX_DIR, an, false); } else { writer = _CLNEW IndexWriter( CLUCENE_INDEX_DIR, an, true); } writer->setMaxFieldLength(1000000); return( writer ); } void closeWriter( IndexWriter *writer ) { WhitespaceAnalyzer *an; #if 0 LogPrintNoArg( LOG_INFO, "Closing Writer" ); #endif an = (WhitespaceAnalyzer *)writer->getAnalyzer(); writer->close(); _CLDELETE(an); _CLDELETE(writer); } void *kicker_thread( void *arg ) { struct timeval tv; unsigned long now; unsigned long target; int i; LogPrintNoArg( LOG_INFO, "Starting CLucene Kicker thread" ); while( !GlobalAbort ) { gettimeofday( &tv, NULL ); now = tv.tv_sec; target = ((now / SEARCH_WINDOW) + 1) * SEARCH_WINDOW; sleep( target - now ); LogPrint( LOG_INFO, "Kicking %d channel indexes", docmax ); for( i = 0; i < docmax; i++ ) { clucene_add( i + 1, NULL, NULL, target / SEARCH_WINDOW ); } } LogPrintNoArg( LOG_INFO, "Ending CLucene Kicker thread" ); return( NULL ); } void *clucene_thread( void *arg ) { IndexItem_t *item; IndexWriter *writer = NULL; Document **doc = NULL; unsigned long *lasttb = NULL; int i; int clear; clear = *(int *)arg; LogPrint(LOG_INFO, "Clear: %d", clear ); LogPrintNoArg( LOG_NOTICE, "Starting CLucene thread" ); LogPrint( LOG_INFO, "Using CLucene v%s index in %s", _CL_VERSION, CLUCENE_INDEX_DIR ); writer = getWriter(clear); LogPrint( LOG_INFO, "%ld documents indexed", (long int)writer->docCount() ); if( optimize ) { LogPrintNoArg( LOG_INFO, "Optimizing index" ); writer->optimize(); LogPrintNoArg( LOG_INFO, "Finished optimizing index" ); } closeWriter( writer ); while( !GlobalAbort ) { item = (IndexItem_t *)QueueDequeueItem( IndexQ, 1000 ); if( !item ) { continue; } if( item->chanid > docmax ) { doc = (Document **)realloc(doc, item->chanid * sizeof(Document *)); lasttb = (unsigned long *)realloc(lasttb, item->chanid * sizeof(unsigned long )); for( i = docmax; i < item->chanid; i++ ) { doc[i] = new Document; doc[i]->clear(); lasttb[i] = 0; } docmax = item->chanid; } addLogentry( doc[item->chanid - 1], &lasttb[item->chanid - 1], item ); if( item->nick ) { free( item->nick ); } if( item->text ) { free( item->text ); } free( item ); } LogPrintNoArg( LOG_NOTICE, "Ending CLucene thread" ); writer = getWriter(0); for( i = 0; i < docmax; i++ ) { if( lasttb[i] != 0 ) { writer->addDocument( doc[i] ); _CLDELETE( doc[i] ); } } closeWriter( writer ); free( lasttb ); free( doc ); return(NULL); } #endif /* * vim:ts=4:sw=4:ai:et:si:sts=4 */ <|endoftext|>
<commit_before>// Copyright (c) 2007, 2008 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <algorithm> #include <string> #include <vector> //#include "libmv/correspondence/correspondence.h" #include "libmv/correspondence/klt.h" #include "libmv/image/image.h" #include "libmv/image/image_io.h" #include "libmv/image/image_pyramid.h" #include "third_party/gflags/gflags.h" using std::string; using std::sort; using std::vector; using libmv::KltContext; using libmv::ImagePyramid; using libmv::FloatImage; using libmv::Vec3; void WriteOutputImage(const FloatImage &image, const KltContext &klt, const KltContext::FeatureList &features, const char *output_filename) { FloatImage output_image(image.Height(), image.Width(), 3); for (int i = 0; i < image.Height(); ++i) { for (int j = 0; j < image.Width(); ++j) { output_image(i,j,0) = image(i,j); output_image(i,j,1) = image(i,j); output_image(i,j,2) = image(i,j); } } Vec3 green; green = 0, 1, 0; klt.DrawFeatureList(features, green, &output_image); WritePnm(output_image, output_filename); } int main(int argc, char **argv) { google::SetUsageMessage("Track a sequence."); google::ParseCommandLineFlags(&argc, &argv, true); // This is not the place for this. I am experimenting with what sort of API // will be convenient for the tracking base classes. vector<string> files; for (int i = 0; i < argc; ++i) { files.push_back(argv[i]); } sort(files.begin(), files.end()); if (files.size() < 2) { printf("Not enough files.\n"); return 1; } int oldind = 0, newind = 1; FloatImage image[2]; ImagePyramid pyramid[2]; KltContext::FeatureList features[2]; KltContext klt; ReadPnm(files[0].c_str(), &image[newind]); pyramid[newind].Init(image[newind], 3); klt.DetectGoodFeatures(pyramid[newind], &features[newind]); WriteOutputImage(image[newind], klt, features[newind], (files[0]+".out.ppm").c_str()); for (size_t i = 1; i < files.size(); ++i) { std::swap(oldind, newind); ReadPnm(files[i].c_str(), &image[newind]); pyramid[newind].Init(image[newind], 3); klt.TrackFeatures(pyramid[oldind], features[oldind], pyramid[newind], &features[newind]); WriteOutputImage(image[newind], klt, features[newind], (files[i]+".out.ppm").c_str()); // TODO(keir): Finish me. } return 0; } <commit_msg>Display tracking information.<commit_after>// Copyright (c) 2007, 2008 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <algorithm> #include <string> #include <vector> //#include "libmv/correspondence/correspondence.h" #include "libmv/correspondence/klt.h" #include "libmv/image/image.h" #include "libmv/image/image_io.h" #include "libmv/image/image_pyramid.h" #include "third_party/gflags/gflags.h" using std::string; using std::sort; using std::vector; using libmv::KltContext; using libmv::ImagePyramid; using libmv::FloatImage; using libmv::Vec3; void WriteOutputImage(const FloatImage &image, const KltContext &klt, const KltContext::FeatureList &features, const char *output_filename) { FloatImage output_image(image.Height(), image.Width(), 3); for (int i = 0; i < image.Height(); ++i) { for (int j = 0; j < image.Width(); ++j) { output_image(i,j,0) = image(i,j); output_image(i,j,1) = image(i,j); output_image(i,j,2) = image(i,j); } } Vec3 green; green = 0, 1, 0; klt.DrawFeatureList(features, green, &output_image); WritePnm(output_image, output_filename); } int main(int argc, char **argv) { google::SetUsageMessage("Track a sequence."); google::ParseCommandLineFlags(&argc, &argv, true); // This is not the place for this. I am experimenting with what sort of API // will be convenient for the tracking base classes. vector<string> files; for (int i = 0; i < argc; ++i) { files.push_back(argv[i]); } sort(files.begin(), files.end()); if (files.size() < 2) { printf("Not enough files.\n"); return 1; } int oldind = 0, newind = 1; FloatImage image[2]; ImagePyramid pyramid[2]; KltContext::FeatureList features[2]; KltContext klt; ReadPnm(files[0].c_str(), &image[newind]); pyramid[newind].Init(image[newind], 3); klt.DetectGoodFeatures(pyramid[newind], &features[newind]); WriteOutputImage(image[newind], klt, features[newind], (files[0]+".out.ppm").c_str()); for (size_t i = 1; i < files.size(); ++i) { std::swap(oldind, newind); printf("Tracking %s\n", files[i].c_str()); ReadPnm(files[i].c_str(), &image[newind]); pyramid[newind].Init(image[newind], 3); klt.TrackFeatures(pyramid[oldind], features[oldind], pyramid[newind], &features[newind]); WriteOutputImage(image[newind], klt, features[newind], (files[i]+".out.ppm").c_str()); // TODO(keir): Finish me. } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: HelperCollections.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-07-10 15:02:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBA_HELPERCOLLECTIONS_HXX #define DBA_HELPERCOLLECTIONS_HXX #ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_ #include "connectivity/sdbcx/VCollection.hxx" #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef _DBHELPER_DBCONVERSION_HXX_ #include <connectivity/dbconversion.hxx> #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include <connectivity/PColumn.hxx> #endif #ifndef _VOS_REF_HXX_ #include <vos/ref.hxx> #endif namespace dbaccess { using namespace dbtools; using namespace comphelper; using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::script; using namespace ::cppu; using namespace ::osl; // ----------------------------------------------------------------------------- typedef connectivity::sdbcx::OCollection OPrivateColumns_Base; class OPrivateColumns : public OPrivateColumns_Base { ::vos::ORef< ::connectivity::OSQLColumns> m_aColumns; protected: virtual connectivity::sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); virtual void impl_refresh() throw(RuntimeException) {} virtual Reference< XPropertySet > createDescriptor() { return NULL; } public: OPrivateColumns(const ::vos::ORef< ::connectivity::OSQLColumns>& _rColumns, sal_Bool _bCase, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector, sal_Bool _bUseAsIndex = sal_False ); /** creates a columns instance as above, but taking the names from the columns itself */ static OPrivateColumns* createWithIntrinsicNames( const ::vos::ORef< ::connectivity::OSQLColumns >& _rColumns, sal_Bool _bCase, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex ); virtual void SAL_CALL disposing(void); }; typedef connectivity::sdbcx::OCollection OPrivateTables_BASE; //========================================================================== //= OPrivateTables //========================================================================== class OPrivateTables : public OPrivateTables_BASE { OSQLTables m_aTables; protected: virtual connectivity::sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); virtual void impl_refresh() throw(RuntimeException) {} virtual Reference< XPropertySet > createDescriptor() { return NULL; } public: OPrivateTables( const OSQLTables& _rTables, sal_Bool _bCase, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector ) : sdbcx::OCollection(_rParent,_bCase,_rMutex,_rVector) ,m_aTables(_rTables) { } virtual void SAL_CALL disposing(void) { clear_NoDispose(); // we're not owner of the objects we're holding, instead the object we got in our ctor is // So we're not allowed to dispose our elements. m_aTables.clear(); OPrivateTables_BASE::disposing(); } }; } #endif // DBA_HELPERCOLLECTIONS_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.5.300); FILE MERGED 2008/03/31 13:26:42 rt 1.5.300.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: HelperCollections.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef DBA_HELPERCOLLECTIONS_HXX #define DBA_HELPERCOLLECTIONS_HXX #ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_ #include "connectivity/sdbcx/VCollection.hxx" #endif #ifndef _CONNECTIVITY_DBTOOLS_HXX_ #include <connectivity/dbtools.hxx> #endif #ifndef _DBHELPER_DBCONVERSION_HXX_ #include <connectivity/dbconversion.hxx> #endif #ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_ #include <connectivity/PColumn.hxx> #endif #ifndef _VOS_REF_HXX_ #include <vos/ref.hxx> #endif namespace dbaccess { using namespace dbtools; using namespace comphelper; using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::script; using namespace ::cppu; using namespace ::osl; // ----------------------------------------------------------------------------- typedef connectivity::sdbcx::OCollection OPrivateColumns_Base; class OPrivateColumns : public OPrivateColumns_Base { ::vos::ORef< ::connectivity::OSQLColumns> m_aColumns; protected: virtual connectivity::sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); virtual void impl_refresh() throw(RuntimeException) {} virtual Reference< XPropertySet > createDescriptor() { return NULL; } public: OPrivateColumns(const ::vos::ORef< ::connectivity::OSQLColumns>& _rColumns, sal_Bool _bCase, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector, sal_Bool _bUseAsIndex = sal_False ); /** creates a columns instance as above, but taking the names from the columns itself */ static OPrivateColumns* createWithIntrinsicNames( const ::vos::ORef< ::connectivity::OSQLColumns >& _rColumns, sal_Bool _bCase, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex ); virtual void SAL_CALL disposing(void); }; typedef connectivity::sdbcx::OCollection OPrivateTables_BASE; //========================================================================== //= OPrivateTables //========================================================================== class OPrivateTables : public OPrivateTables_BASE { OSQLTables m_aTables; protected: virtual connectivity::sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); virtual void impl_refresh() throw(RuntimeException) {} virtual Reference< XPropertySet > createDescriptor() { return NULL; } public: OPrivateTables( const OSQLTables& _rTables, sal_Bool _bCase, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector ) : sdbcx::OCollection(_rParent,_bCase,_rMutex,_rVector) ,m_aTables(_rTables) { } virtual void SAL_CALL disposing(void) { clear_NoDispose(); // we're not owner of the objects we're holding, instead the object we got in our ctor is // So we're not allowed to dispose our elements. m_aTables.clear(); OPrivateTables_BASE::disposing(); } }; } #endif // DBA_HELPERCOLLECTIONS_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TableConnectionData.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-11-01 15:18:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBAUI_TABLECONNECTIONDATA_HXX #define DBAUI_TABLECONNECTIONDATA_HXX #ifndef DBAUI_CONNECTIONLINEDATA_HXX #include "ConnectionLineData.hxx" #endif #include "TableWindowData.hxx" #include <vector> #ifndef _RTTI_HXX #include <tools/rtti.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #include <boost/shared_ptr.hpp> namespace dbaui { #define MAX_CONN_COUNT 2 //================================================================== // ConnData ---------->* ConnLineData // ^1 ^1 // | | // Conn ---------->* ConnLine //================================================================== //================================================================== /* the class OTableConnectionData contains all connection data which exists between two windows **/ class OTableConnectionData { protected: TTableWindowData::value_type m_pReferencingTable; TTableWindowData::value_type m_pReferencedTable; String m_aConnName; OConnectionLineDataVec m_vConnLineData; void Init(); virtual OConnectionLineDataRef CreateLineDataObj(); virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData ); OTableConnectionData& operator=( const OTableConnectionData& rConnData ); public: OTableConnectionData(); OTableConnectionData(const TTableWindowData::value_type& _pReferencingTable,const TTableWindowData::value_type& _pReferencedTable, const String& rConnName = String() ); OTableConnectionData( const OTableConnectionData& rConnData ); virtual ~OTableConnectionData(); // sich aus einer Quelle initialisieren (das ist mir irgendwie angenehmer als ein virtueller Zuweisungsoperator) virtual void CopyFrom(const OTableConnectionData& rSource); // eine neue Instanz meines eigenen Typs liefern (braucht NICHT initialisiert sein) virtual OTableConnectionData* NewInstance() const; // (von OTableConnectionData abgeleitete Klasse muessen entsprechend eine Instanz ihrer Klasse liefern) BOOL SetConnLine( USHORT nIndex, const String& rSourceFieldName, const String& rDestFieldName ); BOOL AppendConnLine( const ::rtl::OUString& rSourceFieldName, const ::rtl::OUString& rDestFieldName ); void ResetConnLines( BOOL bUseDefaults = TRUE ); /** normalizeLines moves the empty lines to the back */ void normalizeLines(); // loescht die Liste der ConnLines, bei bUseDefaults == TRUE werden danach MAX_CONN_COUNT neue Dummy-Linien eingefuegt OConnectionLineDataVec* GetConnLineDataList(){ return &m_vConnLineData; } inline TTableWindowData::value_type getReferencingTable() const { return m_pReferencingTable; } inline TTableWindowData::value_type getReferencedTable() const { return m_pReferencedTable; } inline void setReferencingTable(const TTableWindowData::value_type& _pTable) { m_pReferencingTable = _pTable; } inline void setReferencedTable(const TTableWindowData::value_type& _pTable) { m_pReferencedTable = _pTable; } String GetConnName() const { return m_aConnName; } virtual void SetConnName( const String& rConnName ){ m_aConnName = rConnName; } /** Update create a new connection @return true if successful */ virtual BOOL Update(){ return TRUE; } }; typedef ::std::vector< ::boost::shared_ptr<OTableConnectionData> > TTableConnectionData; } #endif // DBAUI_TABLECONNECTIONDATA_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.5.96); FILE MERGED 2008/03/31 13:27:44 rt 1.5.96.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TableConnectionData.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef DBAUI_TABLECONNECTIONDATA_HXX #define DBAUI_TABLECONNECTIONDATA_HXX #ifndef DBAUI_CONNECTIONLINEDATA_HXX #include "ConnectionLineData.hxx" #endif #include "TableWindowData.hxx" #include <vector> #ifndef _RTTI_HXX #include <tools/rtti.hxx> #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #include <boost/shared_ptr.hpp> namespace dbaui { #define MAX_CONN_COUNT 2 //================================================================== // ConnData ---------->* ConnLineData // ^1 ^1 // | | // Conn ---------->* ConnLine //================================================================== //================================================================== /* the class OTableConnectionData contains all connection data which exists between two windows **/ class OTableConnectionData { protected: TTableWindowData::value_type m_pReferencingTable; TTableWindowData::value_type m_pReferencedTable; String m_aConnName; OConnectionLineDataVec m_vConnLineData; void Init(); virtual OConnectionLineDataRef CreateLineDataObj(); virtual OConnectionLineDataRef CreateLineDataObj( const OConnectionLineData& rConnLineData ); OTableConnectionData& operator=( const OTableConnectionData& rConnData ); public: OTableConnectionData(); OTableConnectionData(const TTableWindowData::value_type& _pReferencingTable,const TTableWindowData::value_type& _pReferencedTable, const String& rConnName = String() ); OTableConnectionData( const OTableConnectionData& rConnData ); virtual ~OTableConnectionData(); // sich aus einer Quelle initialisieren (das ist mir irgendwie angenehmer als ein virtueller Zuweisungsoperator) virtual void CopyFrom(const OTableConnectionData& rSource); // eine neue Instanz meines eigenen Typs liefern (braucht NICHT initialisiert sein) virtual OTableConnectionData* NewInstance() const; // (von OTableConnectionData abgeleitete Klasse muessen entsprechend eine Instanz ihrer Klasse liefern) BOOL SetConnLine( USHORT nIndex, const String& rSourceFieldName, const String& rDestFieldName ); BOOL AppendConnLine( const ::rtl::OUString& rSourceFieldName, const ::rtl::OUString& rDestFieldName ); void ResetConnLines( BOOL bUseDefaults = TRUE ); /** normalizeLines moves the empty lines to the back */ void normalizeLines(); // loescht die Liste der ConnLines, bei bUseDefaults == TRUE werden danach MAX_CONN_COUNT neue Dummy-Linien eingefuegt OConnectionLineDataVec* GetConnLineDataList(){ return &m_vConnLineData; } inline TTableWindowData::value_type getReferencingTable() const { return m_pReferencingTable; } inline TTableWindowData::value_type getReferencedTable() const { return m_pReferencedTable; } inline void setReferencingTable(const TTableWindowData::value_type& _pTable) { m_pReferencingTable = _pTable; } inline void setReferencedTable(const TTableWindowData::value_type& _pTable) { m_pReferencedTable = _pTable; } String GetConnName() const { return m_aConnName; } virtual void SetConnName( const String& rConnName ){ m_aConnName = rConnName; } /** Update create a new connection @return true if successful */ virtual BOOL Update(){ return TRUE; } }; typedef ::std::vector< ::boost::shared_ptr<OTableConnectionData> > TTableConnectionData; } #endif // DBAUI_TABLECONNECTIONDATA_HXX <|endoftext|>
<commit_before>/* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __MEM_RUBY_SYSTEM_PERFECTCACHEMEMORY_HH__ #define __MEM_RUBY_SYSTEM_PERFECTCACHEMEMORY_HH__ #include "base/hashmap.hh" #include "mem/protocol/AccessPermission.hh" #include "mem/ruby/common/Address.hh" #include "mem/ruby/common/Global.hh" template<class ENTRY> struct PerfectCacheLineState { PerfectCacheLineState() { m_permission = AccessPermission_NUM; } AccessPermission m_permission; ENTRY m_entry; }; template<class ENTRY> inline std::ostream& operator<<(std::ostream& out, const PerfectCacheLineState<ENTRY>& obj) { return out; } template<class ENTRY> class PerfectCacheMemory { public: PerfectCacheMemory(); static void printConfig(std::ostream& out); // perform a cache access and see if we hit or not. Return true // on a hit. bool tryCacheAccess(const CacheMsg& msg, bool& block_stc, ENTRY*& entry); // tests to see if an address is present in the cache bool isTagPresent(const Address& address) const; // Returns true if there is: // a) a tag match on this address or there is // b) an Invalid line in the same cache "way" bool cacheAvail(const Address& address) const; // find an Invalid entry and sets the tag appropriate for the address void allocate(const Address& address); void deallocate(const Address& address); // Returns with the physical address of the conflicting cache line Address cacheProbe(const Address& newAddress) const; // looks an address up in the cache ENTRY& lookup(const Address& address); const ENTRY& lookup(const Address& address) const; // Get/Set permission of cache block AccessPermission getPermission(const Address& address) const; void changePermission(const Address& address, AccessPermission new_perm); // Print cache contents void print(std::ostream& out) const; private: // Private copy constructor and assignment operator PerfectCacheMemory(const PerfectCacheMemory& obj); PerfectCacheMemory& operator=(const PerfectCacheMemory& obj); // Data Members (m_prefix) m5::hash_map<Address, PerfectCacheLineState<ENTRY> > m_map; }; template<class ENTRY> inline std::ostream& operator<<(std::ostream& out, const PerfectCacheMemory<ENTRY>& obj) { obj.print(out); out << std::flush; return out; } template<class ENTRY> inline PerfectCacheMemory<ENTRY>::PerfectCacheMemory() { } template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::printConfig(std::ostream& out) { } template<class ENTRY> inline bool PerfectCacheMemory<ENTRY>::tryCacheAccess(const CacheMsg& msg, bool& block_stc, ENTRY*& entry) { panic("not implemented"); } // tests to see if an address is present in the cache template<class ENTRY> inline bool PerfectCacheMemory<ENTRY>::isTagPresent(const Address& address) const { return m_map.count(line_address(address)) > 0; } template<class ENTRY> inline bool PerfectCacheMemory<ENTRY>::cacheAvail(const Address& address) const { return true; } // find an Invalid or already allocated entry and sets the tag // appropriate for the address template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::allocate(const Address& address) { PerfectCacheLineState<ENTRY> line_state; line_state.m_permission = AccessPermission_Busy; line_state.m_entry = ENTRY(); m_map[line_address(address)] = line_state; } // deallocate entry template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::deallocate(const Address& address) { m_map.erase(line_address(address)); } // Returns with the physical address of the conflicting cache line template<class ENTRY> inline Address PerfectCacheMemory<ENTRY>::cacheProbe(const Address& newAddress) const { panic("cacheProbe called in perfect cache"); } // looks an address up in the cache template<class ENTRY> inline ENTRY& PerfectCacheMemory<ENTRY>::lookup(const Address& address) { return m_map[line_address(address)].m_entry; } // looks an address up in the cache template<class ENTRY> inline const ENTRY& PerfectCacheMemory<ENTRY>::lookup(const Address& address) const { return m_map[line_address(address)].m_entry; } template<class ENTRY> inline AccessPermission PerfectCacheMemory<ENTRY>::getPermission(const Address& address) const { return m_map[line_address(address)].m_permission; } template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::changePermission(const Address& address, AccessPermission new_perm) { Address line_address = address; line_address.makeLineAddress(); PerfectCacheLineState<ENTRY>& line_state = m_map[line_address]; AccessPermission old_perm = line_state.m_permission; line_state.m_permission = new_perm; } template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::print(std::ostream& out) const { } #endif // __MEM_RUBY_SYSTEM_PERFECTCACHEMEMORY_HH__ <commit_msg>PerfectCacheMemory: Add return statements to two functions. Two functions in src/mem/ruby/system/PerfectCacheMemory.hh, tryCacheAccess() and cacheProbe(), end with calls to panic(). Both of these functions have return type other than void. Any file that includes this header file fails to compile because of the missing return statement. This patch adds dummy values so as to avoid the compiler warnings.<commit_after>/* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __MEM_RUBY_SYSTEM_PERFECTCACHEMEMORY_HH__ #define __MEM_RUBY_SYSTEM_PERFECTCACHEMEMORY_HH__ #include "base/hashmap.hh" #include "mem/protocol/AccessPermission.hh" #include "mem/ruby/common/Address.hh" #include "mem/ruby/common/Global.hh" template<class ENTRY> struct PerfectCacheLineState { PerfectCacheLineState() { m_permission = AccessPermission_NUM; } AccessPermission m_permission; ENTRY m_entry; }; template<class ENTRY> inline std::ostream& operator<<(std::ostream& out, const PerfectCacheLineState<ENTRY>& obj) { return out; } template<class ENTRY> class PerfectCacheMemory { public: PerfectCacheMemory(); static void printConfig(std::ostream& out); // perform a cache access and see if we hit or not. Return true // on a hit. bool tryCacheAccess(const CacheMsg& msg, bool& block_stc, ENTRY*& entry); // tests to see if an address is present in the cache bool isTagPresent(const Address& address) const; // Returns true if there is: // a) a tag match on this address or there is // b) an Invalid line in the same cache "way" bool cacheAvail(const Address& address) const; // find an Invalid entry and sets the tag appropriate for the address void allocate(const Address& address); void deallocate(const Address& address); // Returns with the physical address of the conflicting cache line Address cacheProbe(const Address& newAddress) const; // looks an address up in the cache ENTRY& lookup(const Address& address); const ENTRY& lookup(const Address& address) const; // Get/Set permission of cache block AccessPermission getPermission(const Address& address) const; void changePermission(const Address& address, AccessPermission new_perm); // Print cache contents void print(std::ostream& out) const; private: // Private copy constructor and assignment operator PerfectCacheMemory(const PerfectCacheMemory& obj); PerfectCacheMemory& operator=(const PerfectCacheMemory& obj); // Data Members (m_prefix) m5::hash_map<Address, PerfectCacheLineState<ENTRY> > m_map; }; template<class ENTRY> inline std::ostream& operator<<(std::ostream& out, const PerfectCacheMemory<ENTRY>& obj) { obj.print(out); out << std::flush; return out; } template<class ENTRY> inline PerfectCacheMemory<ENTRY>::PerfectCacheMemory() { } template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::printConfig(std::ostream& out) { } template<class ENTRY> inline bool PerfectCacheMemory<ENTRY>::tryCacheAccess(const CacheMsg& msg, bool& block_stc, ENTRY*& entry) { panic("not implemented"); return true; } // tests to see if an address is present in the cache template<class ENTRY> inline bool PerfectCacheMemory<ENTRY>::isTagPresent(const Address& address) const { return m_map.count(line_address(address)) > 0; } template<class ENTRY> inline bool PerfectCacheMemory<ENTRY>::cacheAvail(const Address& address) const { return true; } // find an Invalid or already allocated entry and sets the tag // appropriate for the address template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::allocate(const Address& address) { PerfectCacheLineState<ENTRY> line_state; line_state.m_permission = AccessPermission_Busy; line_state.m_entry = ENTRY(); m_map[line_address(address)] = line_state; } // deallocate entry template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::deallocate(const Address& address) { m_map.erase(line_address(address)); } // Returns with the physical address of the conflicting cache line template<class ENTRY> inline Address PerfectCacheMemory<ENTRY>::cacheProbe(const Address& newAddress) const { panic("cacheProbe called in perfect cache"); return newAddress; } // looks an address up in the cache template<class ENTRY> inline ENTRY& PerfectCacheMemory<ENTRY>::lookup(const Address& address) { return m_map[line_address(address)].m_entry; } // looks an address up in the cache template<class ENTRY> inline const ENTRY& PerfectCacheMemory<ENTRY>::lookup(const Address& address) const { return m_map[line_address(address)].m_entry; } template<class ENTRY> inline AccessPermission PerfectCacheMemory<ENTRY>::getPermission(const Address& address) const { return m_map[line_address(address)].m_permission; } template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::changePermission(const Address& address, AccessPermission new_perm) { Address line_address = address; line_address.makeLineAddress(); PerfectCacheLineState<ENTRY>& line_state = m_map[line_address]; AccessPermission old_perm = line_state.m_permission; line_state.m_permission = new_perm; } template<class ENTRY> inline void PerfectCacheMemory<ENTRY>::print(std::ostream& out) const { } #endif // __MEM_RUBY_SYSTEM_PERFECTCACHEMEMORY_HH__ <|endoftext|>