text
stringlengths
54
60.6k
<commit_before>#pragma once #include <cassert> #include <cstring> #include <cuchar> #include <map> #include <string> #include <unordered_map> namespace xmlpp { enum class entity_type { TAG, TAG_ENDING, COMMENT, TEXT }; /** * @brief A parser adhering to SAX inteface. * * The class itself acts as an iterator, a foward one. So each * time you call next() (or operator++()) it will advance to next * entity, in a Depth first approach. */ class sax { public: static constexpr const char *BLANKS = " \t\n\r"; /** * @brief constructor that takes a c-string with the content. */ sax(const char *code) { m_code = code; next(); } bool next() { using namespace std; if (m_singletag) { m_type = entity_type::TAG_ENDING; m_singletag = false; return true; } if (*m_code == 0) { return false; } auto space = ignoreBlanks(); if (*m_code == '<') { if (*(m_code + 1) == '!') { if (*(m_code + 2) == '-') { nextComment(); } else if (*(m_code + 2) == '[') { nextText(); } } else if (*(m_code + 1) == '?') { nextDeclaration(); return next(); } else { nextTag(); } } else { m_code -= space; nextText(); } return true; } sax &operator++() { next(); return *this; } sax operator++(int) { auto temp = *this; next(); return temp; } /** * @brief returns the type of the current node. */ entity_type type() const { return m_type; } /** * @brief Returns the value of the current node. * * The meaning of value is: * | type() | Meaning | * | ------ | ------------------------------------------ | * | tag | the name of tag ("<root/>"'s name is root) | */ const std::string &value() const { return m_value; } /** * @brief the type of the parameters map. * * The underline type is implementation defined. Please use the aliased type. * We guaranteed that it defines an iterator, the operator[], the begin(), * end(), count() and size() and is able to be used with range-for. */ using params_map = std::unordered_map<std::string, std::string>; /** * @brief Return the current parameters. * * The reference is valid until the next call of next() or operator++(). */ const params_map &params() const { return m_params; } /** * @brief Return the document's encoding. * * Currently it always will return "UTF-8" */ const std::string encoding() const { return "UTF-8"; } /** * @brief Return the document's xml version. * * This will report whatever is informed on the XML declaration or * "1.0" if no declaration is provided. * In the future different behaviour can be enabled for different versions. */ const std::string &version() const { return m_version; } private: const char *m_code; entity_type m_type; std::string m_value; params_map m_params; bool m_singletag = false; bool m_initialized = false; std::string m_version = "1.0"; private: void nextTag() { using namespace std; assert(*m_code == '<'); auto tag_beg = ++m_code; bool closing = false; if (*m_code == '/') { closing = true; ++m_code; m_type = entity_type::TAG_ENDING; } else { m_type = entity_type::TAG; } for (; *m_code != 0; ++m_code) { if (strchr(BLANKS, *m_code) || *m_code == '>' || *m_code == '/') { m_value.assign(tag_beg, m_code); parameters(); break; } } if (*m_code == '/') { ++m_code; m_singletag = true; } if (*m_code == '>') { ++m_code; } else { throw runtime_error("Unclosed tag."); } } void nextComment() { assert(*m_code++ == '<'); assert(*m_code++ == '!'); expect('-'); expect('-'); auto comment_beg = m_code; size_t level = 0; for (; *m_code != 0; ++m_code) { if (*m_code == '-') ++level; else if (*m_code == '>' && level >= 2) { m_type = entity_type::COMMENT; m_value.assign(comment_beg, m_code - 2); ++m_code; return; } else level = 0; } throw std::runtime_error("Expected '-->' before end of the buffer"); } void nextText() { auto text_beg = m_code; m_value.clear(); for (; *m_code != 0; ++m_code) { if (*m_code == '<') { if (*(m_code + 1) == '!' && *(m_code + 2) == '[') { m_value.append(text_beg, m_code); m_value.append(cdataSequence()); text_beg = m_code--; } else { break; } } if (*m_code == '&') { m_value.append(text_beg, m_code); m_value.append(escapeSequence()); text_beg = m_code + 1; } } m_type = entity_type::TEXT; m_value.append(text_beg, m_code); } void nextDeclaration() { if (m_initialized) { throw std::runtime_error( "Invalid declaration or using processor " "instruction, which aren't currently implemented."); } assert(*m_code++ == '<'); assert(*m_code++ == '?'); expect('x'); expect('m'); expect('l'); parameters(); if (m_params.count("encoding")) { auto encoding = m_params["encoding"]; if (encoding != "UTF-8") { throw std::runtime_error("Invalid encoding:" + encoding); } } if (m_params.count("version")) { m_version = m_params["version"]; } expect('?'); expect('>'); m_initialized = true; } std::string cdataSequence() { using namespace std; ensure('<'); ensure('!'); ensure('['); expect('C'); expect('D'); expect('A'); expect('T'); expect('A'); expect('['); auto cdata_beg = m_code; string result; for (; *m_code != 0; ++m_code) { if (*m_code == ']' && *(m_code + 1) == ']' && *(m_code + 2) == '>') { result.assign(cdata_beg, m_code); break; } } ensure(']'); ensure(']'); ensure('>'); return result; } std::string escapeSequence() { using namespace std; ensure('&'); auto escape_beg = m_code; for (; *m_code != 0; ++m_code) { if (*m_code == ';') { std::string escape(escape_beg, m_code); if (escape[0] == '#') { char32_t value = 0; if (escape[1] == 'x') { for (size_t i = 2; i < escape.size(); ++i) { value *= 0x10; if (isdigit(escape[i])) { value += escape[i] & 0xf; } else if (isupper(escape[i])) { value += (escape[i] - 'A') | 0xA; } else { value += (escape[i] - 'a') | 0xA; } } } else { for (size_t i = 1; i < escape.size(); ++i) { value *= 10; value += escape[i] & 0xf; } } if (value) { if (value < 0x7f) { return {char(value)}; } else { string locale = std::setlocale(LC_ALL, nullptr); std::setlocale(LC_ALL, "en_US.utf8"); char buffer[MB_CUR_MAX + 1]; std::mbstate_t state{}; auto end = c32rtomb(buffer, value, &state); buffer[end] = 0; std::setlocale(LC_ALL, locale.c_str()); return string(buffer); } } } static map<string, string> escapeMapping = {{"lt", "<"}, {"gt", ">"}, {"amp", "&"}, {"quot", "\""}, {"apos", "'"}}; return escapeMapping[escape]; } } } void parameters() { using namespace std; PARAM_NAME: ignoreBlanks(); string pname = ""; auto pname_beg = m_code; for (; *m_code != 0; ++m_code) { if (*m_code == '>' || *m_code == '/' || *m_code == '?') { return; } if (*m_code == '=' || strchr(BLANKS, *m_code)) { if (m_code == pname_beg) { throw runtime_error( "Invalid Parameter. A name is expected before the '='"); } pname.assign(pname_beg, m_code); goto PARAM_VALUE; } } throw runtime_error("Expected close tag or parameter definition"); PARAM_VALUE: ignoreBlanks(); if (*m_code != '=') { m_params[pname] = pname; goto PARAM_NAME; } ++m_code; ignoreBlanks(); if (!strchr("\"\'", *m_code)) { throw runtime_error("Invalid Parameter '" + pname + "'. The parameter value must be " "surrounded by \' or \", we got: '" + *m_code + "'"); } char endToken = *m_code++; auto pvalue_beg = m_code++; m_params[pname].clear(); for (; *m_code != 0; ++m_code) { if (*m_code == '>') { throw runtime_error("Expected a \' or \" before <"); } if (*m_code == '&') { m_params[pname].append(pvalue_beg, m_code); m_params[pname].append(escapeSequence()); pvalue_beg = m_code + 1; } if (*m_code == endToken) { m_params[pname].append(pvalue_beg, m_code); ++m_code; goto PARAM_NAME; } } throw runtime_error("Unclosed parameter value"); } void expect(char expected) { if (*m_code == expected) { ++m_code; } else { using namespace std; throw std::runtime_error("Expected char '"s + expected + "', got '" + *m_code + "'."); } } void ensure(char expected) { assert(*m_code == expected); ++m_code; } size_t ignoreBlanks() { auto initial = m_code; while (strchr(BLANKS, *m_code)) { ++m_code; } return m_code - initial; } }; } <commit_msg>Using a better idiom for escaping.<commit_after>#pragma once #include <cassert> #include <cstring> #include <cuchar> #include <map> #include <string> #include <unordered_map> namespace xmlpp { enum class entity_type { TAG, TAG_ENDING, COMMENT, TEXT }; /** * @brief A parser adhering to SAX inteface. * * The class itself acts as an iterator, a foward one. So each * time you call next() (or operator++()) it will advance to next * entity, in a Depth first approach. */ class sax { public: static constexpr const char *BLANKS = " \t\n\r"; /** * @brief constructor that takes a c-string with the content. */ sax(const char *code) { m_code = code; next(); } bool next() { using namespace std; if (m_singletag) { m_type = entity_type::TAG_ENDING; m_singletag = false; return true; } if (*m_code == 0) { return false; } auto space = ignoreBlanks(); if (*m_code == '<') { if (*(m_code + 1) == '!') { if (*(m_code + 2) == '-') { nextComment(); } else if (*(m_code + 2) == '[') { nextText(); } } else if (*(m_code + 1) == '?') { nextDeclaration(); return next(); } else { nextTag(); } } else { m_code -= space; nextText(); } return true; } sax &operator++() { next(); return *this; } sax operator++(int) { auto temp = *this; next(); return temp; } /** * @brief returns the type of the current node. */ entity_type type() const { return m_type; } /** * @brief Returns the value of the current node. * * The meaning of value is: * | type() | Meaning | * | ------ | ------------------------------------------ | * | tag | the name of tag ("<root/>"'s name is root) | */ const std::string &value() const { return m_value; } /** * @brief the type of the parameters map. * * The underline type is implementation defined. Please use the aliased type. * We guaranteed that it defines an iterator, the operator[], the begin(), * end(), count() and size() and is able to be used with range-for. */ using params_map = std::unordered_map<std::string, std::string>; /** * @brief Return the current parameters. * * The reference is valid until the next call of next() or operator++(). */ const params_map &params() const { return m_params; } /** * @brief Return the document's encoding. * * Currently it always will return "UTF-8" */ const std::string encoding() const { return "UTF-8"; } /** * @brief Return the document's xml version. * * This will report whatever is informed on the XML declaration or * "1.0" if no declaration is provided. * In the future different behaviour can be enabled for different versions. */ const std::string &version() const { return m_version; } private: const char *m_code; entity_type m_type; std::string m_value; params_map m_params; bool m_singletag = false; bool m_initialized = false; std::string m_version = "1.0"; private: void nextTag() { using namespace std; assert(*m_code == '<'); auto tag_beg = ++m_code; bool closing = false; if (*m_code == '/') { closing = true; ++m_code; m_type = entity_type::TAG_ENDING; } else { m_type = entity_type::TAG; } for (; *m_code != 0; ++m_code) { if (strchr(BLANKS, *m_code) || *m_code == '>' || *m_code == '/') { m_value.assign(tag_beg, m_code); parameters(); break; } } if (*m_code == '/') { ++m_code; m_singletag = true; } if (*m_code == '>') { ++m_code; } else { throw runtime_error("Unclosed tag."); } } void nextComment() { assert(*m_code++ == '<'); assert(*m_code++ == '!'); expect('-'); expect('-'); auto comment_beg = m_code; size_t level = 0; for (; *m_code != 0; ++m_code) { if (*m_code == '-') ++level; else if (*m_code == '>' && level >= 2) { m_type = entity_type::COMMENT; m_value.assign(comment_beg, m_code - 2); ++m_code; return; } else level = 0; } throw std::runtime_error("Expected '-->' before end of the buffer"); } void nextText() { auto text_beg = m_code; m_value.clear(); for (; *m_code != 0; ++m_code) { if (*m_code == '<') { if (*(m_code + 1) == '!' && *(m_code + 2) == '[') { m_value.append(text_beg, m_code); m_value.append(cdataSequence()); text_beg = m_code--; } else { break; } } if (*m_code == '&') { m_value.append(text_beg, m_code); m_value.append(escapeSequence()); text_beg = m_code--; } } m_type = entity_type::TEXT; m_value.append(text_beg, m_code); } void nextDeclaration() { if (m_initialized) { throw std::runtime_error( "Invalid declaration or using processor " "instruction, which aren't currently implemented."); } assert(*m_code++ == '<'); assert(*m_code++ == '?'); expect('x'); expect('m'); expect('l'); parameters(); if (m_params.count("encoding")) { auto encoding = m_params["encoding"]; if (encoding != "UTF-8") { throw std::runtime_error("Invalid encoding:" + encoding); } } if (m_params.count("version")) { m_version = m_params["version"]; } expect('?'); expect('>'); m_initialized = true; } std::string cdataSequence() { using namespace std; ensure('<'); ensure('!'); ensure('['); expect('C'); expect('D'); expect('A'); expect('T'); expect('A'); expect('['); auto cdata_beg = m_code; string result; for (; *m_code != 0; ++m_code) { if (*m_code == ']' && *(m_code + 1) == ']' && *(m_code + 2) == '>') { result.assign(cdata_beg, m_code); break; } } ensure(']'); ensure(']'); ensure('>'); return result; } std::string escapeSequence() { using namespace std; ensure('&'); auto escape_beg = m_code; for (; *m_code != 0; ++m_code) { if (*m_code == ';') { std::string escape(escape_beg, m_code); ensure(';'); if (escape[0] == '#') { char32_t value = 0; if (escape[1] == 'x') { for (size_t i = 2; i < escape.size(); ++i) { value *= 0x10; if (isdigit(escape[i])) { value += escape[i] & 0xf; } else if (isupper(escape[i])) { value += (escape[i] - 'A') | 0xA; } else { value += (escape[i] - 'a') | 0xA; } } } else { for (size_t i = 1; i < escape.size(); ++i) { value *= 10; value += escape[i] & 0xf; } } if (value) { if (value < 0x7f) { return {char(value)}; } else { string locale = std::setlocale(LC_ALL, nullptr); std::setlocale(LC_ALL, "en_US.utf8"); char buffer[MB_CUR_MAX + 1]; std::mbstate_t state{}; auto end = c32rtomb(buffer, value, &state); buffer[end] = 0; std::setlocale(LC_ALL, locale.c_str()); return string(buffer); } } } static map<string, string> escapeMapping = {{"lt", "<"}, {"gt", ">"}, {"amp", "&"}, {"quot", "\""}, {"apos", "'"}}; return escapeMapping[escape]; } } } void parameters() { using namespace std; PARAM_NAME: ignoreBlanks(); string pname = ""; auto pname_beg = m_code; for (; *m_code != 0; ++m_code) { if (*m_code == '>' || *m_code == '/' || *m_code == '?') { return; } if (*m_code == '=' || strchr(BLANKS, *m_code)) { if (m_code == pname_beg) { throw runtime_error( "Invalid Parameter. A name is expected before the '='"); } pname.assign(pname_beg, m_code); goto PARAM_VALUE; } } throw runtime_error("Expected close tag or parameter definition"); PARAM_VALUE: ignoreBlanks(); if (*m_code != '=') { m_params[pname] = pname; goto PARAM_NAME; } ++m_code; ignoreBlanks(); if (!strchr("\"\'", *m_code)) { throw runtime_error("Invalid Parameter '" + pname + "'. The parameter value must be " "surrounded by \' or \", we got: '" + *m_code + "'"); } char endToken = *m_code++; auto pvalue_beg = m_code++; m_params[pname].clear(); for (; *m_code != 0; ++m_code) { if (*m_code == '>') { throw runtime_error("Expected a \' or \" before <"); } if (*m_code == '&') { m_params[pname].append(pvalue_beg, m_code); m_params[pname].append(escapeSequence()); pvalue_beg = m_code--; } if (*m_code == endToken) { m_params[pname].append(pvalue_beg, m_code); ++m_code; goto PARAM_NAME; } } throw runtime_error("Unclosed parameter value"); } void expect(char expected) { if (*m_code == expected) { ++m_code; } else { using namespace std; throw std::runtime_error("Expected char '"s + expected + "', got '" + *m_code + "'."); } } void ensure(char expected) { assert(*m_code == expected); ++m_code; } size_t ignoreBlanks() { auto initial = m_code; while (strchr(BLANKS, *m_code)) { ++m_code; } return m_code - initial; } }; } <|endoftext|>
<commit_before>/* * Copyright 2017 deepstreamHub 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. */ #ifndef DEEPSTREAM_USE_HPP #define DEEPSTREAM_USE_HPP namespace deepstream { template<typename T> void use(const T&) {} } #endif <commit_msg>Src: explain what `use()` does<commit_after>/* * Copyright 2017 deepstreamHub 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. */ #ifndef DEEPSTREAM_USE_HPP #define DEEPSTREAM_USE_HPP namespace deepstream { /** * Helper function used for suppressing "unused variable" warnings. * * Warnings about unused variables are useful but in some situations there * are false positives, e.g., when variables are only used during debugging * and one is compiling in release mode (here: with NDEBUG defined): * int ret = function(args); // causes warning: unused variable `ret' * assert( ret == 0 ); * return; */ template<typename T> void use(const T&) {} } #endif <|endoftext|>
<commit_before>// Copyright 2016 Robo@FIT #include "art_pr2_grasping/objects.h" #include <string> #include <vector> #include <set> namespace art_pr2_grasping { Objects::Objects(boost::shared_ptr<tf::TransformListener> tfl, std::string target_frame) { tfl_ = tfl; object_type_srv_ = nh_.serviceClient<art_msgs::getObjectType>("/art/db/object_type/get"); obj_sub_ = nh_.subscribe("/art/object_detector/object_filtered", 1, &Objects::detectedObjectsCallback, this); target_frame_ = target_frame; visual_tools_.reset(new moveit_visual_tools::VisualTools(target_frame_, "markers")); visual_tools_->loadPlanningSceneMonitor(); visual_tools_->setLifetime(10.0); visual_tools_->setMuted(false); visual_tools_->publishRemoveAllCollisionObjects(); paused_ = false; } void Objects::setPaused(bool paused) { boost::recursive_mutex::scoped_lock lock(mutex_); paused_ = paused; if (paused) { TObjectMap::iterator it; for (it = objects_.begin(); it != objects_.end(); ++it) { if (isGrasped(it->first)) continue; visual_tools_->cleanupCO(it->first); } } } void Objects::clear() { boost::recursive_mutex::scoped_lock lock(mutex_); for (std::set<std::string>::iterator i = grasped_objects_.begin(); i != grasped_objects_.end(); ++i) { visual_tools_->cleanupACO(*i); } visual_tools_->publishRemoveAllCollisionObjects(); objects_.clear(); grasped_objects_.clear(); } bool Objects::isKnownObject(std::string id) { boost::recursive_mutex::scoped_lock lock(mutex_); TObjectMap::iterator it = objects_.find(id); return it != objects_.end(); } std::vector<std::string> Objects::getObjects() { boost::recursive_mutex::scoped_lock lock(mutex_); std::vector<std::string> tmp; TObjectMap::iterator it; for (it = objects_.begin(); it != objects_.end(); ++it) { tmp.push_back(it->first); } return tmp; } TObjectInfo Objects::getObject(std::string object_id) { boost::recursive_mutex::scoped_lock lock(mutex_); if (isKnownObject(object_id)) return objects_[object_id]; else throw std::invalid_argument("unknown object_id: " + object_id); } bool Objects::transformPose(geometry_msgs::PoseStamped& ps) { try { if (tfl_->waitForTransform(target_frame_, ps.header.frame_id, ps.header.stamp, ros::Duration(1.0))) { tfl_->transformPose(target_frame_, ps, ps); } else { ROS_ERROR_NAMED("objects", "Transform between %s and %s not available!", target_frame_.c_str(), ps.header.frame_id.c_str()); return false; } } catch (tf::TransformException& ex) { ROS_ERROR_NAMED("objects", "%s", ex.what()); return false; } return true; } void Objects::detectedObjectsCallback(const art_msgs::InstancesArrayConstPtr& msg) { boost::recursive_mutex::scoped_lock lock(mutex_); // remove outdated objects TObjectMap::iterator it; std::vector<std::string> ids_to_remove; for (it = objects_.begin(); it != objects_.end(); ++it) { bool found = false; for (int i = 0; i < msg->instances.size(); i++) { if (msg->instances[i].object_id == it->first) { found = true; break; } } if (!found && !isGrasped(it->first)) { ids_to_remove.push_back(it->first); visual_tools_->cleanupCO(it->first); } } for (int i = 0; i < ids_to_remove.size(); i++) { TObjectMap::iterator it; it = objects_.find(ids_to_remove[i]); objects_.erase(it); } // add and publish currently detected objects for (int i = 0; i < msg->instances.size(); i++) { geometry_msgs::PoseStamped ps; ps.header = msg->header; ps.pose = msg->instances[i].pose; if (!transformPose(ps)) { ROS_WARN_NAMED("objects", "Failed to transform object."); continue; } if (isKnownObject(msg->instances[i].object_id)) { objects_[msg->instances[i].object_id].pose = ps; } else { art_msgs::getObjectType srv; srv.request.name = msg->instances[i].object_type; if (!object_type_srv_.call(srv)) { ROS_ERROR_NAMED("objects", "Failed to call object_type service"); continue; } TObjectInfo obj; obj.object_id = msg->instances[i].object_id; obj.pose = ps; objects_[msg->instances[i].object_id].type = srv.response.object_type; } } if (paused_) return; for (TObjectMap::iterator it = objects_.begin(); it != objects_.end(); ++it) { // do not publish for grasped objects if (isGrasped(it->first)) continue; publishObject(it->first); } } void Objects::publishObject(std::string object_id) { boost::recursive_mutex::scoped_lock lock(mutex_); ROS_DEBUG_NAMED("objects", "Publishing object_id: %s", object_id.c_str()); moveit_msgs::CollisionObject collision_obj; collision_obj.header.stamp = ros::Time::now(); collision_obj.header.frame_id = target_frame_; collision_obj.id = object_id; collision_obj.operation = moveit_msgs::CollisionObject::ADD; // TODO(ZdenekM): param for update? collision_obj.primitives.resize(1); collision_obj.primitives[0] = objects_[object_id].type.bbox; collision_obj.primitive_poses.resize(1); collision_obj.primitive_poses[0] = objects_[object_id].pose.pose; for (int j = 0; j < 3; j++) { visual_tools_->publishCollisionObjectMsg(collision_obj); // ros::Duration(0.1).sleep(); } visual_tools_->publishBlock(objects_[object_id].pose.pose, moveit_visual_tools::BLUE, objects_[object_id].type.bbox.dimensions[0], objects_[object_id].type.bbox.dimensions[1], objects_[object_id].type.bbox.dimensions[2]); } void Objects::setGrasped(std::string object_id, bool grasped) { boost::recursive_mutex::scoped_lock lock(mutex_); if (grasped) { ROS_DEBUG_NAMED("objects", "Setting object_id as grasped: %s", object_id.c_str()); grasped_objects_.insert(object_id); } else { ROS_DEBUG_NAMED("objects", "Setting object_id as not grasped: %s", object_id.c_str()); grasped_objects_.erase(object_id); if (!isKnownObject(object_id)) { visual_tools_->cleanupCO(object_id); } else { publishObject(object_id); } } } } // namespace art_pr2_grasping <commit_msg>art_pr2_grasping: bug (id of object was not stored)<commit_after>// Copyright 2016 Robo@FIT #include "art_pr2_grasping/objects.h" #include <string> #include <vector> #include <set> namespace art_pr2_grasping { Objects::Objects(boost::shared_ptr<tf::TransformListener> tfl, std::string target_frame) { tfl_ = tfl; object_type_srv_ = nh_.serviceClient<art_msgs::getObjectType>("/art/db/object_type/get"); obj_sub_ = nh_.subscribe("/art/object_detector/object_filtered", 1, &Objects::detectedObjectsCallback, this); target_frame_ = target_frame; visual_tools_.reset(new moveit_visual_tools::VisualTools(target_frame_, "markers")); visual_tools_->loadPlanningSceneMonitor(); visual_tools_->setLifetime(10.0); visual_tools_->setMuted(false); visual_tools_->publishRemoveAllCollisionObjects(); paused_ = false; } void Objects::setPaused(bool paused) { boost::recursive_mutex::scoped_lock lock(mutex_); paused_ = paused; if (paused) { TObjectMap::iterator it; for (it = objects_.begin(); it != objects_.end(); ++it) { if (isGrasped(it->first)) continue; visual_tools_->cleanupCO(it->first); } } } void Objects::clear() { boost::recursive_mutex::scoped_lock lock(mutex_); for (std::set<std::string>::iterator i = grasped_objects_.begin(); i != grasped_objects_.end(); ++i) { visual_tools_->cleanupACO(*i); } visual_tools_->publishRemoveAllCollisionObjects(); objects_.clear(); grasped_objects_.clear(); } bool Objects::isKnownObject(std::string id) { boost::recursive_mutex::scoped_lock lock(mutex_); TObjectMap::iterator it = objects_.find(id); return it != objects_.end(); } std::vector<std::string> Objects::getObjects() { boost::recursive_mutex::scoped_lock lock(mutex_); std::vector<std::string> tmp; TObjectMap::iterator it; for (it = objects_.begin(); it != objects_.end(); ++it) { tmp.push_back(it->first); } return tmp; } TObjectInfo Objects::getObject(std::string object_id) { boost::recursive_mutex::scoped_lock lock(mutex_); if (isKnownObject(object_id)) return objects_[object_id]; else throw std::invalid_argument("unknown object_id: " + object_id); } bool Objects::transformPose(geometry_msgs::PoseStamped& ps) { try { if (tfl_->waitForTransform(target_frame_, ps.header.frame_id, ps.header.stamp, ros::Duration(1.0))) { tfl_->transformPose(target_frame_, ps, ps); } else { ROS_ERROR_NAMED("objects", "Transform between %s and %s not available!", target_frame_.c_str(), ps.header.frame_id.c_str()); return false; } } catch (tf::TransformException& ex) { ROS_ERROR_NAMED("objects", "%s", ex.what()); return false; } return true; } void Objects::detectedObjectsCallback(const art_msgs::InstancesArrayConstPtr& msg) { boost::recursive_mutex::scoped_lock lock(mutex_); // remove outdated objects TObjectMap::iterator it; std::vector<std::string> ids_to_remove; for (it = objects_.begin(); it != objects_.end(); ++it) { bool found = false; for (int i = 0; i < msg->instances.size(); i++) { if (msg->instances[i].object_id == it->first) { found = true; break; } } if (!found && !isGrasped(it->first)) { ids_to_remove.push_back(it->first); visual_tools_->cleanupCO(it->first); } } for (int i = 0; i < ids_to_remove.size(); i++) { TObjectMap::iterator it; it = objects_.find(ids_to_remove[i]); objects_.erase(it); } // add and publish currently detected objects for (int i = 0; i < msg->instances.size(); i++) { geometry_msgs::PoseStamped ps; ps.header = msg->header; ps.pose = msg->instances[i].pose; if (!transformPose(ps)) { ROS_WARN_NAMED("objects", "Failed to transform object."); continue; } if (isKnownObject(msg->instances[i].object_id)) { objects_[msg->instances[i].object_id].pose = ps; } else { art_msgs::getObjectType srv; srv.request.name = msg->instances[i].object_type; if (!object_type_srv_.call(srv)) { ROS_ERROR_NAMED("objects", "Failed to call object_type service"); continue; } TObjectInfo obj; obj.object_id = msg->instances[i].object_id; obj.pose = ps; obj.type = srv.response.object_type; objects_[msg->instances[i].object_id] = obj; } } if (paused_) return; for (TObjectMap::iterator it = objects_.begin(); it != objects_.end(); ++it) { // do not publish for grasped objects if (isGrasped(it->first)) continue; publishObject(it->first); } } void Objects::publishObject(std::string object_id) { boost::recursive_mutex::scoped_lock lock(mutex_); ROS_DEBUG_NAMED("objects", "Publishing object_id: %s", object_id.c_str()); moveit_msgs::CollisionObject collision_obj; collision_obj.header.stamp = ros::Time::now(); collision_obj.header.frame_id = target_frame_; collision_obj.id = object_id; collision_obj.operation = moveit_msgs::CollisionObject::ADD; // TODO(ZdenekM): param for update? collision_obj.primitives.resize(1); collision_obj.primitives[0] = objects_[object_id].type.bbox; collision_obj.primitive_poses.resize(1); collision_obj.primitive_poses[0] = objects_[object_id].pose.pose; for (int j = 0; j < 3; j++) { visual_tools_->publishCollisionObjectMsg(collision_obj); // ros::Duration(0.1).sleep(); } visual_tools_->publishBlock(objects_[object_id].pose.pose, moveit_visual_tools::BLUE, objects_[object_id].type.bbox.dimensions[0], objects_[object_id].type.bbox.dimensions[1], objects_[object_id].type.bbox.dimensions[2]); } void Objects::setGrasped(std::string object_id, bool grasped) { boost::recursive_mutex::scoped_lock lock(mutex_); if (grasped) { ROS_DEBUG_NAMED("objects", "Setting object_id as grasped: %s", object_id.c_str()); grasped_objects_.insert(object_id); } else { ROS_DEBUG_NAMED("objects", "Setting object_id as not grasped: %s", object_id.c_str()); grasped_objects_.erase(object_id); if (!isKnownObject(object_id)) { visual_tools_->cleanupCO(object_id); } else { publishObject(object_id); } } } } // namespace art_pr2_grasping <|endoftext|>
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3220 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3220 to 3221<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3221 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3335 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3335 to 3336<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3336 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3432 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3432 to 3433<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3433 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* LICENSE NOTICE Copyright (c) 2009, Frederick Emmott <[email protected]> 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 "ThreadPool.h" #include "Settings.h" #include "ThreadPool_Worker.h" #include <QDebug> namespace FastCgiQt { ThreadPool::ThreadPool(QObject* parent) : QObject(parent) , m_nextWorker(0) , m_threadCount(-1) , m_threads(0) , m_workers(0) { Settings settings; const int threadSetting = settings.value("FastCGI/numberOfThreads", -1).toInt(); if(threadSetting == -1) { m_threadCount = QThread::idealThreadCount(); } else { Q_ASSERT(threadSetting > 0); m_threadCount = threadSetting; } Q_ASSERT(m_threadCount > 0); m_threads = new QThread*[m_threadCount]; m_workers = new Worker*[m_threadCount]; for(int i = 0; i < m_threadCount; ++i) { QThread* thread = new QThread(this); m_threads[i] = thread; thread->start(); Worker* worker = new Worker(0); worker->moveToThread(thread); m_workers[i] = worker; } } ThreadPool::~ThreadPool() { for(int i = 0; i < m_threadCount; ++i) { delete m_threads[i]; delete m_workers[i]; } delete[] m_workers; delete[] m_threads; } void ThreadPool::start(QRunnable* runnable, QObject* payload) { Worker* worker = m_workers[m_nextWorker]; payload->moveToThread(worker->thread()); worker->enqueue(runnable); m_nextWorker = (m_nextWorker + 1) % m_threadCount; } }; <commit_msg>cleanup threads properly on exit - thanks to Hauke Wintjen<commit_after>/* LICENSE NOTICE Copyright (c) 2009, Frederick Emmott <[email protected]> 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 "ThreadPool.h" #include "Settings.h" #include "ThreadPool_Worker.h" #include <QDebug> namespace FastCgiQt { ThreadPool::ThreadPool(QObject* parent) : QObject(parent) , m_nextWorker(0) , m_threadCount(-1) , m_threads(0) , m_workers(0) { Settings settings; const int threadSetting = settings.value("FastCGI/numberOfThreads", -1).toInt(); if(threadSetting == -1) { m_threadCount = QThread::idealThreadCount(); } else { Q_ASSERT(threadSetting > 0); m_threadCount = threadSetting; } Q_ASSERT(m_threadCount > 0); m_threads = new QThread*[m_threadCount]; m_workers = new Worker*[m_threadCount]; for(int i = 0; i < m_threadCount; ++i) { QThread* thread = new QThread(this); m_threads[i] = thread; thread->start(); Worker* worker = new Worker(0); worker->moveToThread(thread); m_workers[i] = worker; } } ThreadPool::~ThreadPool() { for(int i = 0; i < m_threadCount; ++i) { m_threads[i]->quit; m_threads[i]->wait(10000); // 10 seconds delete m_threads[i]; delete m_workers[i]; } delete[] m_workers; delete[] m_threads; } void ThreadPool::start(QRunnable* runnable, QObject* payload) { Worker* worker = m_workers[m_nextWorker]; payload->moveToThread(worker->thread()); worker->enqueue(runnable); m_nextWorker = (m_nextWorker + 1) % m_threadCount; } }; <|endoftext|>
<commit_before>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- * * Quadra, an action puzzle game * Copyright (C) 1998-2000 Ludus Design * * This program 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 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 * 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 <string.h> #include <stdarg.h> #include <stdio.h> #include "config.h" #include "url.h" #include "http_post.h" #include "dict.h" #include "stringtable.h" #include "video.h" #include "qserv.h" RCSID("$Id$") Dword Qserv::http_addr=0; int Qserv::http_port=0; Qserv::Qserv() { req=NULL; status[0]=0; reply=NULL; create_req(); req->add_data_raw("data="); } Qserv::~Qserv() { if(req) delete req; if(reply) delete reply; } bool Qserv::done() { if(!req) return true; if(!req->done()) return false; //Save ip info for future requests Qserv::http_addr = req->gethostaddr(); Qserv::http_port = req->gethostport(); //Parse reply reply=new Dict(); if(!req->getsize()) { strcpy(status, ""); } else { Stringtable st(req->getbuf(), req->getsize()); int i=0; for(i=0; i<st.size(); i++) if(strlen(st.get(i))==0) { //end of HTTP header i++; // Skip blank line if(i>=st.size()) strcpy(status, ""); else { strncpy(status, st.get(i), sizeof(status)-1); status[sizeof(status)-1]=0; i++; // Skip status line } break; } while(i<st.size()) { //msgbox("Qserv::done: adding [%-60.60s]\n", st.get(i)); reply->add(st.get(i)); i++; } } if(!strcmp(status, "Redirect permanent") && reply->find("location")) { //we are being redirected to another qserv server //update the config strncpy(config.info.game_server_address, reply->find("location"), sizeof(config.info.game_server_address)-1); config.info.game_server_address[sizeof(config.info.game_server_address)-1]=0; //clear cache of ip address unless we use a proxy Url proxy(config.info2.proxy_address); if(!strlen(proxy.getHost())) { Qserv::http_addr = 0; Qserv::http_port = 0; } //and retry the query with the same data Buf data = req->get_data(); delete req; delete reply; status[0] = 0; create_req(); req->add_data_raw(data); req->send(); return false; } else { delete req; req=NULL; } msgbox("Qserv::done: done\n"); return true; } void Qserv::add_data(const char *s, ...) { char st[32768]; Textbuf buf; va_list marker; va_start(marker, s); vsprintf(st, s, marker); va_end(marker); Http_request::url_encode(st, buf); req->add_data_raw(buf.get()); } void Qserv::add_data_large(const Textbuf &buf) { req->add_data_raw(buf.get()); } void Qserv::send() { req->add_data_encode("info/language %i\n", config.info.language); req->add_data_encode("info/platform/os %s\n", #if defined(UGS_DIRECTX) "Windows" #elif defined(UGS_LINUX) "Linux i386" #else #error "What platform???" #endif ); if(video_is_dumb) req->add_data_encode("info/platform/display None\n"); else { #if defined(UGS_LINUX) req->add_data_encode("info/platform/display Xlib\n"); #endif #if defined(UGS_DIRECTX) req->add_data_encode("info/platform/display DirectX\n"); #endif } req->send(); } const char *Qserv::get_status() { if(status[0]) return status; else return NULL; } Dict *Qserv::get_reply() { return reply; } bool Qserv::isconnected() const { if(req && req->isconnected()) return true; return false; } Dword Qserv::getnbrecv() const { int val = 0; if(req) { val = req->getsize(); if(val < 0) val = 0; } return val; } void Qserv::create_req() { const char* host; int port; char path[256]; Url url(config.info.game_server_address); if(!url.getPort()) url.setPort(80); if(!strcmp(url.getHost(), "")) url.setHost("quadra.sourceforge.net:80"); if(!strcmp(url.getPath(), "/")) url.setPath("/cgi-bin/qserv.pl"); Url proxy(config.info2.proxy_address); if(!proxy.getPort()) proxy.setPort(80); if(strlen(proxy.getHost())) { //Use proxy info for host and port, and full game server address for path host = proxy.getHost(); port = proxy.getPort(); url.getFull(path); } else { //No proxy configuration, use game server address for everything host = url.getHost(); port = url.getPort(); strcpy(path, url.getPath()); } //Use IP cache if set if(http_addr) req=new Http_post(host, http_addr, http_port, path); else req=new Http_post(host, port, path); } <commit_msg>Put back the quadra_version key in the Qserv client.<commit_after>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- * * Quadra, an action puzzle game * Copyright (C) 1998-2000 Ludus Design * * This program 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 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 * 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 <string.h> #include <stdarg.h> #include <stdio.h> #include "config.h" #include "url.h" #include "http_post.h" #include "dict.h" #include "stringtable.h" #include "video.h" #include "qserv.h" RCSID("$Id$") Dword Qserv::http_addr=0; int Qserv::http_port=0; Qserv::Qserv() { req=NULL; status[0]=0; reply=NULL; create_req(); req->add_data_raw("data="); } Qserv::~Qserv() { if(req) delete req; if(reply) delete reply; } bool Qserv::done() { if(!req) return true; if(!req->done()) return false; //Save ip info for future requests Qserv::http_addr = req->gethostaddr(); Qserv::http_port = req->gethostport(); //Parse reply reply=new Dict(); if(!req->getsize()) { strcpy(status, ""); } else { Stringtable st(req->getbuf(), req->getsize()); int i=0; for(i=0; i<st.size(); i++) if(strlen(st.get(i))==0) { //end of HTTP header i++; // Skip blank line if(i>=st.size()) strcpy(status, ""); else { strncpy(status, st.get(i), sizeof(status)-1); status[sizeof(status)-1]=0; i++; // Skip status line } break; } while(i<st.size()) { //msgbox("Qserv::done: adding [%-60.60s]\n", st.get(i)); reply->add(st.get(i)); i++; } } if(!strcmp(status, "Redirect permanent") && reply->find("location")) { //we are being redirected to another qserv server //update the config strncpy(config.info.game_server_address, reply->find("location"), sizeof(config.info.game_server_address)-1); config.info.game_server_address[sizeof(config.info.game_server_address)-1]=0; //clear cache of ip address unless we use a proxy Url proxy(config.info2.proxy_address); if(!strlen(proxy.getHost())) { Qserv::http_addr = 0; Qserv::http_port = 0; } //and retry the query with the same data Buf data = req->get_data(); delete req; delete reply; status[0] = 0; create_req(); req->add_data_raw(data); req->send(); return false; } else { delete req; req=NULL; } msgbox("Qserv::done: done\n"); return true; } void Qserv::add_data(const char *s, ...) { char st[32768]; Textbuf buf; va_list marker; va_start(marker, s); vsprintf(st, s, marker); va_end(marker); Http_request::url_encode(st, buf); req->add_data_raw(buf.get()); } void Qserv::add_data_large(const Textbuf &buf) { req->add_data_raw(buf.get()); } void Qserv::send() { req->add_data_encode("info/language %i\n", config.info.language); req->add_data_encode("info/quadra_version %i.%i.%i\n", config.major, config.minor, config.patchlevel); req->add_data_encode("info/platform/os %s\n", #if defined(UGS_DIRECTX) "Windows" #elif defined(UGS_LINUX) "Linux i386" #else #error "What platform???" #endif ); if(video_is_dumb) req->add_data_encode("info/platform/display None\n"); else { #if defined(UGS_LINUX) req->add_data_encode("info/platform/display Xlib\n"); #endif #if defined(UGS_DIRECTX) req->add_data_encode("info/platform/display DirectX\n"); #endif } req->send(); } const char *Qserv::get_status() { if(status[0]) return status; else return NULL; } Dict *Qserv::get_reply() { return reply; } bool Qserv::isconnected() const { if(req && req->isconnected()) return true; return false; } Dword Qserv::getnbrecv() const { int val = 0; if(req) { val = req->getsize(); if(val < 0) val = 0; } return val; } void Qserv::create_req() { const char* host; int port; char path[256]; Url url(config.info.game_server_address); if(!url.getPort()) url.setPort(80); if(!strcmp(url.getHost(), "")) url.setHost("quadra.sourceforge.net:80"); if(!strcmp(url.getPath(), "/")) url.setPath("/cgi-bin/qserv.pl"); Url proxy(config.info2.proxy_address); if(!proxy.getPort()) proxy.setPort(80); if(strlen(proxy.getHost())) { //Use proxy info for host and port, and full game server address for path host = proxy.getHost(); port = proxy.getPort(); url.getFull(path); } else { //No proxy configuration, use game server address for everything host = url.getHost(); port = url.getPort(); strcpy(path, url.getPath()); } //Use IP cache if set if(http_addr) req=new Http_post(host, http_addr, http_port, path); else req=new Http_post(host, port, path); } <|endoftext|>
<commit_before>#include "Page.h" #include <math.h> #include "PackageFiles.h" #include "Kernel/OVR_MemBuffer.h" #include "stb_image.h" #include "ImageData.h" #include "Helpers.h" #include "Config.h" namespace OvrMangaroll { const int Page::SEGMENTS = 10; const float Page::HEIGHT = 1.0f; const float Page::RADIUS = 1.0f; Page::~Page(void) { if (_ATexture->GetState() >= TEXTURE_LOADED) { _Geometry.Free(); } _ATexture->Unload(); } Page *Page::GetNext() { return _Next; } void Page::SetPrev(Page *p) { _Prev = p; if (_ATexture->GetState() >= TEXTURE_LOADED) { p->SetHighOffset(_Offset); } } bool Page::IsLoaded() { return _ATexture->GetState() >= TEXTURE_LOADED; } bool Page::IsVisible() { return _DisplayState == DisplayState::VISIBLE; } bool Page::IsTarget(float angle) { if(IsVisible()) { Vector3f pos = Position; pos.y = 0; float zoom = pos.Length(); // 0/0/0 is default. Moves toward the camera when selected float margin = zoom * _AngularWidth * 0.5f; float angularOffset = _AngularOffset - margin; float angularEnd = _AngularOffset + _AngularWidth + margin; //// Calculate the angle of the isosceles triangle //float x = Alg::Clamp(-(_ChordLength * _ChordLength) / (2 * distance * distance), -1.0f, 1.0f); //float angularWidth = acosf(x) * Mathf::RadToDegreeFactor; //if (_Selected) { // LOG("Distance: %.2f Angular Width: %.2f Chord: %.2f, Cos: %.2f", distance, angularWidth, _ChordLength, 1 - (_ChordLength * _ChordLength) / (2 * distance * distance)); //} //if (angularWidth == NAN) return true; //float angularOffset = _AngularOffset - (angularWidth - _AngularWidth) / 2; //float angleEnd = angularOffset + angularWidth; return angle > angularOffset && angle < angularEnd; } return false; } void Page::SetSelected(bool state) { _Selected = state; _SelectionStart = Time::Elapsed; } void Page::UpdateStates(float angle) { _DisplayState = DisplayState::INVISIBLE; float pixelStart = angle * PIXELS_PER_DEGREE - 90 * PIXELS_PER_DEGREE; float pixelEnd = angle * PIXELS_PER_DEGREE + 90 * PIXELS_PER_DEGREE; bool textureLoaded = _ATexture->GetState() >= TEXTURE_LOADED; if(_Positionable) { int left = (_Offset + _Width); bool initialIsVisible = (_Origin == PLACING_BOTTOM || textureLoaded) ? _Offset > pixelStart && _Offset < pixelEnd // Right end within view : _HighOffset > pixelStart && _HighOffset < pixelEnd; // left end within view // "On-Load" if unloaded Load(); // If user's view is inside the valid range... if (initialIsVisible || (textureLoaded && left > pixelStart && left < pixelEnd)) { _DisplayState = DisplayState::VISIBLE; if (_ATexture->GetState() == TEXTURE_UNLOADED) { _ATexture->Load(); } else if (_ATexture->GetState() == TEXTURE_LOADED) { _ATexture->Display(); } } else { // Otherwise - disappear! _DisplayState = DisplayState::INVISIBLE; _ATexture->Hide(); if (_ATexture->GetFutureState() != TEXTURE_UNLOADED) { float degreeStart = _Offset / PIXELS_PER_DEGREE; if (abs(angle - degreeStart) > 720) { _ATexture->Unload(); _Geometry.Free(); _Loaded = false; } } //LOG("DONT DRAW %s", _Path.ToCStr()); } } else { _DisplayState = DisplayState::INVISIBLE; } } void Page::Update(float angle, bool onlyVisual) { if (!onlyVisual) { UpdateStates(angle); } if(_DisplayState == DisplayState::VISIBLE) { if(_Selected) { float radianOffset = Mathf::Pi / 2;// - widthInRadians / 2; // Makes sure this thing is centered radianOffset += DegreeToRad(_AngularOffset); radianOffset += DegreeToRad(_AngularWidth) / 2.0f; float x = cos(radianOffset) * RADIUS; float z = -sin(radianOffset) * RADIUS; if (AppState::Conf->LeftToRight) { z *= -1; } float distance = AppState::Conf->Zoom * 0.7f; Vector3f targetPos = Vector3f(-x, 0.0f, -z) * distance; if (AppState::Conf->Guided) { float maxAngle = atan( (HEIGHT / 2) / RADIUS ); float verticalAngle = Acos(HMD::Direction.ProjectToPlane(Vector3f(0.0f, 1.0f, 0.0f)).Length()); if(HMD::Direction.y < 0) verticalAngle *= -1; float verticalShift = fmax(-1, fmin(1, verticalAngle / maxAngle)); targetPos += (-verticalShift * (HEIGHT / 3) * Vector3f(0, 1, 0)); } LOG("Target Position: %.2f/%.2f/%.2f", targetPos.x, targetPos.y, targetPos.z); LOG("Current Position: %.2f/%.2f/%.2f", Position.x, Position.y, Position.z); Position = Position.Lerp(targetPos, Time::Delta * 10); Touch(); } else { Position = Position.Lerp(Vector3f::ZERO, Time::Delta * 10); Touch(); } } } void Page::Load() { if (!_Loaded && _ATexture->GetState() == TEXTURE_LOADED) { _Loaded = true; // Calculate real width _Width = REFERENCE_HEIGHT / _ATexture->GetHeight() * _ATexture->GetWidth(); _AngularWidth = _Width / PIXELS_PER_DEGREE; _ChordLength = 2 * RADIUS * sinf(_AngularWidth * Mathf::DegreeToRadFactor / 2); if (_Origin == PLACING_TOP) { // Coming from the top! _Offset = _HighOffset - _Width; _AngularOffset = _Offset / PIXELS_PER_DEGREE; } if(_Next != NULL) { _Next->SetOffset(_Offset + _Width); } if (_Prev != NULL) { _Prev->SetHighOffset(_Offset); } LOG("LOADED %s", _Path.ToCStr()); CreateMesh(); if (!_Initialized) { // Only do this once _Progs[0] = ShaderManager::Instance()->Get(PAGE_SHADER_NAME); _Progs[1] = ShaderManager::Instance()->Get(PAGE_SHADER_NAME, PAGE_TRANSPARENT_FRAG_NAME); _uDisplayTime[0] = glGetUniformLocation(_Progs[0]->program, "DisplayTime"); _uDisplayTime[1] = glGetUniformLocation(_Progs[1]->program, "DisplayTime"); _Initialized = true; } _DisplayTime = Time::Elapsed; } } void Page::Reset(void) { _Positionable = false; _Origin = PLACING_NONE; _Offset = 0; _AngularOffset = 0; _HighOffset = 0; _Loaded = false; if (_ATexture->GetState() > TEXTURE_LOADED) { _Geometry.Free(); } _ATexture->Unload(); _DisplayState = DisplayState::INVISIBLE; } void Page::SetOffset(int offset) { if (_Origin == PLACING_NONE) { _Offset = offset; _AngularOffset = _Offset / PIXELS_PER_DEGREE; _Positionable = true; _Origin = PLACING_BOTTOM; } } void Page::SetHighOffset(int offset) { if (_Origin == PLACING_NONE) { _HighOffset = offset; _Positionable = true; _Origin = PLACING_TOP; } } void Page::Draw(const Matrix4f &m) { if(this->_DisplayState == DisplayState::VISIBLE && _ATexture->GetState() == TEXTURE_APPLIED) { this->UpdateModel(); int index = AppState::Conf->Transparent ? 1 : 0; // Draw glUniform1f(_uDisplayTime[index], Time::Elapsed - this->_DisplayTime); //glUniform1f(_uDisplayTime[index], Time::Elapsed - this->_DisplayTime); // ^--- WHY IN THE NAME OF FUCKING JESUS CHRIST DOES THE UNIFORM LOCATION CHANGE HERE?! glUniformMatrix4fv(_Progs[index]->uModel, 1, GL_TRUE, (m * Mat).M[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(_ATexture->GetTarget(), _ATexture->Display()); _Geometry.Draw(); glBindVertexArray( 0 ); glBindTexture(_ATexture->GetTarget(), 0); } } void Page::SetNext(Page *next) { _Next = next; if (_ATexture->GetState() >= TEXTURE_LOADED) { next->SetOffset(_Offset + _Width); } } // Creates a mesh // Precondition: Width is known void Page::CreateMesh(void) { LOG("CREATE MESH %s", _Path.ToCStr()); //_Geometry = GlGeometry::Create(); // Create the quad. VertexAttribs attribs; Array< TriangleIndex > indices; attribs.position.Resize( Page::SEGMENTS * 2 ); attribs.uv0.Resize( Page::SEGMENTS * 2 ); indices.Resize( (Page::SEGMENTS - 1) * 2 * 3 ); // Number of faces * triangles per face * vertices per triangle float widthInRadians = DegreeToRad(_AngularWidth); float radianOffset = Mathf::Pi / 2;// - widthInRadians / 2; // Makes sure this thing is centered radianOffset += DegreeToRad(_AngularOffset); float y0 = -Page::HEIGHT / 2.0f; float y1 = +Page::HEIGHT / 2.0f; int index = 0; int off1 = 0; int off2 = AppState::Conf->LeftToRight ? 2 : 1; int off3 = AppState::Conf->LeftToRight ? 1 : 2; for ( int i = 0; i < Page::SEGMENTS; i++ ) { float progress = (i / float(Page::SEGMENTS - 1)); float x = cos( progress * widthInRadians + radianOffset ) * RADIUS; float z = -sin( progress * widthInRadians + radianOffset) * RADIUS; if (AppState::Conf->LeftToRight) { z *= -1; } attribs.position[i * 2] = Vector3f(x, y0, z); attribs.position[i * 2 + 1] = Vector3f(x, y1, z); //LOG("V1: (%.2f, %.2f, %.2f)", x, y0, z); //LOG("V2: (%.2f, %.2f, %.2f)", x, y1, z); attribs.uv0[i * 2] = Vector2f(1 - progress, 1); attribs.uv0[i * 2 + 1] = Vector2f(1 - progress, 0); if (AppState::Conf->LeftToRight) { attribs.uv0[i * 2].x = 1 - attribs.uv0[i * 2].x; attribs.uv0[i * 2+1].x = 1 - attribs.uv0[i * 2+1].x; } if(i > 0) { // Add index // T1 indices[index + off1] = (i * 2 - 1); indices[index + off2] = (i * 2 + 1); indices[index + off3] = (i * 2 - 2); index += 3; // T2 indices[index + off1] = (i * 2 + 1); indices[index + off2] = (i * 2); indices[index + off3] = (i * 2 - 2); index += 3; } } _Geometry.Create(attribs, indices); } } <commit_msg>Remove obsolete comment.<commit_after>#include "Page.h" #include <math.h> #include "PackageFiles.h" #include "Kernel/OVR_MemBuffer.h" #include "stb_image.h" #include "ImageData.h" #include "Helpers.h" #include "Config.h" namespace OvrMangaroll { const int Page::SEGMENTS = 10; const float Page::HEIGHT = 1.0f; const float Page::RADIUS = 1.0f; Page::~Page(void) { if (_ATexture->GetState() >= TEXTURE_LOADED) { _Geometry.Free(); } _ATexture->Unload(); } Page *Page::GetNext() { return _Next; } void Page::SetPrev(Page *p) { _Prev = p; if (_ATexture->GetState() >= TEXTURE_LOADED) { p->SetHighOffset(_Offset); } } bool Page::IsLoaded() { return _ATexture->GetState() >= TEXTURE_LOADED; } bool Page::IsVisible() { return _DisplayState == DisplayState::VISIBLE; } bool Page::IsTarget(float angle) { if(IsVisible()) { Vector3f pos = Position; pos.y = 0; float zoom = pos.Length(); // 0/0/0 is default. Moves toward the camera when selected float margin = zoom * _AngularWidth * 0.5f; float angularOffset = _AngularOffset - margin; float angularEnd = _AngularOffset + _AngularWidth + margin; //// Calculate the angle of the isosceles triangle //float x = Alg::Clamp(-(_ChordLength * _ChordLength) / (2 * distance * distance), -1.0f, 1.0f); //float angularWidth = acosf(x) * Mathf::RadToDegreeFactor; //if (_Selected) { // LOG("Distance: %.2f Angular Width: %.2f Chord: %.2f, Cos: %.2f", distance, angularWidth, _ChordLength, 1 - (_ChordLength * _ChordLength) / (2 * distance * distance)); //} //if (angularWidth == NAN) return true; //float angularOffset = _AngularOffset - (angularWidth - _AngularWidth) / 2; //float angleEnd = angularOffset + angularWidth; return angle > angularOffset && angle < angularEnd; } return false; } void Page::SetSelected(bool state) { _Selected = state; _SelectionStart = Time::Elapsed; } void Page::UpdateStates(float angle) { _DisplayState = DisplayState::INVISIBLE; float pixelStart = angle * PIXELS_PER_DEGREE - 90 * PIXELS_PER_DEGREE; float pixelEnd = angle * PIXELS_PER_DEGREE + 90 * PIXELS_PER_DEGREE; bool textureLoaded = _ATexture->GetState() >= TEXTURE_LOADED; if(_Positionable) { int left = (_Offset + _Width); bool initialIsVisible = (_Origin == PLACING_BOTTOM || textureLoaded) ? _Offset > pixelStart && _Offset < pixelEnd // Right end within view : _HighOffset > pixelStart && _HighOffset < pixelEnd; // left end within view // "On-Load" if unloaded Load(); // If user's view is inside the valid range... if (initialIsVisible || (textureLoaded && left > pixelStart && left < pixelEnd)) { _DisplayState = DisplayState::VISIBLE; if (_ATexture->GetState() == TEXTURE_UNLOADED) { _ATexture->Load(); } else if (_ATexture->GetState() == TEXTURE_LOADED) { _ATexture->Display(); } } else { // Otherwise - disappear! _DisplayState = DisplayState::INVISIBLE; _ATexture->Hide(); if (_ATexture->GetFutureState() != TEXTURE_UNLOADED) { float degreeStart = _Offset / PIXELS_PER_DEGREE; if (abs(angle - degreeStart) > 720) { _ATexture->Unload(); _Geometry.Free(); _Loaded = false; } } //LOG("DONT DRAW %s", _Path.ToCStr()); } } else { _DisplayState = DisplayState::INVISIBLE; } } void Page::Update(float angle, bool onlyVisual) { if (!onlyVisual) { UpdateStates(angle); } if(_DisplayState == DisplayState::VISIBLE) { if(_Selected) { float radianOffset = Mathf::Pi / 2;// - widthInRadians / 2; // Makes sure this thing is centered radianOffset += DegreeToRad(_AngularOffset); radianOffset += DegreeToRad(_AngularWidth) / 2.0f; float x = cos(radianOffset) * RADIUS; float z = -sin(radianOffset) * RADIUS; if (AppState::Conf->LeftToRight) { z *= -1; } float distance = AppState::Conf->Zoom * 0.7f; Vector3f targetPos = Vector3f(-x, 0.0f, -z) * distance; if (AppState::Conf->Guided) { float maxAngle = atan( (HEIGHT / 2) / RADIUS ); float verticalAngle = Acos(HMD::Direction.ProjectToPlane(Vector3f(0.0f, 1.0f, 0.0f)).Length()); if(HMD::Direction.y < 0) verticalAngle *= -1; float verticalShift = fmax(-1, fmin(1, verticalAngle / maxAngle)); targetPos += (-verticalShift * (HEIGHT / 3) * Vector3f(0, 1, 0)); } LOG("Target Position: %.2f/%.2f/%.2f", targetPos.x, targetPos.y, targetPos.z); LOG("Current Position: %.2f/%.2f/%.2f", Position.x, Position.y, Position.z); Position = Position.Lerp(targetPos, Time::Delta * 10); Touch(); } else { Position = Position.Lerp(Vector3f::ZERO, Time::Delta * 10); Touch(); } } } void Page::Load() { if (!_Loaded && _ATexture->GetState() == TEXTURE_LOADED) { _Loaded = true; // Calculate real width _Width = REFERENCE_HEIGHT / _ATexture->GetHeight() * _ATexture->GetWidth(); _AngularWidth = _Width / PIXELS_PER_DEGREE; _ChordLength = 2 * RADIUS * sinf(_AngularWidth * Mathf::DegreeToRadFactor / 2); if (_Origin == PLACING_TOP) { // Coming from the top! _Offset = _HighOffset - _Width; _AngularOffset = _Offset / PIXELS_PER_DEGREE; } if(_Next != NULL) { _Next->SetOffset(_Offset + _Width); } if (_Prev != NULL) { _Prev->SetHighOffset(_Offset); } LOG("LOADED %s", _Path.ToCStr()); CreateMesh(); if (!_Initialized) { // Only do this once _Progs[0] = ShaderManager::Instance()->Get(PAGE_SHADER_NAME); _Progs[1] = ShaderManager::Instance()->Get(PAGE_SHADER_NAME, PAGE_TRANSPARENT_FRAG_NAME); _uDisplayTime[0] = glGetUniformLocation(_Progs[0]->program, "DisplayTime"); _uDisplayTime[1] = glGetUniformLocation(_Progs[1]->program, "DisplayTime"); _Initialized = true; } _DisplayTime = Time::Elapsed; } } void Page::Reset(void) { _Positionable = false; _Origin = PLACING_NONE; _Offset = 0; _AngularOffset = 0; _HighOffset = 0; _Loaded = false; if (_ATexture->GetState() > TEXTURE_LOADED) { _Geometry.Free(); } _ATexture->Unload(); _DisplayState = DisplayState::INVISIBLE; } void Page::SetOffset(int offset) { if (_Origin == PLACING_NONE) { _Offset = offset; _AngularOffset = _Offset / PIXELS_PER_DEGREE; _Positionable = true; _Origin = PLACING_BOTTOM; } } void Page::SetHighOffset(int offset) { if (_Origin == PLACING_NONE) { _HighOffset = offset; _Positionable = true; _Origin = PLACING_TOP; } } void Page::Draw(const Matrix4f &m) { if(this->_DisplayState == DisplayState::VISIBLE && _ATexture->GetState() == TEXTURE_APPLIED) { this->UpdateModel(); int index = AppState::Conf->Transparent ? 1 : 0; // Draw glUniform1f(_uDisplayTime[index], Time::Elapsed - this->_DisplayTime); glUniformMatrix4fv(_Progs[index]->uModel, 1, GL_TRUE, (m * Mat).M[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(_ATexture->GetTarget(), _ATexture->Display()); _Geometry.Draw(); glBindVertexArray( 0 ); glBindTexture(_ATexture->GetTarget(), 0); } } void Page::SetNext(Page *next) { _Next = next; if (_ATexture->GetState() >= TEXTURE_LOADED) { next->SetOffset(_Offset + _Width); } } // Creates a mesh // Precondition: Width is known void Page::CreateMesh(void) { LOG("CREATE MESH %s", _Path.ToCStr()); //_Geometry = GlGeometry::Create(); // Create the quad. VertexAttribs attribs; Array< TriangleIndex > indices; attribs.position.Resize( Page::SEGMENTS * 2 ); attribs.uv0.Resize( Page::SEGMENTS * 2 ); indices.Resize( (Page::SEGMENTS - 1) * 2 * 3 ); // Number of faces * triangles per face * vertices per triangle float widthInRadians = DegreeToRad(_AngularWidth); float radianOffset = Mathf::Pi / 2;// - widthInRadians / 2; // Makes sure this thing is centered radianOffset += DegreeToRad(_AngularOffset); float y0 = -Page::HEIGHT / 2.0f; float y1 = +Page::HEIGHT / 2.0f; int index = 0; int off1 = 0; int off2 = AppState::Conf->LeftToRight ? 2 : 1; int off3 = AppState::Conf->LeftToRight ? 1 : 2; for ( int i = 0; i < Page::SEGMENTS; i++ ) { float progress = (i / float(Page::SEGMENTS - 1)); float x = cos( progress * widthInRadians + radianOffset ) * RADIUS; float z = -sin( progress * widthInRadians + radianOffset) * RADIUS; if (AppState::Conf->LeftToRight) { z *= -1; } attribs.position[i * 2] = Vector3f(x, y0, z); attribs.position[i * 2 + 1] = Vector3f(x, y1, z); //LOG("V1: (%.2f, %.2f, %.2f)", x, y0, z); //LOG("V2: (%.2f, %.2f, %.2f)", x, y1, z); attribs.uv0[i * 2] = Vector2f(1 - progress, 1); attribs.uv0[i * 2 + 1] = Vector2f(1 - progress, 0); if (AppState::Conf->LeftToRight) { attribs.uv0[i * 2].x = 1 - attribs.uv0[i * 2].x; attribs.uv0[i * 2+1].x = 1 - attribs.uv0[i * 2+1].x; } if(i > 0) { // Add index // T1 indices[index + off1] = (i * 2 - 1); indices[index + off2] = (i * 2 + 1); indices[index + off3] = (i * 2 - 2); index += 3; // T2 indices[index + off1] = (i * 2 + 1); indices[index + off2] = (i * 2); indices[index + off3] = (i * 2 - 2); index += 3; } } _Geometry.Create(attribs, indices); } } <|endoftext|>
<commit_before>/* * Copyright 2012 Coherent Theory LLC * * This program 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, 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 Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "assetoperations_p.h" #include "ratingattributesjob.h" #include <QtCore/QMetaEnum> namespace Bodega { QHash<QString, QList<RatingAttributes> > AssetOperations::RatingsModel::s_ratingAttributesByAssetType; AssetOperations::RatingsModel::RatingsModel(QObject *parent) : QAbstractItemModel(parent), m_session(0) { // set the role names based on the values of the DisplayRoles enum for // the sake of QML QHash<int, QByteArray> roles; QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("DisplayRoles")); for (int i = 0; i < e.keyCount(); ++i) { roles.insert(e.value(i), e.key(i)); } setRoleNames(roles); connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SIGNAL(countChanged())); connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SIGNAL(countChanged())); connect(this, SIGNAL(modelReset()), this, SIGNAL(countChanged())); connect(this, SIGNAL(assetJobChanged()), this, SLOT(fetchRatingAttributes())); } AssetOperations::RatingsModel::~RatingsModel() { } AssetJob *AssetOperations::RatingsModel::assetJob() const { return m_assetJob; } void AssetOperations::RatingsModel::setAssetJob(AssetJob *assetJob) { m_assetJob = assetJob; emit assetJobChanged(); } int AssetOperations::RatingsModel::columnCount(const QModelIndex &parent) const { return 1; } QVariant AssetOperations::RatingsModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= m_ratingAttributes.count()) { return QVariant(); } switch (role) { case Name: { return m_ratingAttributes.at(index.row()).name; } case AttributeId: { return m_ratingAttributes.at(index.row()).id; } case LowDesc: { return m_ratingAttributes.at(index.row()).lowDesc; } case HighDesc: { return m_ratingAttributes.at(index.row()).highDesc; } case AssetType: { return m_ratingAttributes.at(index.row()).assetType; } case RatingsCount: { return findRatingsCount(m_ratingAttributes.at(index.row()).id); } case AverageRating: { return findAverageRating(m_ratingAttributes.at(index.row()).id); } case AllRatings: { return m_allRatings; } default: { return QVariant(); } } } Qt::ItemFlags AssetOperations::RatingsModel::flags(const QModelIndex &index) const { if (index.isValid()) { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } else { return Qt::NoItemFlags; } } bool AssetOperations::RatingsModel::hasChildren(const QModelIndex &parent) const { Q_UNUSED(parent) return false; } QVariant AssetOperations::RatingsModel::headerData(int section, Qt::Orientation orientation, int role) const { return QVariant(); } QModelIndex AssetOperations::RatingsModel::index(int row, int column, const QModelIndex &parent) const { if (column > 0) { return QModelIndex(); } if (row < 0 || row >= m_ratingAttributes.count()) { return QModelIndex(); } return createIndex(row, column); } QMap<int, QVariant> AssetOperations::RatingsModel::itemData(const QModelIndex &index) const { return QMap<int, QVariant>(); } QModelIndex AssetOperations::RatingsModel::parent(const QModelIndex &index) const { return QModelIndex(); } int AssetOperations::RatingsModel::rowCount(const QModelIndex &parent) const { return m_ratingAttributes.size(); } void AssetOperations::RatingsModel::setSession(Session *session) { if (session == m_session) { return; } if (m_session) { //not connected directly, so disconnect everything m_session->disconnect(this); } m_session = session; if (!m_session) { return; } } Session *AssetOperations::RatingsModel::session() const { return m_session; } QString AssetOperations::RatingsModel::findAverageRating(const QString &ratingAttributeId) const { /*foreach(const AssetInfo::AssetInfoRatings &info, assetInfo.ratings) { if (ratingAttributeId == info.attributeId) { return info.averageRating; } }*/ return QString(); } QString AssetOperations::RatingsModel::findRatingsCount(const QString &ratingAttributeId) const { /*foreach(const AssetInfo::AssetInfoRatings &info, assetInfo.ratings) { if (ratingAttributeId == info.attributeId) { return info.ratingsCount; } }*/ return QString(); } void AssetOperations::RatingsModel::fetchRatingAttributes() { beginResetModel(); const QString contentType = m_assetJob->contentType(); if (!contentType.isEmpty()) { if (RatingsModel::s_ratingAttributesByAssetType.contains(contentType)) { m_ratingAttributes = RatingsModel::s_ratingAttributesByAssetType[contentType]; } else { m_ratingAttributes.clear(); RatingAttributesJob *job = m_session->listRatingAttributes(m_assetJob->assetId()); connect(job, SIGNAL(jobFinished(Bodega::NetworkJob *)), this, SLOT(ratingAttributesJobFinished(Bodega::NetworkJob *))); } } endResetModel(); } void AssetOperations::RatingsModel::ratingAttributesJobFinished(Bodega::NetworkJob *) { } } #include "assetoperations_p.moc" <commit_msg>handle the population of the model<commit_after>/* * Copyright 2012 Coherent Theory LLC * * This program 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, 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 Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "assetoperations_p.h" #include "ratingattributesjob.h" #include <QtCore/QMetaEnum> namespace Bodega { QHash<QString, QList<RatingAttributes> > AssetOperations::RatingsModel::s_ratingAttributesByAssetType; AssetOperations::RatingsModel::RatingsModel(QObject *parent) : QAbstractItemModel(parent), m_session(0) { // set the role names based on the values of the DisplayRoles enum for // the sake of QML QHash<int, QByteArray> roles; QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("DisplayRoles")); for (int i = 0; i < e.keyCount(); ++i) { roles.insert(e.value(i), e.key(i)); } setRoleNames(roles); connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SIGNAL(countChanged())); connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SIGNAL(countChanged())); connect(this, SIGNAL(modelReset()), this, SIGNAL(countChanged())); connect(this, SIGNAL(assetJobChanged()), this, SLOT(fetchRatingAttributes())); } AssetOperations::RatingsModel::~RatingsModel() { } AssetJob *AssetOperations::RatingsModel::assetJob() const { return m_assetJob; } void AssetOperations::RatingsModel::setAssetJob(AssetJob *assetJob) { m_assetJob = assetJob; emit assetJobChanged(); } int AssetOperations::RatingsModel::columnCount(const QModelIndex &parent) const { return 1; } QVariant AssetOperations::RatingsModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= m_ratingAttributes.count()) { return QVariant(); } switch (role) { case Name: { return m_ratingAttributes.at(index.row()).name; } case AttributeId: { return m_ratingAttributes.at(index.row()).id; } case LowDesc: { return m_ratingAttributes.at(index.row()).lowDesc; } case HighDesc: { return m_ratingAttributes.at(index.row()).highDesc; } case AssetType: { return m_ratingAttributes.at(index.row()).assetType; } case RatingsCount: { return findRatingsCount(m_ratingAttributes.at(index.row()).id); } case AverageRating: { return findAverageRating(m_ratingAttributes.at(index.row()).id); } case AllRatings: { return m_allRatings; } default: { return QVariant(); } } } Qt::ItemFlags AssetOperations::RatingsModel::flags(const QModelIndex &index) const { if (index.isValid()) { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } else { return Qt::NoItemFlags; } } bool AssetOperations::RatingsModel::hasChildren(const QModelIndex &parent) const { Q_UNUSED(parent) return false; } QVariant AssetOperations::RatingsModel::headerData(int section, Qt::Orientation orientation, int role) const { return QVariant(); } QModelIndex AssetOperations::RatingsModel::index(int row, int column, const QModelIndex &parent) const { if (column > 0) { return QModelIndex(); } if (row < 0 || row >= m_ratingAttributes.count()) { return QModelIndex(); } return createIndex(row, column); } QMap<int, QVariant> AssetOperations::RatingsModel::itemData(const QModelIndex &index) const { return QMap<int, QVariant>(); } QModelIndex AssetOperations::RatingsModel::parent(const QModelIndex &index) const { return QModelIndex(); } int AssetOperations::RatingsModel::rowCount(const QModelIndex &parent) const { return m_ratingAttributes.size(); } void AssetOperations::RatingsModel::setSession(Session *session) { if (session == m_session) { return; } if (m_session) { //not connected directly, so disconnect everything m_session->disconnect(this); } m_session = session; if (!m_session) { return; } } Session *AssetOperations::RatingsModel::session() const { return m_session; } QString AssetOperations::RatingsModel::findAverageRating(const QString &ratingAttributeId) const { /*foreach(const AssetInfo::AssetInfoRatings &info, assetInfo.ratings) { if (ratingAttributeId == info.attributeId) { return info.averageRating; } }*/ return QString(); } QString AssetOperations::RatingsModel::findRatingsCount(const QString &ratingAttributeId) const { /*foreach(const AssetInfo::AssetInfoRatings &info, assetInfo.ratings) { if (ratingAttributeId == info.attributeId) { return info.ratingsCount; } }*/ return QString(); } void AssetOperations::RatingsModel::fetchRatingAttributes() { beginResetModel(); m_allRatings = 0; m_ratingAttributes.clear(); endResetModel(); const QString contentType = m_assetJob->contentType(); if (!contentType.isEmpty()) { if (RatingsModel::s_ratingAttributesByAssetType.contains(contentType)) { m_ratingAttributes = RatingsModel::s_ratingAttributesByAssetType[contentType]; const int begin = 0; const int end = qMax(begin, m_ratingAttributes.count() -1); beginInsertRows(QModelIndex(), begin, end); endInsertRows(); } else { m_ratingAttributes.clear(); RatingAttributesJob *job = m_session->listRatingAttributes(m_assetJob->assetId()); connect(job, SIGNAL(jobFinished(Bodega::NetworkJob *)), this, SLOT(ratingAttributesJobFinished(Bodega::NetworkJob *))); } } } void AssetOperations::RatingsModel::ratingAttributesJobFinished(Bodega::NetworkJob *job) { RatingAttributesJob *ratingAttributesJob = qobject_cast<RatingAttributesJob*>(job); if (!ratingAttributesJob) { return; } ratingAttributesJob->deleteLater(); if (ratingAttributesJob->failed()) { return; } const int begin = 0; const int end = qMax(begin, ratingAttributesJob->ratingAttributes().count() -1); beginInsertRows(QModelIndex(), begin, end); m_ratingAttributes = ratingAttributesJob->ratingAttributes(); RatingsModel::s_ratingAttributesByAssetType.insert(m_assetJob->contentType(), m_ratingAttributes); endInsertRows(); } } #include "assetoperations_p.moc" <|endoftext|>
<commit_before> #define EIGEN_INTERNAL_DEBUG_CACHE_QUERY #include <iostream> #include "../Eigen/Core" using namespace Eigen; using namespace std; #define DUMP_CPUID(CODE) {\ int abcd[4]; \ abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0;\ EIGEN_CPUID(abcd, CODE, 0); \ std::cout << "The code " << CODE << " gives " \ << (int*)(abcd[0]) << " " << (int*)(abcd[1]) << " " \ << (int*)(abcd[2]) << " " << (int*)(abcd[3]) << " " << std::endl; \ } int main() { cout << "Eigen's L1 = " << ei_queryL1CacheSize() << endl; cout << "Eigen's L2/L3 = " << ei_queryTopLevelCacheSize() << endl; int l1, l2, l3; ei_queryCacheSizes(l1, l2, l3); cout << "Eigen's L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; #ifdef EIGEN_CPUID ei_queryCacheSizes_intel(l1, l2, l3); cout << "Eigen's intel L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; ei_queryCacheSizes_amd(l1, l2, l3); cout << "Eigen's amd L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; int abcd[4]; int string[8]; char* string_char = (char*)(string); // vendor ID EIGEN_CPUID(abcd,0x0,0); string[0] = abcd[1]; string[1] = abcd[3]; string[2] = abcd[2]; string[3] = 0; cout << "vendor id = " << string_char << endl; // dump Intel direct method { l1 = l2 = l3 = 0; int cache_id = 0; int cache_type = 0; do { abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0; EIGEN_CPUID(abcd,0x4,cache_id); cache_type = (abcd[0] & 0x0F) >> 0; int cache_level = (abcd[0] & 0xE0) >> 5; // A[7:5] int ways = (abcd[1] & 0xFFC00000) >> 22; // B[31:22] int partitions = (abcd[1] & 0x003FF000) >> 12; // B[21:12] int line_size = (abcd[1] & 0x00000FFF) >> 0; // B[11:0] int sets = (abcd[2]); // C[31:0] int cache_size = (ways+1) * (partitions+1) * (line_size+1) * (sets+1); cout << "cache[" << cache_id << "].type = " << cache_type << "\n"; cout << "cache[" << cache_id << "].level = " << cache_level << "\n"; cout << "cache[" << cache_id << "].ways = " << ways << "\n"; cout << "cache[" << cache_id << "].partitions = " << partitions << "\n"; cout << "cache[" << cache_id << "].line_size = " << line_size << "\n"; cout << "cache[" << cache_id << "].sets = " << sets << "\n"; cout << "cache[" << cache_id << "].size = " << cache_size << "\n"; cache_id++; } while(cache_type>0); } // dump everything std::cout << endl <<"Raw dump:" << endl; DUMP_CPUID(0x0); DUMP_CPUID(0x1); DUMP_CPUID(0x2); DUMP_CPUID(0x3); DUMP_CPUID(0x4); DUMP_CPUID(0x5); DUMP_CPUID(0x6); DUMP_CPUID(0x80000000); DUMP_CPUID(0x80000001); DUMP_CPUID(0x80000002); DUMP_CPUID(0x80000003); DUMP_CPUID(0x80000004); DUMP_CPUID(0x80000005); DUMP_CPUID(0x80000006); DUMP_CPUID(0x80000007); DUMP_CPUID(0x80000008); #else cout << "EIGEN_CPUID is not defined" << endl; #endif return 0; } #if 0 #define FOO(CODE) { \ EIGEN_CPUID(abcd, CODE); \ std::cout << "The code " << CODE << " gives " \ << (int*)(abcd[0]) << " " << (int*)(abcd[1]) << " " \ << (int*)(abcd[2]) << " " << (int*)(abcd[3]) << " " << std::endl; \ } int abcd[5]; abcd[4] = 0; // for (int a = 0; a < 5; a++) { // cpuid(abcd,a); // std::cout << "The code " << a << " gives " // << abcd[0] << " " << abcd[1] << " " // << abcd[2] << " " << abcd[3] << " " << abcd[4] << std::endl; // } FOO(0x1); std::cerr << (char*)abcd << "\n"; FOO(0x2); FOO(0x2); FOO(0x2); FOO(0x3); std::cerr << (char*)abcd << "\n"; FOO(0x80000002); std::cerr << (char*)abcd << "\n"; FOO(0x80000003); std::cerr << (char*)abcd << "\n"; FOO(0x80000004); std::cerr << (char*)abcd << "\n"; FOO(0x80000005); std::cerr << (char*)abcd << "\n"; FOO(0x80000006); std::cerr << (char*)(abcd) << "\n"; std::cerr << "L2 : " << (abcd[2] >> 16) << "KB\n"; // FOO(0x80000019); std::cerr << (char*)(abcd) << "\n"; FOO(0x8000001A); std::cerr << (char*)(abcd) << "\n"; #endif<commit_msg>add the manual Intel's way to query cache info<commit_after> #define EIGEN_INTERNAL_DEBUG_CACHE_QUERY #include <iostream> #include "../Eigen/Core" using namespace Eigen; using namespace std; #define DUMP_CPUID(CODE) {\ int abcd[4]; \ abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0;\ EIGEN_CPUID(abcd, CODE, 0); \ std::cout << "The code " << CODE << " gives " \ << (int*)(abcd[0]) << " " << (int*)(abcd[1]) << " " \ << (int*)(abcd[2]) << " " << (int*)(abcd[3]) << " " << std::endl; \ } int main() { cout << "Eigen's L1 = " << ei_queryL1CacheSize() << endl; cout << "Eigen's L2/L3 = " << ei_queryTopLevelCacheSize() << endl; int l1, l2, l3; ei_queryCacheSizes(l1, l2, l3); cout << "Eigen's L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; #ifdef EIGEN_CPUID ei_queryCacheSizes_intel(l1, l2, l3); cout << "Eigen's intel L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; ei_queryCacheSizes_amd(l1, l2, l3); cout << "Eigen's amd L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; int abcd[4]; int string[8]; char* string_char = (char*)(string); // vendor ID EIGEN_CPUID(abcd,0x0,0); string[0] = abcd[1]; string[1] = abcd[3]; string[2] = abcd[2]; string[3] = 0; cout << endl; cout << "vendor id = " << string_char << endl; cout << endl; // dump Intel direct method { l1 = l2 = l3 = 0; int cache_id = 0; int cache_type = 0; do { abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0; EIGEN_CPUID(abcd,0x4,cache_id); cache_type = (abcd[0] & 0x0F) >> 0; int cache_level = (abcd[0] & 0xE0) >> 5; // A[7:5] int ways = (abcd[1] & 0xFFC00000) >> 22; // B[31:22] int partitions = (abcd[1] & 0x003FF000) >> 12; // B[21:12] int line_size = (abcd[1] & 0x00000FFF) >> 0; // B[11:0] int sets = (abcd[2]); // C[31:0] int cache_size = (ways+1) * (partitions+1) * (line_size+1) * (sets+1); cout << "cache[" << cache_id << "].type = " << cache_type << "\n"; cout << "cache[" << cache_id << "].level = " << cache_level << "\n"; cout << "cache[" << cache_id << "].ways = " << ways << "\n"; cout << "cache[" << cache_id << "].partitions = " << partitions << "\n"; cout << "cache[" << cache_id << "].line_size = " << line_size << "\n"; cout << "cache[" << cache_id << "].sets = " << sets << "\n"; cout << "cache[" << cache_id << "].size = " << cache_size << "\n"; cache_id++; } while(cache_type>0); } // manual method for intel { l1 = l2 = l3 = 0; abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0; EIGEN_CPUID(abcd,0x00000002,0); unsigned char * bytes = reinterpret_cast<unsigned char *>(abcd)+2; for(int i=0; i<14; ++i) { switch(bytes[i]) { case 0x0A: l1 = 8; break; // 0Ah data L1 cache, 8 KB, 2 ways, 32 byte lines case 0x0C: l1 = 16; break; // 0Ch data L1 cache, 16 KB, 4 ways, 32 byte lines case 0x0E: l1 = 24; break; // 0Eh data L1 cache, 24 KB, 6 ways, 64 byte lines case 0x10: l1 = 16; break; // 10h data L1 cache, 16 KB, 4 ways, 32 byte lines (IA-64) case 0x15: l1 = 16; break; // 15h code L1 cache, 16 KB, 4 ways, 32 byte lines (IA-64) case 0x2C: l1 = 32; break; // 2Ch data L1 cache, 32 KB, 8 ways, 64 byte lines case 0x30: l1 = 32; break; // 30h code L1 cache, 32 KB, 8 ways, 64 byte lines // 56h L0 data TLB, 4M pages, 4 ways, 16 entries // 57h L0 data TLB, 4K pages, 4 ways, 16 entries // 59h L0 data TLB, 4K pages, fully, 16 entries case 0x60: l1 = 16; break; // 60h data L1 cache, 16 KB, 8 ways, 64 byte lines, sectored case 0x66: l1 = 8; break; // 66h data L1 cache, 8 KB, 4 ways, 64 byte lines, sectored case 0x67: l1 = 16; break; // 67h data L1 cache, 16 KB, 4 ways, 64 byte lines, sectored case 0x68: l1 = 32; break; // 68h data L1 cache, 32 KB, 4 ways, 64 byte lines, sectored // 77h code L1 cache, 16 KB, 4 ways, 64 byte lines, sectored (IA-64) // 96h data L1 TLB, 4K...256M pages, fully, 32 entries (IA-64) case 0x1A: l2 = 96; break; // code and data L2 cache, 96 KB, 6 ways, 64 byte lines (IA-64) case 0x22: l3 = 512; break; // code and data L3 cache, 512 KB, 4 ways (!), 64 byte lines, dual-sectored case 0x23: l3 = 1024; break; // code and data L3 cache, 1024 KB, 8 ways, 64 byte lines, dual-sectored case 0x25: l3 = 2048; break; // code and data L3 cache, 2048 KB, 8 ways, 64 byte lines, dual-sectored case 0x29: l3 = 4096; break; // code and data L3 cache, 4096 KB, 8 ways, 64 byte lines, dual-sectored case 0x39: l2 = 128; break; // code and data L2 cache, 128 KB, 4 ways, 64 byte lines, sectored case 0x3A: l2 = 192; break; // code and data L2 cache, 192 KB, 6 ways, 64 byte lines, sectored case 0x3B: l2 = 128; break; // code and data L2 cache, 128 KB, 2 ways, 64 byte lines, sectored case 0x3C: l2 = 256; break; // code and data L2 cache, 256 KB, 4 ways, 64 byte lines, sectored case 0x3D: l2 = 384; break; // code and data L2 cache, 384 KB, 6 ways, 64 byte lines, sectored case 0x3E: l2 = 512; break; // code and data L2 cache, 512 KB, 4 ways, 64 byte lines, sectored case 0x40: l2 = 0; break; // no integrated L2 cache (P6 core) or L3 cache (P4 core) case 0x41: l2 = 128; break; // code and data L2 cache, 128 KB, 4 ways, 32 byte lines case 0x42: l2 = 256; break; // code and data L2 cache, 256 KB, 4 ways, 32 byte lines case 0x43: l2 = 512; break; // code and data L2 cache, 512 KB, 4 ways, 32 byte lines case 0x44: l2 = 1024; break; // code and data L2 cache, 1024 KB, 4 ways, 32 byte lines case 0x45: l2 = 2048; break; // code and data L2 cache, 2048 KB, 4 ways, 32 byte lines case 0x46: l3 = 4096; break; // code and data L3 cache, 4096 KB, 4 ways, 64 byte lines case 0x47: l3 = 8192; break; // code and data L3 cache, 8192 KB, 8 ways, 64 byte lines case 0x48: l2 = 3072; break; // code and data L2 cache, 3072 KB, 12 ways, 64 byte lines case 0x49: l3 = 4096; break; // code and data L3 cache, 4096 KB, 16 ways, 64 byte lines (P4) or case 0x4A: l3 = 6144; break; // code and data L3 cache, 6144 KB, 12 ways, 64 byte lines case 0x4B: l3 = 8192; break; // code and data L3 cache, 8192 KB, 16 ways, 64 byte lines case 0x4C: l3 = 12288; break; // code and data L3 cache, 12288 KB, 12 ways, 64 byte lines case 0x4D: l3 = 16384; break; // code and data L3 cache, 16384 KB, 16 ways, 64 byte lines case 0x4E: l2 = 6144; break; // code and data L2 cache, 6144 KB, 24 ways, 64 byte lines case 0x78: l2 = 1024; break; // code and data L2 cache, 1024 KB, 4 ways, 64 byte lines case 0x79: l2 = 128; break; // code and data L2 cache, 128 KB, 8 ways, 64 byte lines, dual-sectored case 0x7A: l2 = 256; break; // code and data L2 cache, 256 KB, 8 ways, 64 byte lines, dual-sectored case 0x7B: l2 = 512; break; // code and data L2 cache, 512 KB, 8 ways, 64 byte lines, dual-sectored case 0x7C: l2 = 1024; break; // code and data L2 cache, 1024 KB, 8 ways, 64 byte lines, dual-sectored case 0x7D: l2 = 2048; break; // code and data L2 cache, 2048 KB, 8 ways, 64 byte lines case 0x7E: l2 = 256; break; // code and data L2 cache, 256 KB, 8 ways, 128 byte lines, sect. (IA-64) case 0x7F: l2 = 512; break; // code and data L2 cache, 512 KB, 2 ways, 64 byte lines case 0x80: l2 = 512; break; // code and data L2 cache, 512 KB, 8 ways, 64 byte lines case 0x81: l2 = 128; break; // code and data L2 cache, 128 KB, 8 ways, 32 byte lines case 0x82: l2 = 256; break; // code and data L2 cache, 256 KB, 8 ways, 32 byte lines case 0x83: l2 = 512; break; // code and data L2 cache, 512 KB, 8 ways, 32 byte lines case 0x84: l2 = 1024; break; // code and data L2 cache, 1024 KB, 8 ways, 32 byte lines case 0x85: l2 = 2048; break; // code and data L2 cache, 2048 KB, 8 ways, 32 byte lines case 0x86: l2 = 512; break; // code and data L2 cache, 512 KB, 4 ways, 64 byte lines case 0x87: l2 = 1024; break; // code and data L2 cache, 1024 KB, 8 ways, 64 byte lines case 0x88: l3 = 2048; break; // code and data L3 cache, 2048 KB, 4 ways, 64 byte lines (IA-64) case 0x89: l3 = 4096; break; // code and data L3 cache, 4096 KB, 4 ways, 64 byte lines (IA-64) case 0x8A: l3 = 8192; break; // code and data L3 cache, 8192 KB, 4 ways, 64 byte lines (IA-64) case 0x8D: l3 = 3072; break; // code and data L3 cache, 3072 KB, 12 ways, 128 byte lines (IA-64) case 0x9B: l2 = 1024; break; // data L2 TLB, 4K...256M pages, fully, 96 entries (IA-64) default: break; } } cout << endl; cout << "tedious way l1 = " << l1 << endl; cout << "tedious way l2 = " << l2 << endl; cout << "tedious way l3 = " << l3 << endl; } // dump everything std::cout << endl <<"Raw dump:" << endl; DUMP_CPUID(0x0); DUMP_CPUID(0x1); DUMP_CPUID(0x2); DUMP_CPUID(0x3); DUMP_CPUID(0x4); DUMP_CPUID(0x5); DUMP_CPUID(0x6); DUMP_CPUID(0x80000000); DUMP_CPUID(0x80000001); DUMP_CPUID(0x80000002); DUMP_CPUID(0x80000003); DUMP_CPUID(0x80000004); DUMP_CPUID(0x80000005); DUMP_CPUID(0x80000006); DUMP_CPUID(0x80000007); DUMP_CPUID(0x80000008); #else cout << "EIGEN_CPUID is not defined" << endl; #endif return 0; } <|endoftext|>
<commit_before>#pragma once #include <memory> #include <QtCore/QObject> #include <QtCore/QUuid> #include <QVariant> #include "PortType.hpp" #include "NodeData.hpp" #include "Serializable.hpp" #include "ConnectionState.hpp" #include "ConnectionGeometry.hpp" class QPointF; namespace std { template<> struct hash<QUuid> { inline std::size_t operator()(QUuid const& uid) const { return qHash(uid); } }; } namespace QtNodes { class Node; class NodeData; class ConnectionGraphicsObject; /// class Connection : public QObject , public Serializable { public: /// New Connection is attached to the port of the given Node. /// The port has parameters (portType, portIndex). /// The opposite connection end will require anothre port. Connection(PortType portType, Node& node, PortIndex portIndex); Connection(Node& nodeIn, PortIndex portIndexIn, Node& nodeOut, PortIndex portIndexOut); Connection(const Connection&) = delete; Connection operator=(const Connection&) = delete; ~Connection(); public: QJsonObject save() const override; public: QUuid id() const; /// Remembers the end being dragged. /// Invalidates Node address. /// Grabs mouse. void setRequiredPort(PortType portType); PortType requiredPort() const; void setGraphicsObject(std::unique_ptr<ConnectionGraphicsObject>&& graphics); /// Assigns a node to the required port. /// It is assumed that there is a required port, no extra checks void setNodeToPort(Node& node, PortType portType, PortIndex portIndex); void removeFromNodes() const; public: ConnectionGraphicsObject& getConnectionGraphicsObject() const; ConnectionState const & connectionState() const; ConnectionState& connectionState(); ConnectionGeometry& connectionGeometry(); ConnectionGeometry const& connectionGeometry() const; Node* getNode(PortType portType) const; Node*& getNode(PortType portType); PortIndex getPortIndex(PortType portType) const; void clearNode(PortType portType); NodeDataType dataType() const; public: // data propagation void propagateData(std::shared_ptr<NodeData> nodeData) const; void propagateEmptyData() const; private: QUuid _id; private: Node* _outNode = nullptr; Node* _inNode = nullptr; PortIndex _outPortIndex; PortIndex _inPortIndex; private: ConnectionState _connectionState; ConnectionGeometry _connectionGeometry; std::unique_ptr<ConnectionGraphicsObject> _connectionGraphicsObject; signals: void updated(Connection& conn) const; }; } <commit_msg>Revert "Q_OBJECT macro removed, as it is already in base class"<commit_after>#pragma once #include <memory> #include <QtCore/QObject> #include <QtCore/QUuid> #include <QVariant> #include "PortType.hpp" #include "NodeData.hpp" #include "Serializable.hpp" #include "ConnectionState.hpp" #include "ConnectionGeometry.hpp" class QPointF; namespace std { template<> struct hash<QUuid> { inline std::size_t operator()(QUuid const& uid) const { return qHash(uid); } }; } namespace QtNodes { class Node; class NodeData; class ConnectionGraphicsObject; /// class Connection : public QObject , public Serializable { Q_OBJECT public: /// New Connection is attached to the port of the given Node. /// The port has parameters (portType, portIndex). /// The opposite connection end will require anothre port. Connection(PortType portType, Node& node, PortIndex portIndex); Connection(Node& nodeIn, PortIndex portIndexIn, Node& nodeOut, PortIndex portIndexOut); Connection(const Connection&) = delete; Connection operator=(const Connection&) = delete; ~Connection(); public: QJsonObject save() const override; public: QUuid id() const; /// Remembers the end being dragged. /// Invalidates Node address. /// Grabs mouse. void setRequiredPort(PortType portType); PortType requiredPort() const; void setGraphicsObject(std::unique_ptr<ConnectionGraphicsObject>&& graphics); /// Assigns a node to the required port. /// It is assumed that there is a required port, no extra checks void setNodeToPort(Node& node, PortType portType, PortIndex portIndex); void removeFromNodes() const; public: ConnectionGraphicsObject& getConnectionGraphicsObject() const; ConnectionState const & connectionState() const; ConnectionState& connectionState(); ConnectionGeometry& connectionGeometry(); ConnectionGeometry const& connectionGeometry() const; Node* getNode(PortType portType) const; Node*& getNode(PortType portType); PortIndex getPortIndex(PortType portType) const; void clearNode(PortType portType); NodeDataType dataType() const; public: // data propagation void propagateData(std::shared_ptr<NodeData> nodeData) const; void propagateEmptyData() const; private: QUuid _id; private: Node* _outNode = nullptr; Node* _inNode = nullptr; PortIndex _outPortIndex; PortIndex _inPortIndex; private: ConnectionState _connectionState; ConnectionGeometry _connectionGeometry; std::unique_ptr<ConnectionGraphicsObject> _connectionGraphicsObject; signals: void updated(Connection& conn) const; }; } <|endoftext|>
<commit_before>#include <cstdlib> #include <ctime> #include <iostream> #include <iterator> #include <dariadb.h> #include <algorithm> #include <atomic> #include <cassert> #include <chrono> #include <cmath> #include <cstdlib> #include <ctime> #include <limits> #include <random> #include <thread> #include <utils/fs.h> class BenchCallback : public dariadb::storage::ReaderClb { public: BenchCallback() = default; void call(const dariadb::Meas &m) { if (m.flag != dariadb::Flags::_NO_DATA) { count++; } else { count_ig++; } } size_t count; size_t count_ig; }; void writer_1(dariadb::storage::MeasStorage_ptr ms) { auto m = dariadb::Meas::empty(); dariadb::Time t = dariadb::timeutil::current_time(); for (dariadb::Id i = 0; i < 32768; i += 1) { m.id = i; m.flag = dariadb::Flag(0); m.time = t; m.value = dariadb::Value(i); ms->append(m); t++; } } std::atomic_long writen{0}; dariadb::IdSet _all_id; std::mutex _id_lock; void writer_2(dariadb::Id id_from, size_t id_per_thread, dariadb::storage::MeasStorage_ptr ms) { auto m = dariadb::Meas::empty(); std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<int> uniform_dist(10, 64); size_t max_id = (id_from + id_per_thread); for (dariadb::Id i = id_from; i < max_id; i += 1) { _id_lock.lock(); _all_id.insert(i); _id_lock.unlock(); dariadb::Value v = 1.0; m.id = i; m.flag = dariadb::Flag(0); auto max_rnd = uniform_dist(e1); m.time = 0;//dariadb::timeutil::current_time(); for (dariadb::Time p = 0; p < dariadb::Time(max_rnd); p++) { m.time += 10; m.value = v; ms->append(m); writen++; auto rnd = rand() / double(RAND_MAX); v += rnd; } } } int main(int argc, char *argv[]) { (void)argc; (void)argv; srand(static_cast<unsigned int>(time(NULL))); const std::string storage_path = "testStorage"; const size_t chunk_per_storage = 1024 * 1024; const size_t chunk_size = 256; const dariadb::Time old_mem_chunks = 0; const size_t cap_B = 10; const size_t max_mem_chunks = 0; { // 1. if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } auto raw_ptr = new dariadb::storage::Engine( dariadb::storage::PageManager::Params(storage_path, chunk_per_storage, chunk_size), dariadb::storage::Capacitor::Params(cap_B, storage_path), dariadb::storage::Engine::Limits(old_mem_chunks, max_mem_chunks)); dariadb::storage::MeasStorage_ptr ms{raw_ptr}; auto start = clock(); writer_1(ms); auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "1. insert : " << elapsed << std::endl; } if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } auto raw_ptr_ds = new dariadb::storage::Engine( dariadb::storage::PageManager::Params(storage_path, chunk_per_storage, chunk_size), dariadb::storage::Capacitor::Params(cap_B, storage_path), dariadb::storage::Engine::Limits(old_mem_chunks, max_mem_chunks)); dariadb::storage::MeasStorage_ptr ms{raw_ptr_ds}; { // 2. const size_t threads_count = 1; const size_t id_per_thread = size_t(32768 / threads_count); auto start = clock(); std::vector<std::thread> writers(threads_count); size_t pos = 0; for (size_t i = 0; i < threads_count; i++) { std::thread t{writer_2, id_per_thread * i + 1, id_per_thread, ms}; writers[pos++] = std::move(t); } pos = 0; for (size_t i = 0; i < threads_count; i++) { std::thread t = std::move(writers[pos++]); t.join(); } auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "2. insert : " << elapsed << std::endl; raw_ptr_ds->flush(); } auto queue_sizes = raw_ptr_ds->queue_size(); std::cout << "\r" << " in queue: (p:" << queue_sizes.page << " cap:" << queue_sizes.cap << ")" << std::endl; //{ // /* auto ids=ms->getIds(); // std::cout << "ids.size:"<<ids.size() << std::endl;*/ // std::cout << "read all..." << std::endl; // std::shared_ptr<BenchCallback> clbk{ new BenchCallback() }; // auto start = clock(); // dariadb::storage::QueryInterval qi( // dariadb::IdArray{ _all_id.begin(),_all_id.end() }, // 0, ms->minTime(), ms->maxTime()); // ms->readInterval(qi)->readAll(clbk.get()); // auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC); // std::cout << "readed: " << clbk->count << std::endl; // std::cout << "time: " << elapsed << std::endl; //} { // 3 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist(1, 32767); dariadb::IdArray ids; ids.resize(1); const size_t queries_count = 10;// 32768; dariadb::IdArray rnd_ids(queries_count); std::vector<dariadb::Time> rnd_time(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_ids[i] = uniform_dist(e1); dariadb::Time minT, maxT; bool exists = raw_ptr_ds->minMaxTime(rnd_ids[i], &minT, &maxT); if (!exists) { throw MAKE_EXCEPTION("!exists"); } std::uniform_int_distribution<dariadb::Time> uniform_dist_tmp(minT, maxT); rnd_time[i] = uniform_dist_tmp(e1); } auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; auto start = clock(); for (size_t i = 0; i < queries_count; i++) { ids[0] = rnd_ids[i]; auto t = rnd_time[i]; auto rdr = ms->readInTimePoint(dariadb::storage::QueryTimePoint(ids, 0, t)); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "3. time point: " << elapsed << " readed: " << raw_ptr->count << " ignored: " << raw_ptr->count_ig << std::endl; } { // 4 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist( dariadb::Time(10), dariadb::Time(32)); const size_t queries_count = 1;//32; dariadb::IdArray ids(_all_id.begin(),_all_id.end()); std::vector<dariadb::Time> rnd_time(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_time[i] = uniform_dist(e1); } auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; auto start = clock(); for (size_t i = 0; i < queries_count; i++) { auto t = rnd_time[i]; auto rdr = ms->readInTimePoint(dariadb::storage::QueryTimePoint(ids, 0, t)); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "4. time point: " << elapsed << " readed: " << raw_ptr->count << std::endl; } { // 5 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Time> uniform_dist( dariadb::Time(10), dariadb::Time(32)); auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; const size_t queries_count = 1; std::vector<dariadb::Time> rnd_time_from(queries_count), rnd_time_to(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_time_from[i] = uniform_dist(e1); rnd_time_to[i] = uniform_dist(e1); } dariadb::IdArray all_ids(_all_id.begin(), _all_id.end()); auto start = clock(); for (size_t i = 0; i < queries_count; i++) { auto f = std::min(rnd_time_from[i], rnd_time_to[i]); auto t = std::max(rnd_time_from[i], rnd_time_to[i]); auto rdr = ms->readInterval(dariadb::storage::QueryInterval(all_ids, 0, f, t)); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "5. interval: " << elapsed << " readed: " << raw_ptr->count << std::endl; } { // 6 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Time> uniform_dist( raw_ptr_ds->minTime(), dariadb::timeutil::current_time()); std::uniform_int_distribution<dariadb::Id> uniform_dist_id(1, 32767); const size_t ids_count = size_t(32768 * 0.1); dariadb::IdArray ids; ids.resize(ids_count); auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; const size_t queries_count = 2;//32; std::vector<dariadb::Time> rnd_time_from(queries_count), rnd_time_to(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_time_from[i] = uniform_dist(e1); rnd_time_to[i] = uniform_dist(e1); } auto start = clock(); for (size_t i = 0; i < queries_count; i++) { for (size_t j = 0; j < ids_count; j++) { ids[j] = uniform_dist_id(e1); } auto f = std::min(rnd_time_from[i], rnd_time_to[i]); auto t = std::max(rnd_time_from[i], rnd_time_to[i]); auto rdr = ms->readInterval(dariadb::storage::QueryInterval(ids, 0, f, t)); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "6. interval: " << elapsed << " readed: " << raw_ptr->count << std::endl; } ms = nullptr; if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } } <commit_msg>uncomment part of hard_benchmark.<commit_after>#include <cstdlib> #include <ctime> #include <iostream> #include <iterator> #include <dariadb.h> #include <algorithm> #include <atomic> #include <cassert> #include <chrono> #include <cmath> #include <cstdlib> #include <ctime> #include <limits> #include <random> #include <thread> #include <utils/fs.h> class BenchCallback : public dariadb::storage::ReaderClb { public: BenchCallback() = default; void call(const dariadb::Meas &m) { if (m.flag != dariadb::Flags::_NO_DATA) { count++; } else { count_ig++; } } size_t count; size_t count_ig; }; void writer_1(dariadb::storage::MeasStorage_ptr ms) { auto m = dariadb::Meas::empty(); dariadb::Time t = dariadb::timeutil::current_time(); for (dariadb::Id i = 0; i < 32768; i += 1) { m.id = i; m.flag = dariadb::Flag(0); m.time = t; m.value = dariadb::Value(i); ms->append(m); t++; } } std::atomic_long writen{0}; dariadb::IdSet _all_id; std::mutex _id_lock; void writer_2(dariadb::Id id_from, size_t id_per_thread, dariadb::storage::MeasStorage_ptr ms) { auto m = dariadb::Meas::empty(); std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<int> uniform_dist(10, 64); size_t max_id = (id_from + id_per_thread); for (dariadb::Id i = id_from; i < max_id; i += 1) { _id_lock.lock(); _all_id.insert(i); _id_lock.unlock(); dariadb::Value v = 1.0; m.id = i; m.flag = dariadb::Flag(0); auto max_rnd = uniform_dist(e1); m.time = 0;//dariadb::timeutil::current_time(); for (dariadb::Time p = 0; p < dariadb::Time(max_rnd); p++) { m.time += 10; m.value = v; ms->append(m); writen++; auto rnd = rand() / double(RAND_MAX); v += rnd; } } } int main(int argc, char *argv[]) { (void)argc; (void)argv; srand(static_cast<unsigned int>(time(NULL))); const std::string storage_path = "testStorage"; const size_t chunk_per_storage = 1024 * 1024; const size_t chunk_size = 256; const dariadb::Time old_mem_chunks = 0; const size_t cap_B = 10; const size_t max_mem_chunks = 0; { // 1. if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } auto raw_ptr = new dariadb::storage::Engine( dariadb::storage::PageManager::Params(storage_path, chunk_per_storage, chunk_size), dariadb::storage::Capacitor::Params(cap_B, storage_path), dariadb::storage::Engine::Limits(old_mem_chunks, max_mem_chunks)); dariadb::storage::MeasStorage_ptr ms{raw_ptr}; auto start = clock(); writer_1(ms); auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "1. insert : " << elapsed << std::endl; } if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } auto raw_ptr_ds = new dariadb::storage::Engine( dariadb::storage::PageManager::Params(storage_path, chunk_per_storage, chunk_size), dariadb::storage::Capacitor::Params(cap_B, storage_path), dariadb::storage::Engine::Limits(old_mem_chunks, max_mem_chunks)); dariadb::storage::MeasStorage_ptr ms{raw_ptr_ds}; { // 2. const size_t threads_count = 1; const size_t id_per_thread = size_t(32768 / threads_count); auto start = clock(); std::vector<std::thread> writers(threads_count); size_t pos = 0; for (size_t i = 0; i < threads_count; i++) { std::thread t{writer_2, id_per_thread * i + 1, id_per_thread, ms}; writers[pos++] = std::move(t); } pos = 0; for (size_t i = 0; i < threads_count; i++) { std::thread t = std::move(writers[pos++]); t.join(); } auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "2. insert : " << elapsed << std::endl; raw_ptr_ds->flush(); } auto queue_sizes = raw_ptr_ds->queue_size(); std::cout << "\r" << " in queue: (p:" << queue_sizes.page << " cap:" << queue_sizes.cap << ")" << std::endl; //{ // /* auto ids=ms->getIds(); // std::cout << "ids.size:"<<ids.size() << std::endl;*/ // std::cout << "read all..." << std::endl; // std::shared_ptr<BenchCallback> clbk{ new BenchCallback() }; // auto start = clock(); // dariadb::storage::QueryInterval qi( // dariadb::IdArray{ _all_id.begin(),_all_id.end() }, // 0, ms->minTime(), ms->maxTime()); // ms->readInterval(qi)->readAll(clbk.get()); // auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC); // std::cout << "readed: " << clbk->count << std::endl; // std::cout << "time: " << elapsed << std::endl; //} { // 3 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist(1, 32767); dariadb::IdArray ids; ids.resize(1); const size_t queries_count = 32768; dariadb::IdArray rnd_ids(queries_count); std::vector<dariadb::Time> rnd_time(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_ids[i] = uniform_dist(e1); dariadb::Time minT, maxT; bool exists = raw_ptr_ds->minMaxTime(rnd_ids[i], &minT, &maxT); if (!exists) { throw MAKE_EXCEPTION("!exists"); } std::uniform_int_distribution<dariadb::Time> uniform_dist_tmp(minT, maxT); rnd_time[i] = uniform_dist_tmp(e1); } auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; auto start = clock(); for (size_t i = 0; i < queries_count; i++) { ids[0] = rnd_ids[i]; auto t = rnd_time[i]; auto rdr = ms->readInTimePoint(dariadb::storage::QueryTimePoint(ids, 0, t)); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "3. time point: " << elapsed << " readed: " << raw_ptr->count << " ignored: " << raw_ptr->count_ig << std::endl; } { // 4 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist( dariadb::Time(10), dariadb::Time(32)); const size_t queries_count = 1;//32; dariadb::IdArray ids(_all_id.begin(),_all_id.end()); std::vector<dariadb::Time> rnd_time(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_time[i] = uniform_dist(e1); } auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; auto start = clock(); for (size_t i = 0; i < queries_count; i++) { auto t = rnd_time[i]; auto rdr = ms->readInTimePoint(dariadb::storage::QueryTimePoint(ids, 0, t)); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "4. time point: " << elapsed << " readed: " << raw_ptr->count << std::endl; } { // 5 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Time> uniform_dist( dariadb::Time(10), dariadb::Time(32)); auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; const size_t queries_count = 1; std::vector<dariadb::Time> rnd_time_from(queries_count), rnd_time_to(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_time_from[i] = uniform_dist(e1); rnd_time_to[i] = uniform_dist(e1); } dariadb::IdArray all_ids(_all_id.begin(), _all_id.end()); auto start = clock(); for (size_t i = 0; i < queries_count; i++) { auto f = std::min(rnd_time_from[i], rnd_time_to[i]); auto t = std::max(rnd_time_from[i], rnd_time_to[i]); auto rdr = ms->readInterval(dariadb::storage::QueryInterval(all_ids, 0, f, t)); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "5. interval: " << elapsed << " readed: " << raw_ptr->count << std::endl; } { // 6 std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Time> uniform_dist( raw_ptr_ds->minTime(), dariadb::timeutil::current_time()); std::uniform_int_distribution<dariadb::Id> uniform_dist_id(1, 32767); const size_t ids_count = size_t(32768 * 0.1); dariadb::IdArray ids; ids.resize(ids_count); auto raw_ptr = new BenchCallback(); dariadb::storage::ReaderClb_ptr clbk{raw_ptr}; const size_t queries_count = 2;//32; std::vector<dariadb::Time> rnd_time_from(queries_count), rnd_time_to(queries_count); for (size_t i = 0; i < queries_count; i++) { rnd_time_from[i] = uniform_dist(e1); rnd_time_to[i] = uniform_dist(e1); } auto start = clock(); for (size_t i = 0; i < queries_count; i++) { for (size_t j = 0; j < ids_count; j++) { ids[j] = uniform_dist_id(e1); } auto f = std::min(rnd_time_from[i], rnd_time_to[i]); auto t = std::max(rnd_time_from[i], rnd_time_to[i]); auto rdr = ms->readInterval(dariadb::storage::QueryInterval(ids, 0, f, t)); rdr->readAll(clbk.get()); } auto elapsed = (((float)clock() - start) / CLOCKS_PER_SEC) / queries_count; std::cout << "6. interval: " << elapsed << " readed: " << raw_ptr->count << std::endl; } ms = nullptr; if (dariadb::utils::fs::path_exists(storage_path)) { dariadb::utils::fs::rm(storage_path); } } <|endoftext|>
<commit_before>#include "src/bitmap.h" #include "src/camera.h" #include "src/math.h" #include "src/timer.h" #include "src/triangle.h" #include "src/utils.h" typedef struct { gfx_Triangle tris[2]; } CubeTexQuad; typedef struct { CubeTexQuad walls[6]; } TexCube; enum DrawModeType { TEX_CUBE, // draw textured cube DEPTH_VALUES, // draw depth buffer values FLAT_COLOR, // draw flat shaded cube DRAWMODE_CNT }; // helper functions void setupCubeTexQuad(CubeTexQuad *q, int qx, int qy, int qw, int qh, uint8_t color, gfx_Bitmap *texture); void setupTexCube(TexCube *c, gfx_Bitmap *texture); void drawCubeTexQuad(const CubeTexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer); void drawTexCube(const TexCube *c, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer); #define ROTATE_CUBE(delta, x, y, z) {\ for(j = 0; j < 6; ++j) \ { \ for(k = 0; k < 2; ++k) \ { \ for(i = 0; i < 3; ++i) \ { \ mth_rotateVecAxisAngle(&cube.walls[j].tris[k].vertices[i].position, delta*dt, x, y, z); \ } \ } \ } \ } // Rotating cube test void testRotatingCube() { uint32_t dt, now, last = 0; const uint16_t *keysPressed; uint8_t defaultPalette[256*3], grayScalePalette[256*3]; TexCube cube; int i, texMapFlipped = 0, cullModeFlipped = 0, depthFuncFlipped = 0; int wireFrameFlipped = 0, drawModeFlipped = 0, rotFlipped = 0; int drawMode = TEX_CUBE; int rotating = 1; gfx_Camera cam; mth_Matrix4 modelViewProj; gfx_Bitmap bmp = gfx_loadBitmap("images/wood.bmp"); gfx_drawBuffer buffer, depthDebug; // main draw buffer where the cube is rendered ALLOC_DRAWBUFFER(buffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH); ASSERT(DRAWBUFFER_VALID(buffer, DB_COLOR | DB_DEPTH), "Out of memory!\n"); buffer.drawOpts.cullMode = FC_BACK; buffer.drawOpts.depthFunc = DF_LESS; // secondary buffer to render depth buffer values ALLOC_DRAWBUFFER(depthDebug, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR); ASSERT(DRAWBUFFER_VALID(depthDebug, DB_COLOR), "Out of memory!\n"); // setup 1ms timer interrupt tmr_start(); // setup camera VEC4(cam.position, 0, 0, 60); VEC4(cam.up, 0, 1, 0); VEC4(cam.right, 1, 0, 0); VEC4(cam.target, 0, 0, -1); // setup the cube setupTexCube(&cube, &bmp); // save default palette and generate grayscale for depth buffer rendering gfx_getPalette(defaultPalette); for(i = 0; i < 768; i += 3) { grayScalePalette[i] = i/3; grayScalePalette[i+1] = i/3; grayScalePalette[i+2] = i/3; } gfx_setPalette(bmp.palette); mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)buffer.width / (float)buffer.height, 0.1f, 500.f); mth_matView(&cam.view, &cam.position, &cam.target, &cam.up); modelViewProj = mth_matMul(&cam.view, &cam.projection); do { int j, k; now = tmr_getMs(); dt = now - last; keysPressed = kbd_getInput(); if(keysPressed[KEY_RIGHT]) ROTATE_CUBE(0.002f, 0.f, 1.f, 0.f); if(keysPressed[KEY_LEFT]) ROTATE_CUBE(-0.002f, 0.f, 1.f, 0.f); if(keysPressed[KEY_UP]) ROTATE_CUBE(0.002f, 1.f, 0.f, 0.f); if(keysPressed[KEY_DOWN]) ROTATE_CUBE(-0.002f, 1.f, 0.f, 0.f); if(keysPressed[KEY_T] && !texMapFlipped) { buffer.drawOpts.drawMode ^= ( DM_PERSPECTIVE | DM_AFFINE); texMapFlipped = 1; } else if(!keysPressed[KEY_T]) texMapFlipped = 0; if(keysPressed[KEY_W] && !wireFrameFlipped) { buffer.drawOpts.drawMode ^= DM_WIREFRAME; wireFrameFlipped = 1; } else if(!keysPressed[KEY_W]) wireFrameFlipped = 0; if(keysPressed[KEY_C] && !cullModeFlipped) { buffer.drawOpts.cullMode = buffer.drawOpts.cullMode == FC_NONE ? FC_BACK : FC_NONE; cullModeFlipped = 1; } else if(!keysPressed[KEY_C]) cullModeFlipped = 0; if(keysPressed[KEY_D] && !depthFuncFlipped && drawMode != DEPTH_VALUES) { buffer.drawOpts.depthFunc = buffer.drawOpts.depthFunc == DF_ALWAYS ? DF_LESS : DF_ALWAYS; depthFuncFlipped = 1; } else if(!keysPressed[KEY_D]) depthFuncFlipped = 0; if(keysPressed[KEY_R] && !rotFlipped) { rotating = ~rotating + 2; rotFlipped = 1; } else if(!keysPressed[KEY_R]) rotFlipped = 0; if(rotating) { ROTATE_CUBE(-0.001f, 1.f, 0.f, 0.f); ROTATE_CUBE(-0.001f, 0.f, 1.f, 0.f); } if(keysPressed[KEY_SPACE] && !drawModeFlipped) { drawMode++; if(drawMode == DRAWMODE_CNT) drawMode = TEX_CUBE; // use image palette in textured cube if(drawMode == TEX_CUBE) { gfx_setPalette(bmp.palette); buffer.drawOpts.drawMode &= ~DM_FLAT; } // viewing depth values requires depth testing to be enabled if(drawMode == DEPTH_VALUES) buffer.drawOpts.depthFunc = DF_LESS; // for flat color reset to default palette if(drawMode == FLAT_COLOR) { gfx_setPalette(defaultPalette); buffer.drawOpts.drawMode |= DM_FLAT; } drawModeFlipped = 1; } else if(!keysPressed[KEY_SPACE]) drawModeFlipped = 0; // clear screen and render the cube! gfx_clrBuffer(&buffer, DB_COLOR | DB_DEPTH); drawTexCube(&cube, &modelViewProj, &buffer); if(drawMode == DEPTH_VALUES) { gfx_setPalette(grayScalePalette); // fill color buffer with depth buffer values and render it in grayscale gfx_clrBufferColor(&depthDebug, 0x80); for(i = 0; i < buffer.width * buffer.height; ++i) { if(buffer.depthBuffer[i]) { uint8_t c = 2.f / buffer.depthBuffer[i]; depthDebug.colorBuffer[i] = 0x80 - (c > 0x7B ? 0x7B : c); } } utl_printf(&depthDebug, 0, 1, 48, 0, "1/Z depth values"); gfx_updateScreen(&depthDebug); } else { utl_printf(&buffer, 0, 1, 15, 0, "[T]exmapping: %s", buffer.drawOpts.drawMode & DM_AFFINE ? "Affine" : "Perspective"); utl_printf(&buffer, 0, 10, 15, 0, "[C]ulling BF: %s", buffer.drawOpts.cullMode == FC_NONE ? "OFF" : "ON"); utl_printf(&buffer, 0, 19, 15, 0, "[D]epth test: %s", buffer.drawOpts.depthFunc == DF_ALWAYS ? "OFF" : "ON"); utl_printf(&buffer, 0, 28, 15, 0, "[W]ireframe : %s", buffer.drawOpts.drawMode & DM_WIREFRAME ? "ON" : "OFF"); gfx_updateScreen(&buffer); } gfx_vSync(); last = now; } while(!keysPressed[KEY_ESC]); tmr_finish(); FREE_DRAWBUFFER(buffer); FREE_DRAWBUFFER(depthDebug); gfx_freeBitmap(&bmp); } /* ***** */ void setupCubeTexQuad(CubeTexQuad *q, int qx, int qy, int qw, int qh, uint8_t color, gfx_Bitmap *texture) { q->tris[0].color = color; q->tris[0].texture = texture; VEC4(q->tris[0].vertices[0].position, qx, qh, 0); q->tris[0].vertices[0].uv.u = 0; q->tris[0].vertices[0].uv.v = 1; VEC4(q->tris[0].vertices[1].position, qw, qy, 0); q->tris[0].vertices[1].uv.u = 1; q->tris[0].vertices[1].uv.v = 0; VEC4(q->tris[0].vertices[2].position, qx, qy, 0); q->tris[0].vertices[2].uv.u = 0; q->tris[0].vertices[2].uv.v = 0; q->tris[1].color = color; q->tris[1].texture = texture; VEC4(q->tris[1].vertices[0].position, qx, qh, 0); q->tris[1].vertices[0].uv.u = 0; q->tris[1].vertices[0].uv.v = 1; VEC4(q->tris[1].vertices[1].position, qw, qh, 0); q->tris[1].vertices[1].uv.u = 1; q->tris[1].vertices[1].uv.v = 1; VEC4(q->tris[1].vertices[2].position, qw, qy, 0); q->tris[1].vertices[2].uv.u = 1; q->tris[1].vertices[2].uv.v = 0; } #define CUBE_SIZE 15 /* ***** */ void setupTexCube(TexCube *c, gfx_Bitmap *texture) { int i, j, k; mth_Matrix4 wallModel; for(i = 0; i < 6; ++i) { float angle = 0.f; mth_Vector4 axis; axis.x = 0.f; axis.y = 0.f; axis.z = 0.f; setupCubeTexQuad(&c->walls[i], -CUBE_SIZE, -CUBE_SIZE, CUBE_SIZE, CUBE_SIZE, i+1, texture); mth_matIdentity(&wallModel); wallModel.m[12] = 0.f; wallModel.m[13] = -CUBE_SIZE; switch(i) { // bottom wall case 0: wallModel.m[13] += 2*CUBE_SIZE; angle = -90.f; axis.x = 1.f; break; // top wall case 1: angle = 90.f; axis.x = 1.f; break; // back wall case 2: wallModel.m[13] += CUBE_SIZE; wallModel.m[14] += -CUBE_SIZE; angle = 180.f; axis.y = 1.f; break; // front wall case 3: wallModel.m[13] += CUBE_SIZE; wallModel.m[14] += CUBE_SIZE; break; // right wall case 4: wallModel.m[12] += CUBE_SIZE; wallModel.m[13] += CUBE_SIZE; angle = 90.f; axis.y = 1.f; break; // left wall case 5: wallModel.m[12] += -CUBE_SIZE; wallModel.m[13] += CUBE_SIZE; angle = -90.f; axis.y = 1.f; break; } for(k = 0; k < 2; ++k) { for(j = 0; j < 3; ++j) { if(axis.x || axis.y || axis.z) mth_rotateVecAxisAngle(&c->walls[i].tris[k].vertices[j].position, angle * M_PI / 180.f, axis.x, axis.y, axis.z); c->walls[i].tris[k].vertices[j].position = mth_matMulVec(&wallModel, &c->walls[i].tris[k].vertices[j].position); } } } } /* ***** */ void drawCubeTexQuad(const CubeTexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer) { gfx_drawTriangle(&q->tris[0], mvp, buffer); gfx_drawTriangle(&q->tris[1], mvp, buffer); } /* ***** */ void drawTexCube(const TexCube *c, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer) { int i; for(i = 0; i < 6; ++i) drawCubeTexQuad(&c->walls[i], mvp, buffer); } <commit_msg>space<commit_after>#include "src/bitmap.h" #include "src/camera.h" #include "src/math.h" #include "src/timer.h" #include "src/triangle.h" #include "src/utils.h" typedef struct { gfx_Triangle tris[2]; } CubeTexQuad; typedef struct { CubeTexQuad walls[6]; } TexCube; enum DrawModeType { TEX_CUBE, // draw textured cube DEPTH_VALUES, // draw depth buffer values FLAT_COLOR, // draw flat shaded cube DRAWMODE_CNT }; // helper functions void setupCubeTexQuad(CubeTexQuad *q, int qx, int qy, int qw, int qh, uint8_t color, gfx_Bitmap *texture); void setupTexCube(TexCube *c, gfx_Bitmap *texture); void drawCubeTexQuad(const CubeTexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer); void drawTexCube(const TexCube *c, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer); #define ROTATE_CUBE(delta, x, y, z) {\ for(j = 0; j < 6; ++j) \ { \ for(k = 0; k < 2; ++k) \ { \ for(i = 0; i < 3; ++i) \ { \ mth_rotateVecAxisAngle(&cube.walls[j].tris[k].vertices[i].position, delta*dt, x, y, z); \ } \ } \ } \ } // Rotating cube test void testRotatingCube() { uint32_t dt, now, last = 0; const uint16_t *keysPressed; uint8_t defaultPalette[256*3], grayScalePalette[256*3]; TexCube cube; int i, texMapFlipped = 0, cullModeFlipped = 0, depthFuncFlipped = 0; int wireFrameFlipped = 0, drawModeFlipped = 0, rotFlipped = 0; int drawMode = TEX_CUBE; int rotating = 1; gfx_Camera cam; mth_Matrix4 modelViewProj; gfx_Bitmap bmp = gfx_loadBitmap("images/wood.bmp"); gfx_drawBuffer buffer, depthDebug; // main draw buffer where the cube is rendered ALLOC_DRAWBUFFER(buffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH); ASSERT(DRAWBUFFER_VALID(buffer, DB_COLOR | DB_DEPTH), "Out of memory!\n"); buffer.drawOpts.cullMode = FC_BACK; buffer.drawOpts.depthFunc = DF_LESS; // secondary buffer to render depth buffer values ALLOC_DRAWBUFFER(depthDebug, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR); ASSERT(DRAWBUFFER_VALID(depthDebug, DB_COLOR), "Out of memory!\n"); // setup 1ms timer interrupt tmr_start(); // setup camera VEC4(cam.position, 0, 0, 60); VEC4(cam.up, 0, 1, 0); VEC4(cam.right, 1, 0, 0); VEC4(cam.target, 0, 0, -1); // setup the cube setupTexCube(&cube, &bmp); // save default palette and generate grayscale for depth buffer rendering gfx_getPalette(defaultPalette); for(i = 0; i < 768; i += 3) { grayScalePalette[i] = i/3; grayScalePalette[i+1] = i/3; grayScalePalette[i+2] = i/3; } gfx_setPalette(bmp.palette); mth_matPerspective(&cam.projection, 75.f * M_PI /180.f, (float)buffer.width / (float)buffer.height, 0.1f, 500.f); mth_matView(&cam.view, &cam.position, &cam.target, &cam.up); modelViewProj = mth_matMul(&cam.view, &cam.projection); do { int j, k; now = tmr_getMs(); dt = now - last; keysPressed = kbd_getInput(); // auto-rotation of the cube if(rotating) { ROTATE_CUBE(-0.001f, 1.f, 0.f, 0.f); ROTATE_CUBE(-0.001f, 0.f, 1.f, 0.f); } if(keysPressed[KEY_RIGHT]) ROTATE_CUBE(0.002f, 0.f, 1.f, 0.f); if(keysPressed[KEY_LEFT]) ROTATE_CUBE(-0.002f, 0.f, 1.f, 0.f); if(keysPressed[KEY_UP]) ROTATE_CUBE(0.002f, 1.f, 0.f, 0.f); if(keysPressed[KEY_DOWN]) ROTATE_CUBE(-0.002f, 1.f, 0.f, 0.f); if(keysPressed[KEY_T] && !texMapFlipped) { buffer.drawOpts.drawMode ^= (DM_PERSPECTIVE | DM_AFFINE); texMapFlipped = 1; } else if(!keysPressed[KEY_T]) texMapFlipped = 0; if(keysPressed[KEY_W] && !wireFrameFlipped) { buffer.drawOpts.drawMode ^= DM_WIREFRAME; wireFrameFlipped = 1; } else if(!keysPressed[KEY_W]) wireFrameFlipped = 0; if(keysPressed[KEY_C] && !cullModeFlipped) { buffer.drawOpts.cullMode = buffer.drawOpts.cullMode == FC_NONE ? FC_BACK : FC_NONE; cullModeFlipped = 1; } else if(!keysPressed[KEY_C]) cullModeFlipped = 0; if(keysPressed[KEY_D] && !depthFuncFlipped && drawMode != DEPTH_VALUES) { buffer.drawOpts.depthFunc = buffer.drawOpts.depthFunc == DF_ALWAYS ? DF_LESS : DF_ALWAYS; depthFuncFlipped = 1; } else if(!keysPressed[KEY_D]) depthFuncFlipped = 0; if(keysPressed[KEY_R] && !rotFlipped) { rotating = ~rotating + 2; rotFlipped = 1; } else if(!keysPressed[KEY_R]) rotFlipped = 0; if(keysPressed[KEY_SPACE] && !drawModeFlipped) { drawMode++; if(drawMode == DRAWMODE_CNT) drawMode = TEX_CUBE; // use image palette in textured cube if(drawMode == TEX_CUBE) { gfx_setPalette(bmp.palette); buffer.drawOpts.drawMode &= ~DM_FLAT; } // viewing depth values requires depth testing to be enabled if(drawMode == DEPTH_VALUES) buffer.drawOpts.depthFunc = DF_LESS; // for flat color reset to default palette if(drawMode == FLAT_COLOR) { gfx_setPalette(defaultPalette); buffer.drawOpts.drawMode |= DM_FLAT; } drawModeFlipped = 1; } else if(!keysPressed[KEY_SPACE]) drawModeFlipped = 0; // clear screen and render the cube! gfx_clrBuffer(&buffer, DB_COLOR | DB_DEPTH); drawTexCube(&cube, &modelViewProj, &buffer); if(drawMode == DEPTH_VALUES) { gfx_setPalette(grayScalePalette); // fill color buffer with depth buffer values and render it in grayscale gfx_clrBufferColor(&depthDebug, 0x80); for(i = 0; i < buffer.width * buffer.height; ++i) { if(buffer.depthBuffer[i]) { uint8_t c = 2.f / buffer.depthBuffer[i]; depthDebug.colorBuffer[i] = 0x80 - (c > 0x7B ? 0x7B : c); } } utl_printf(&depthDebug, 0, 1, 48, 0, "1/Z depth values"); gfx_updateScreen(&depthDebug); } else { utl_printf(&buffer, 0, 1, 15, 0, "[T]exmapping: %s", buffer.drawOpts.drawMode & DM_AFFINE ? "Affine" : "Perspective"); utl_printf(&buffer, 0, 10, 15, 0, "[C]ulling BF: %s", buffer.drawOpts.cullMode == FC_NONE ? "OFF" : "ON"); utl_printf(&buffer, 0, 19, 15, 0, "[D]epth test: %s", buffer.drawOpts.depthFunc == DF_ALWAYS ? "OFF" : "ON"); utl_printf(&buffer, 0, 28, 15, 0, "[W]ireframe : %s", buffer.drawOpts.drawMode & DM_WIREFRAME ? "ON" : "OFF"); gfx_updateScreen(&buffer); } gfx_vSync(); last = now; } while(!keysPressed[KEY_ESC]); tmr_finish(); FREE_DRAWBUFFER(buffer); FREE_DRAWBUFFER(depthDebug); gfx_freeBitmap(&bmp); } /* ***** */ void setupCubeTexQuad(CubeTexQuad *q, int qx, int qy, int qw, int qh, uint8_t color, gfx_Bitmap *texture) { q->tris[0].color = color; q->tris[0].texture = texture; VEC4(q->tris[0].vertices[0].position, qx, qh, 0); q->tris[0].vertices[0].uv.u = 0; q->tris[0].vertices[0].uv.v = 1; VEC4(q->tris[0].vertices[1].position, qw, qy, 0); q->tris[0].vertices[1].uv.u = 1; q->tris[0].vertices[1].uv.v = 0; VEC4(q->tris[0].vertices[2].position, qx, qy, 0); q->tris[0].vertices[2].uv.u = 0; q->tris[0].vertices[2].uv.v = 0; q->tris[1].color = color; q->tris[1].texture = texture; VEC4(q->tris[1].vertices[0].position, qx, qh, 0); q->tris[1].vertices[0].uv.u = 0; q->tris[1].vertices[0].uv.v = 1; VEC4(q->tris[1].vertices[1].position, qw, qh, 0); q->tris[1].vertices[1].uv.u = 1; q->tris[1].vertices[1].uv.v = 1; VEC4(q->tris[1].vertices[2].position, qw, qy, 0); q->tris[1].vertices[2].uv.u = 1; q->tris[1].vertices[2].uv.v = 0; } #define CUBE_SIZE 15 /* ***** */ void setupTexCube(TexCube *c, gfx_Bitmap *texture) { int i, j, k; mth_Matrix4 wallModel; for(i = 0; i < 6; ++i) { float angle = 0.f; mth_Vector4 axis; axis.x = 0.f; axis.y = 0.f; axis.z = 0.f; setupCubeTexQuad(&c->walls[i], -CUBE_SIZE, -CUBE_SIZE, CUBE_SIZE, CUBE_SIZE, i+1, texture); mth_matIdentity(&wallModel); wallModel.m[12] = 0.f; wallModel.m[13] = -CUBE_SIZE; switch(i) { // bottom wall case 0: wallModel.m[13] += 2*CUBE_SIZE; angle = -90.f; axis.x = 1.f; break; // top wall case 1: angle = 90.f; axis.x = 1.f; break; // back wall case 2: wallModel.m[13] += CUBE_SIZE; wallModel.m[14] += -CUBE_SIZE; angle = 180.f; axis.y = 1.f; break; // front wall case 3: wallModel.m[13] += CUBE_SIZE; wallModel.m[14] += CUBE_SIZE; break; // right wall case 4: wallModel.m[12] += CUBE_SIZE; wallModel.m[13] += CUBE_SIZE; angle = 90.f; axis.y = 1.f; break; // left wall case 5: wallModel.m[12] += -CUBE_SIZE; wallModel.m[13] += CUBE_SIZE; angle = -90.f; axis.y = 1.f; break; } for(k = 0; k < 2; ++k) { for(j = 0; j < 3; ++j) { if(axis.x || axis.y || axis.z) mth_rotateVecAxisAngle(&c->walls[i].tris[k].vertices[j].position, angle * M_PI / 180.f, axis.x, axis.y, axis.z); c->walls[i].tris[k].vertices[j].position = mth_matMulVec(&wallModel, &c->walls[i].tris[k].vertices[j].position); } } } } /* ***** */ void drawCubeTexQuad(const CubeTexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer) { gfx_drawTriangle(&q->tris[0], mvp, buffer); gfx_drawTriangle(&q->tris[1], mvp, buffer); } /* ***** */ void drawTexCube(const TexCube *c, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer) { int i; for(i = 0; i < 6; ++i) drawCubeTexQuad(&c->walls[i], mvp, buffer); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go double ** param_mtx = new double *[num_of_ent]; double ** coord_mtx = new double *[num_of_ent]; for (int i = 0; i < num_of_ent; ++i) { coord_mtx[i] = new double[3*COORDIM]; param_mtx[i] = new double[PARAMDIM]; } // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coord_mtx[i][j*3] >> coord_mtx[i][j*3+1] >> coord_mtx[i][j*3+2] >> a >> b >> c; } mytfp >> param_mtx[i][0] >> param_mtx[i][1] >> param_mtx[i][2] >> param_mtx[i][3] >> param_mtx[i][4]; } mytfp.close(); #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coord_mtx[i][j*3] << " " << coord_mtx[i][j*3+1] << " " << coord_mtx[i][j*3+2] << std::endl; } std::cout << param_mtx[i][0] << " " << param_mtx[i][1] << " " << param_mtx[i][2] << " " << param_mtx[i][3] << " " << param_mtx[i][4] << std::endl; } #endif double sum = 1.0e0; double coordm[3*COORDIM]; double hc[3*COORDIM][3*COORDIM]; std::fill_n (coordm, (3*COORDIM), 0.0e0); std::fill_n (&(hc[0][0]), (3*COORDIM)*(3*COORDIM), 0.0e0); for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] += ((coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j])- (sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0); } } } for (int l=0; l<num_of_ent; ++l) { for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] += ((coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j])- (sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0); } } } for (int i=0; i<(3*COORDIM); ++i) for (int j=i+1; j<(3*COORDIM); ++j) if (hc[i][j] != hc[j][i]) std::cout << i << " " << j << " " << hc[i][j] << " ERROR" << std::endl;; #ifdef DEBUG double coordm_d[3*COORDIM]; std::fill_n (coordm_d, (3*COORDIM), 0.0e0); for (int i=0; i<(3*COORDIM); ++i) { for (int l=0; l<num_of_ent; ++l) coordm_d[i] += coord_mtx[l][i]; coordm_d[i] = coordm_d[i] / (double)num_of_ent; //std::cout << coordm_d[i] << " " << coordm[i] << std::endl; } double hc_d[3*COORDIM][3*COORDIM]; std::fill_n (&(hc_d[0][0]), (3*COORDIM)*(3*COORDIM), 0.0e0); for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { for (int l=0; l<num_of_ent; ++l) { hc_d[i][j] += (coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j]); } hc_d[i][j] = hc_d[i][j] / (double)num_of_ent; //std::cout << hc_d[i][j] << " " << hc[i][j] << std::endl; } } arma::mat hca_d = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca_d(i,j) = hc_d[i][j]; arma::vec eigval_d; arma::mat eigvec_d; arma::eig_sym(eigval_d, eigvec_d, hca_d); for (int i=(3*COORDIM-1); i>=0; --i) { std::cout << i+1 << " ==> " << eigval_d(i) << std::endl; } std::cout << "====" << std::endl; #endif arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca(i,j) = hc[i][j]; arma::vec eigval; arma::mat eigvec; arma::eig_sym(eigval, eigvec, hca); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); int j = 1; double totvar = 0.0e0; for (int i=(3*COORDIM-1); i>=0; --i) { if (j <= PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); ++j; std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << " ==> " << eigval(i) << std::endl; } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); hcai = hca.i(); //std::cout << hca * hcai ; // and so on ... double paramm[PARAMDIM]; arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); std::fill_n(coordm, (3*COORDIM), 0.0e0 ); std::fill_n(paramm, PARAMDIM, 0.0e0 ); for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) paramm[i] += (param_mtx[l][i]-paramm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord_mtx[l][i] - coordm[i])* (param_mtx[l][j] - paramm[j])- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += hcai(l,m) * hcap (m,i); std::cout << "C matrix: " << std::endl; std::cout << cmtx; double q[PARAMDIM]; std::fill_n(q, PARAMDIM, 0.0e0 ); //std::cout << cmtx; for (int i=0; i<PARAMDIM; ++i) { q[i] = paramm[i]; for (int j=0; j<(3*COORDIM); ++j) q[i] -= cmtx(i,j)*coordm[j]; } std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q[i] << std::endl; //test back for (int i=0; i<PARAMDIM; ++i) { double p = q[i]; for (int l=0; l<(3*COORDIM); ++l) p += cmtx(i,l)*coord_mtx[0][l]; std::cout << "P " << i+1 << " ==> " << p << std::endl; std::cout << " " << param_mtx[0][i] << std::endl; } // documento Annovi // calcolo matrice di correlazione traccie HC // diagonalizzo HC e determino A, matrice 5 autovettori principali (5 componenti pricipali) // A matrice rotazione che mi permette di calcolare la traslazione usando i paamtri di tracce // simulate. // documento ATLAS // calcolare V e data V calcolare inversa V e quindi C, matrice di rotazione // data C determinare il vettore di traslazione q // c plus q costanti PCA // write constants in a file for (int i = 0; i < num_of_ent; ++i) { delete(coord_mtx[i]); delete(param_mtx[i]); } delete(coord_mtx); delete(param_mtx); return 0; } <commit_msg>bug fix an some extra debug<commit_after>#include <iostream> #include <fstream> #include <string> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go double ** param_mtx = new double *[num_of_ent]; double ** coord_mtx = new double *[num_of_ent]; for (int i = 0; i < num_of_ent; ++i) { coord_mtx[i] = new double[3*COORDIM]; param_mtx[i] = new double[PARAMDIM]; } // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coord_mtx[i][j*3] >> coord_mtx[i][j*3+1] >> coord_mtx[i][j*3+2] >> a >> b >> c; } mytfp >> param_mtx[i][0] >> param_mtx[i][1] >> param_mtx[i][2] >> param_mtx[i][3] >> param_mtx[i][4]; } mytfp.close(); #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coord_mtx[i][j*3] << " " << coord_mtx[i][j*3+1] << " " << coord_mtx[i][j*3+2] << std::endl; } std::cout << param_mtx[i][0] << " " << param_mtx[i][1] << " " << param_mtx[i][2] << " " << param_mtx[i][3] << " " << param_mtx[i][4] << std::endl; } #endif double sum = 1.0e0; double coordm[3*COORDIM]; double hc[3*COORDIM][3*COORDIM]; std::fill_n (coordm, (3*COORDIM), 0.0e0); std::fill_n (&(hc[0][0]), (3*COORDIM)*(3*COORDIM), 0.0e0); for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] += ((coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j])- (sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0); } } } double cstdev[3*COORDIM]; for (int i=0; i<(3*COORDIM); ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(coord_mtx[l][i]); std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << coordm[i] << std::endl; std::cout << "var = " << stats.stddev() << std::endl; cstdev[i] = stats.stddev(); } for (int l=0; l<num_of_ent; ++l) { for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] += ((coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j])- (sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0); } } } /* for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] = hc[i][j]/(cstdev[i]*cstdev[j]); } } */ for (int i=0; i<(3*COORDIM); ++i) for (int j=i+1; j<(3*COORDIM); ++j) if (hc[i][j] != hc[j][i]) std::cout << i << " " << j << " " << hc[i][j] << " ERROR" << std::endl;; #ifdef DEBUG double coordm_d[3*COORDIM]; std::fill_n (coordm_d, (3*COORDIM), 0.0e0); for (int i=0; i<(3*COORDIM); ++i) { for (int l=0; l<num_of_ent; ++l) coordm_d[i] += coord_mtx[l][i]; coordm_d[i] = coordm_d[i] / (double)num_of_ent; //std::cout << coordm_d[i] << " " << coordm[i] << std::endl; } double hc_d[3*COORDIM][3*COORDIM]; std::fill_n (&(hc_d[0][0]), (3*COORDIM)*(3*COORDIM), 0.0e0); for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { for (int l=0; l<num_of_ent; ++l) { hc_d[i][j] += (coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j]); } hc_d[i][j] = hc_d[i][j] / (double)num_of_ent; //std::cout << hc_d[i][j] << " " << hc[i][j] << std::endl; } } arma::mat hca_d = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca_d(i,j) = hc_d[i][j]; arma::vec eigval_d; arma::mat eigvec_d; arma::eig_sym(eigval_d, eigvec_d, hca_d); for (int i=(3*COORDIM-1); i>=0; --i) { std::cout << i+1 << " ==> " << eigval_d(i) << std::endl; } std::cout << "====" << std::endl; #endif arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca(i,j) = hc[i][j]; arma::vec eigval; arma::mat eigvec; arma::eig_sym(eigval, eigvec, hca); #ifdef DEBUG double xnew[3*COORDIM]; std::fill_n (xnew, (3*COORDIM), 0.0e0); for (int l=0; l<num_of_ent; ++l) { for (int i=0; i<(3*COORDIM); ++i) { xnew[i] = 0.0e0; for (int j=0; j<(3*COORDIM); ++j) xnew[i] += eigvec(i, j) * (coord_mtx[l][i] - coordm[i]); } for (int i=0; i<(3*COORDIM); ++i) { std::cout << i << " --> " << xnew[i] << std::endl; } for (int i=0; i<PARAMDIM; ++i) std::cout << " " << param_mtx[i][i] << std::endl; } #endif double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); int j = 1; double totvar = 0.0e0; for (int i=(3*COORDIM-1); i>=0; --i) { if (j <= PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); ++j; std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << " ==> " << eigval(i) << std::endl; } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); hcai = hca.i(); //std::cout << hca * hcai ; //exit(1); // and so on ... double paramm[PARAMDIM]; arma::mat hcap = arma::zeros<arma::mat>(3*COORDIM,PARAMDIM); std::fill_n(coordm, (3*COORDIM), 0.0e0 ); std::fill_n(paramm, PARAMDIM, 0.0e0 ); sum = 1.0e0; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<PARAMDIM; ++i) paramm[i] += (param_mtx[l][i]-paramm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcap(i,j) += ((coord_mtx[l][i] - coordm[i])* (param_mtx[l][j] - paramm[j])- (sum-1.0e0)*hcap(i,j)/sum)/(sum-1.0e0); } } } double pstdev[PARAMDIM]; for (int i=0; i<PARAMDIM; ++i) { arma::running_stat<double> stats; for (int l=0; l<num_of_ent; ++l) stats(param_mtx[l][i]); std::cout << "mean = " << stats.mean() << std::endl; std::cout << " " << paramm[i] << std::endl; std::cout << "var = " << stats.stddev() << std::endl; pstdev[i] = stats.stddev(); } /* for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<PARAMDIM; ++j) hcap(i,j) = hcap(i,j) / (cstdev[i]*pstdev[j]); */ arma::mat cmtx = arma::zeros<arma::mat>(PARAMDIM,3*COORDIM); for (int i=0; i<PARAMDIM; ++i) for (int l=0; l<(3*COORDIM); ++l) for (int m=0; m<(3*COORDIM); ++m) cmtx(i,l) += hcai(l,m) * hcap (m,i); std::cout << "C matrix: " << std::endl; std::cout << cmtx; double q[PARAMDIM]; std::fill_n(q, PARAMDIM, 0.0e0 ); //std::cout << cmtx; for (int i=0; i<PARAMDIM; ++i) { q[i] = paramm[i]; for (int l=0; l<(3*COORDIM); ++l) q[i] -= cmtx(i,l)*coordm[l]; } std::cout << "Q vector: " << std::endl; for (int i=0; i<PARAMDIM; ++i) std::cout << q[i] << std::endl; //test back for (int i=0; i<PARAMDIM; ++i) { double p = q[i]; for (int l=0; l<(3*COORDIM); ++l) p += cmtx(i,l)*coord_mtx[0][l]; std::cout << "P " << i+1 << " ==> " << p << std::endl; std::cout << " " << param_mtx[0][i] << std::endl; } // documento Annovi // calcolo matrice di correlazione traccie HC // diagonalizzo HC e determino A, matrice 5 autovettori principali (5 componenti pricipali) // A matrice rotazione che mi permette di calcolare la traslazione usando i paamtri di tracce // simulate. // documento ATLAS // calcolare V e data V calcolare inversa V e quindi C, matrice di rotazione // data C determinare il vettore di traslazione q // c plus q costanti PCA // write constants in a file for (int i = 0; i < num_of_ent; ++i) { delete(coord_mtx[i]); delete(param_mtx[i]); } delete(coord_mtx); delete(param_mtx); return 0; } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <stdio.h> #include <stdlib.h> #include <process.h> #include <string.h> #include <tchar.h> #include <windows.h> #include <oleacc.h> #include <tlhelp32.h> #include <MinHook.h> #include "hooks.h" #include "inproc.h" #include "ipc.h" #include "msctfhooks.h" #include "userhooks.h" #include "wordhooks.h" typedef struct _HEWK { bool bInstalled; LPCSTR pTargetName; LPVOID pTarget; LPVOID *ppOriginal; LPVOID pDetour; } HEWK, *PHEWK; typedef struct _HOOKEE { PHEWK Hooks; LPCTSTR Name; } HOOKEE, *PHOOKEE; #define HewkEntry(TargetName) \ {false, #TargetName, nullptr, (LPVOID *)(&Original_##TargetName), Detour_##TargetName} static HMODULE g_hDll = nullptr; static CRITICAL_SECTION g_Lock; static bool g_bLockInitialized = false; static volatile bool g_bActive = false; static volatile bool g_bUnloading = false; #define HooksLock() EnterCriticalSection(&g_Lock) #define HooksUnlock() LeaveCriticalSection(&g_Lock) extern "C" volatile LONG g_ThreadsIn = 0; bool ShouldBePresent() { return IsMasterRunning(); } static HEWK hkUSER32[] = { HewkEntry(SendMessageW), {false, nullptr} }; static HOOKEE Hookees[] = { {hkUSER32, TEXT("USER32.DLL")}, {nullptr} }; void InitInproc(); void ShutdownInproc(); bool OnLoad() { if (!ShouldBePresent()) return false; InitInproc(); return true; } bool OnUnload() { if (g_ThreadsIn > 0) { Sleep(250); if (g_ThreadsIn > 0) return false; } ShutdownInproc(); return true; } ULONG Unhook1(LONG iHookee) { ULONG Result, i; PHOOKEE pHookee = &(Hookees[iHookee]); for (Result = i = 0; pHookee->Hooks[i].pTargetName; i++) { PHEWK pHook = &(pHookee->Hooks[i]); if (pHook->bInstalled) { if (MH_RemoveHook(pHook->pTarget) == MH_OK) pHook->bInstalled = false; else Result++; } } return Result; } ULONG Unhook(LONG iHookee) { ULONG Result; HooksLock(); if (iHookee == -1) { for (Result = iHookee = 0; Hookees[iHookee].Hooks; iHookee++) Result += Unhook1(iHookee); } else Result = Unhook1(iHookee); HooksUnlock(); return Result; } ULONG Hook1(LONG iHookee, HMODULE hHookee) { ULONG Result, i; PHOOKEE pHookee = &(Hookees[iHookee]); if (hHookee == nullptr) { hHookee = GetModuleHandle(pHookee->Name); if (hHookee == nullptr) return 0; } for (Result = i = 0; pHookee->Hooks[i].pTargetName; i++) { PHEWK pHook = &(pHookee->Hooks[i]); if (!pHook->bInstalled) { pHook->pTarget = GetProcAddress(hHookee, pHook->pTargetName); if (pHook->pTarget != nullptr && MH_CreateHook(pHook->pTarget, pHook->pDetour, pHook->ppOriginal) == MH_OK && MH_EnableHook(pHook->pTarget) == MH_OK) { pHook->bInstalled = true; Result++; } } } return Result; } ULONG Hook(LONG iHookee, HMODULE hHookee) { ULONG Result; HooksLock(); if (iHookee == -1) { for (Result = iHookee = 0; Hookees[iHookee].Hooks; iHookee++) Result += Hook1(iHookee, hHookee); } else Result = Hook1(iHookee, hHookee); HooksUnlock(); return(Result); } unsigned WINAPI UnhookAndUnload(LPVOID lpv) { bool UnloadNow = false; while (1) { HooksLock(); if (!ShouldBePresent()) { g_bUnloading = true; g_bActive = false; UnloadNow = true; } HooksUnlock(); if (UnloadNow) break; Sleep(127); } while (Unhook(-1)) { Sleep(127); } while (1) { bool UnloadSucceeded = false; HooksLock(); UnloadSucceeded = OnUnload(); HooksUnlock(); if (UnloadSucceeded) break; Sleep(127); } FreeLibraryAndExitThread(g_hDll, 0); return 0; } void CreateUUThread() { HANDLE hThread = (HANDLE)_beginthreadex(nullptr, 0, UnhookAndUnload, nullptr, 0, nullptr); if (hThread) CloseHandle(hThread); } DWORD Attach() { DWORD Result = 0x80000000; HooksLock(); if (g_bUnloading) Result = 0x80000001; else { if (g_bActive) Result = 0; else if (OnLoad()) { TCHAR ModuleFileName[MAX_PATH]; GetModuleFileName(g_hDll, ModuleFileName, ARRAYSIZE(ModuleFileName)); LoadLibrary(ModuleFileName); g_bActive = true; CreateUUThread(); Result = 0; } if (!(Result & 0x80000000)) { Result = Hook(-1, nullptr); } } HooksUnlock(); return Result; } static DWORD g_dwHooksSuspendedTLS = TLS_OUT_OF_INDEXES; bool HooksActive() { if (g_bActive) { LastErrorSave les; return (TlsGetValue(g_dwHooksSuspendedTLS) == 0); } else return false; } HookSuspension::HookSuspension(): _initialized(false) { UINT_PTR currentValue = (UINT_PTR) TlsGetValue(g_dwHooksSuspendedTLS); TlsSetValue(g_dwHooksSuspendedTLS, (LPVOID) (currentValue + 1)); _initialized = true; } HookSuspension::~HookSuspension() { if (_initialized) { UINT_PTR currentValue = (UINT_PTR) TlsGetValue(g_dwHooksSuspendedTLS); TlsSetValue(g_dwHooksSuspendedTLS, (LPVOID) (currentValue - 1)); } } UINT_PTR g_uTimer = 0; void CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { if (g_uTimer != 0) { KillTimer(0, g_uTimer); g_uTimer = 0; } ITfThreadMgr* tm = nullptr; CoCreateInstance(CLSID_TF_ThreadMgr, nullptr, CLSCTX_INPROC_SERVER, IID_ITfThreadMgr, (void**) &tm); if (tm != nullptr) { ITfDocumentMgr* dm = nullptr; tm->GetFocus(&dm); if (dm != nullptr) { OutputDebugString(TEXT("got document manager\n")); ITfContext* ctx = nullptr; dm->GetBase(&ctx); if (ctx != nullptr) { ITfInsertAtSelection* ias = nullptr; ctx->QueryInterface(IID_ITfInsertAtSelection, (void**) &ias); if (ias != nullptr) { MSCTFHooks_HookInsertAtSelection(ias); OutputDebugString(TEXT("hooked ITfInsertAtSelection\n")); ias->Release(); } ctx->Release(); } dm->Release(); } tm->Release(); } } void InitInproc() { if (g_dwHooksSuspendedTLS == TLS_OUT_OF_INDEXES) g_dwHooksSuspendedTLS = TlsAlloc(); MSCTFHooks_Init(); WordHooks_Init(); } void ShutdownInproc() { if (g_uTimer != 0) { KillTimer(0, g_uTimer); g_uTimer = 0; } MSCTFHooks_Shutdown(); WordHooks_Shutdown(); if (g_dwHooksSuspendedTLS != TLS_OUT_OF_INDEXES) { TlsFree(g_dwHooksSuspendedTLS); g_dwHooksSuspendedTLS = TLS_OUT_OF_INDEXES; } } extern "C" void CALLBACK WinEventProc(HWINEVENTHOOK hook, DWORD event, HWND hwnd, long objid, long child, DWORD idThread, DWORD time) { ThreadIn ti; if (idThread != GetCurrentThreadId()) { return; } if (!g_bActive) { Attach(); } if (!g_bActive) { return; } HWND hwndFocus = GetFocus(); if (hwndFocus != nullptr) { TCHAR className[256] = TEXT(""); GetClassName(hwndFocus, className, ARRAYSIZE(className)); if (_tcsicmp(className, TEXT("_wwg")) == 0) { IDispatch* disp = nullptr; HRESULT hr = AccessibleObjectFromWindow(hwnd, OBJID_NATIVEOM, IID_IDispatch, (void**) &disp); if (hr == S_OK && disp != nullptr) { WordHooks_HookIDispatchInvoke(disp); disp->Release(); } } } if (g_uTimer != 0) { KillTimer(0, g_uTimer); g_uTimer = 0; } g_uTimer = SetTimer(0, 0, 100, TimerProc); } static HWINEVENTHOOK g_hForegroundEventHook = nullptr; static HWINEVENTHOOK g_hFocusEventHook = nullptr; bool InstallHooks() { g_hForegroundEventHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, g_hDll, WinEventProc, 0, 0, WINEVENT_INCONTEXT); if (g_hForegroundEventHook == nullptr) { return false; } g_hFocusEventHook = SetWinEventHook(EVENT_OBJECT_FOCUS, EVENT_OBJECT_FOCUS, g_hDll, WinEventProc, 0, 0, WINEVENT_INCONTEXT); if (g_hFocusEventHook == nullptr) { return false; } return true; } void RemoveHooks() { if (g_hFocusEventHook != nullptr) { UnhookWinEvent(g_hFocusEventHook); g_hFocusEventHook = nullptr; } if (g_hForegroundEventHook != nullptr) { UnhookWinEvent(g_hForegroundEventHook); g_hForegroundEventHook = nullptr; } } BOOL APIENTRY DllMain(HMODULE hDll, ULONG ulReason, LPVOID lpRsv) { BOOL Result = TRUE; if (ulReason == DLL_PROCESS_ATTACH) { g_hDll = hDll; InitializeCriticalSection(&g_Lock); g_bLockInitialized = true; MH_Initialize(); DisableThreadLibraryCalls(hDll); } else if (ulReason == DLL_PROCESS_DETACH) { g_bUnloading = true; g_bActive = false; MH_Uninitialize(); if (g_bLockInitialized) { g_bLockInitialized = false; DeleteCriticalSection(&g_Lock); } } return Result; } <commit_msg>Fix a bug that prevented the in-process DLL from unloading<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <stdio.h> #include <stdlib.h> #include <process.h> #include <string.h> #include <tchar.h> #include <windows.h> #include <oleacc.h> #include <tlhelp32.h> #include <MinHook.h> #include "hooks.h" #include "inproc.h" #include "ipc.h" #include "msctfhooks.h" #include "userhooks.h" #include "wordhooks.h" typedef struct _HEWK { bool bInstalled; LPCSTR pTargetName; LPVOID pTarget; LPVOID *ppOriginal; LPVOID pDetour; } HEWK, *PHEWK; typedef struct _HOOKEE { PHEWK Hooks; LPCTSTR Name; } HOOKEE, *PHOOKEE; #define HewkEntry(TargetName) \ {false, #TargetName, nullptr, (LPVOID *)(&Original_##TargetName), Detour_##TargetName} static HMODULE g_hDll = nullptr; static CRITICAL_SECTION g_Lock; static bool g_bLockInitialized = false; static volatile bool g_bActive = false; static volatile bool g_bUnloading = false; #define HooksLock() EnterCriticalSection(&g_Lock) #define HooksUnlock() LeaveCriticalSection(&g_Lock) extern "C" volatile LONG g_ThreadsIn = 0; bool ShouldBePresent() { return IsMasterRunning(); } static HEWK hkUSER32[] = { HewkEntry(SendMessageW), {false, nullptr} }; static HOOKEE Hookees[] = { {hkUSER32, TEXT("USER32.DLL")}, {nullptr} }; void InitInproc(); void ShutdownInproc(); bool OnLoad() { if (!ShouldBePresent()) return false; InitInproc(); return true; } bool OnUnload() { if (g_ThreadsIn > 0) { Sleep(250); if (g_ThreadsIn > 0) return false; } ShutdownInproc(); return true; } ULONG Unhook1(LONG iHookee) { ULONG Result, i; PHOOKEE pHookee = &(Hookees[iHookee]); for (Result = i = 0; pHookee->Hooks[i].pTargetName; i++) { PHEWK pHook = &(pHookee->Hooks[i]); if (pHook->bInstalled) { if (MH_RemoveHook(pHook->pTarget) == MH_OK) pHook->bInstalled = false; else Result++; } } return Result; } ULONG Unhook(LONG iHookee) { ULONG Result; HooksLock(); if (iHookee == -1) { for (Result = iHookee = 0; Hookees[iHookee].Hooks; iHookee++) Result += Unhook1(iHookee); } else Result = Unhook1(iHookee); HooksUnlock(); return Result; } ULONG Hook1(LONG iHookee, HMODULE hHookee) { ULONG Result, i; PHOOKEE pHookee = &(Hookees[iHookee]); if (hHookee == nullptr) { hHookee = GetModuleHandle(pHookee->Name); if (hHookee == nullptr) return 0; } for (Result = i = 0; pHookee->Hooks[i].pTargetName; i++) { PHEWK pHook = &(pHookee->Hooks[i]); if (!pHook->bInstalled) { pHook->pTarget = GetProcAddress(hHookee, pHook->pTargetName); if (pHook->pTarget != nullptr && MH_CreateHook(pHook->pTarget, pHook->pDetour, pHook->ppOriginal) == MH_OK && MH_EnableHook(pHook->pTarget) == MH_OK) { pHook->bInstalled = true; Result++; } } } return Result; } ULONG Hook(LONG iHookee, HMODULE hHookee) { ULONG Result; HooksLock(); if (iHookee == -1) { for (Result = iHookee = 0; Hookees[iHookee].Hooks; iHookee++) Result += Hook1(iHookee, hHookee); } else Result = Hook1(iHookee, hHookee); HooksUnlock(); return(Result); } DWORD WINAPI UnhookAndUnload(LPVOID lpv) { bool UnloadNow = false; while (1) { HooksLock(); if (!ShouldBePresent()) { g_bUnloading = true; g_bActive = false; UnloadNow = true; } HooksUnlock(); if (UnloadNow) break; Sleep(127); } while (Unhook(-1)) { Sleep(127); } while (1) { bool UnloadSucceeded = false; HooksLock(); UnloadSucceeded = OnUnload(); HooksUnlock(); if (UnloadSucceeded) break; Sleep(127); } FreeLibraryAndExitThread(g_hDll, 0); return 0; } void CreateUUThread() { HANDLE hThread = CreateThread(nullptr, 0, UnhookAndUnload, nullptr, 0, nullptr); if (hThread) CloseHandle(hThread); } DWORD Attach() { DWORD Result = 0x80000000; HooksLock(); if (g_bUnloading) Result = 0x80000001; else { if (g_bActive) Result = 0; else if (OnLoad()) { TCHAR ModuleFileName[MAX_PATH]; GetModuleFileName(g_hDll, ModuleFileName, ARRAYSIZE(ModuleFileName)); LoadLibrary(ModuleFileName); g_bActive = true; CreateUUThread(); Result = 0; } if (!(Result & 0x80000000)) { Result = Hook(-1, nullptr); } } HooksUnlock(); return Result; } static DWORD g_dwHooksSuspendedTLS = TLS_OUT_OF_INDEXES; bool HooksActive() { if (g_bActive) { LastErrorSave les; return (TlsGetValue(g_dwHooksSuspendedTLS) == 0); } else return false; } HookSuspension::HookSuspension(): _initialized(false) { UINT_PTR currentValue = (UINT_PTR) TlsGetValue(g_dwHooksSuspendedTLS); TlsSetValue(g_dwHooksSuspendedTLS, (LPVOID) (currentValue + 1)); _initialized = true; } HookSuspension::~HookSuspension() { if (_initialized) { UINT_PTR currentValue = (UINT_PTR) TlsGetValue(g_dwHooksSuspendedTLS); TlsSetValue(g_dwHooksSuspendedTLS, (LPVOID) (currentValue - 1)); } } UINT_PTR g_uTimer = 0; void CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) { if (g_uTimer != 0) { KillTimer(0, g_uTimer); g_uTimer = 0; } ITfThreadMgr* tm = nullptr; CoCreateInstance(CLSID_TF_ThreadMgr, nullptr, CLSCTX_INPROC_SERVER, IID_ITfThreadMgr, (void**) &tm); if (tm != nullptr) { ITfDocumentMgr* dm = nullptr; tm->GetFocus(&dm); if (dm != nullptr) { OutputDebugString(TEXT("got document manager\n")); ITfContext* ctx = nullptr; dm->GetBase(&ctx); if (ctx != nullptr) { ITfInsertAtSelection* ias = nullptr; ctx->QueryInterface(IID_ITfInsertAtSelection, (void**) &ias); if (ias != nullptr) { MSCTFHooks_HookInsertAtSelection(ias); OutputDebugString(TEXT("hooked ITfInsertAtSelection\n")); ias->Release(); } ctx->Release(); } dm->Release(); } tm->Release(); } } void InitInproc() { if (g_dwHooksSuspendedTLS == TLS_OUT_OF_INDEXES) g_dwHooksSuspendedTLS = TlsAlloc(); MSCTFHooks_Init(); WordHooks_Init(); } void ShutdownInproc() { if (g_uTimer != 0) { KillTimer(0, g_uTimer); g_uTimer = 0; } MSCTFHooks_Shutdown(); WordHooks_Shutdown(); if (g_dwHooksSuspendedTLS != TLS_OUT_OF_INDEXES) { TlsFree(g_dwHooksSuspendedTLS); g_dwHooksSuspendedTLS = TLS_OUT_OF_INDEXES; } } extern "C" void CALLBACK WinEventProc(HWINEVENTHOOK hook, DWORD event, HWND hwnd, long objid, long child, DWORD idThread, DWORD time) { ThreadIn ti; if (idThread != GetCurrentThreadId()) { return; } if (!g_bActive) { Attach(); } if (!g_bActive) { return; } HWND hwndFocus = GetFocus(); if (hwndFocus != nullptr) { TCHAR className[256] = TEXT(""); GetClassName(hwndFocus, className, ARRAYSIZE(className)); if (_tcsicmp(className, TEXT("_wwg")) == 0) { IDispatch* disp = nullptr; HRESULT hr = AccessibleObjectFromWindow(hwnd, OBJID_NATIVEOM, IID_IDispatch, (void**) &disp); if (hr == S_OK && disp != nullptr) { WordHooks_HookIDispatchInvoke(disp); disp->Release(); } } } if (g_uTimer != 0) { KillTimer(0, g_uTimer); g_uTimer = 0; } g_uTimer = SetTimer(0, 0, 100, TimerProc); } static HWINEVENTHOOK g_hForegroundEventHook = nullptr; static HWINEVENTHOOK g_hFocusEventHook = nullptr; bool InstallHooks() { g_hForegroundEventHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, g_hDll, WinEventProc, 0, 0, WINEVENT_INCONTEXT); if (g_hForegroundEventHook == nullptr) { return false; } g_hFocusEventHook = SetWinEventHook(EVENT_OBJECT_FOCUS, EVENT_OBJECT_FOCUS, g_hDll, WinEventProc, 0, 0, WINEVENT_INCONTEXT); if (g_hFocusEventHook == nullptr) { return false; } return true; } void RemoveHooks() { if (g_hFocusEventHook != nullptr) { UnhookWinEvent(g_hFocusEventHook); g_hFocusEventHook = nullptr; } if (g_hForegroundEventHook != nullptr) { UnhookWinEvent(g_hForegroundEventHook); g_hForegroundEventHook = nullptr; } } BOOL APIENTRY DllMain(HMODULE hDll, ULONG ulReason, LPVOID lpRsv) { BOOL Result = TRUE; if (ulReason == DLL_PROCESS_ATTACH) { g_hDll = hDll; InitializeCriticalSection(&g_Lock); g_bLockInitialized = true; MH_Initialize(); DisableThreadLibraryCalls(hDll); } else if (ulReason == DLL_PROCESS_DETACH) { g_bUnloading = true; g_bActive = false; MH_Uninitialize(); if (g_bLockInitialized) { g_bLockInitialized = false; DeleteCriticalSection(&g_Lock); } } return Result; } <|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <algorithm> #include <Eigen/Dense> #include "RRTPlanner.hpp" #include "motion/TrapezoidalMotion.hpp" #include <Constants.hpp> #include <Utils.hpp> using namespace std; using namespace Planning; Geometry2d::Point Planning::randomPoint() { float x = Field_Dimensions::Current_Dimensions.FloorWidth() * (drand48() - 0.5f); float y = Field_Dimensions::Current_Dimensions.FloorLength() * drand48() - Field_Dimensions::Current_Dimensions.Border(); return Geometry2d::Point(x, y); } RRTPlanner::RRTPlanner() { _maxIterations = 100; } Planning::InterpolatedPath* RRTPlanner::run( const Geometry2d::Point &start, const float angle, const Geometry2d::Point &vel, const MotionConstraints &motionConstraints, const Geometry2d::CompositeShape *obstacles) { Planning::InterpolatedPath *path = new Planning::InterpolatedPath(); Geometry2d::Point goal = *motionConstraints.targetPos; _motionConstraints = motionConstraints; vi = vel; _obstacles = obstacles; // Simple case: no path if (start == goal) { path->points.push_back(start); return path; } /// Locate a non blocked goal point Geometry2d::Point newGoal = goal; if (obstacles && obstacles->hit(goal)) { FixedStepTree goalTree; goalTree.init(goal, obstacles); goalTree.step = .1f; // The starting point is in an obstacle // extend the tree until we find an unobstructed point for (int i= 0 ; i< 100 ; ++i) { Geometry2d::Point r = randomPoint(); //extend to a random point Tree::Point* newPoint = goalTree.extend(r); //if the new point is not blocked //it becomes the new goal if (newPoint && newPoint->hit.empty()) { newGoal = newPoint->pos; break; } } /// see if the new goal is better than old one /// must be at least a robot radius better else the move isn't worth it const float oldDist = _bestGoal.distTo(goal); const float newDist = newGoal.distTo(goal) + Robot_Radius; if (newDist < oldDist || obstacles->hit(_bestGoal)) { _bestGoal = newGoal; } } else { _bestGoal = goal; } /// simple case of direct shot /* if (!obstacles->hit(Geometry2d::Segment(start, _bestGoal))) { path.points.push_back(start); path.points.push_back(_bestGoal); _bestPath = path; return; } */ _fixedStepTree0.init(start, obstacles); _fixedStepTree1.init(_bestGoal, obstacles); _fixedStepTree0.step = _fixedStepTree1.step = .15f; /// run global position best path search Tree* ta = &_fixedStepTree0; Tree* tb = &_fixedStepTree1; for (unsigned int i=0 ; i<_maxIterations; ++i) { Geometry2d::Point r = randomPoint(); Tree::Point* newPoint = ta->extend(r); if (newPoint) { //try to connect the other tree to this point if (tb->connect(newPoint->pos)) { //trees connected //done with global path finding //the path is from start to goal //makePath will handle the rest break; } } swap(ta, tb); } //see if we found a better global path *path = makePath(); if (path->points.empty()) { // FIXME: without these two lines, an empty path is returned which causes errors down the line. path->points.push_back(start); } return path; } Planning::InterpolatedPath update( Planning::InterpolatedPath &origionalPath, const float angle, const Geometry2d::Point& vel, const MotionConstraints &motionConstraints, const Geometry2d::CompositeShape* obstacles) { return InterpolatedPath(); } Planning::InterpolatedPath RRTPlanner::makePath() { Planning::InterpolatedPath newPath; Tree::Point* p0 = _fixedStepTree0.last(); Tree::Point* p1 = _fixedStepTree1.last(); //sanity check if (!p0 || !p1 || p0->pos != p1->pos) { return newPath; } // extract path from RRTs _fixedStepTree0.addPath(newPath, p0);//add the start tree first...normal order (aka from root to p0) _fixedStepTree1.addPath(newPath, p1, true);//add the goal tree in reverse (aka p1 to root) optimize(newPath, _obstacles, _motionConstraints, vi); //TODO evaluate the old path based on the closest segment //and the distance to the endpoint of that segment //Otherwise, a new path will always be shorter than the old given we traveled some /// Conditions to use new path /// 1. old path is empty /// 2. goal changed /// 3. start changed -- maybe (Roman) /// 3. new path is better /// 4. old path not valid (hits obstacles) return newPath; } void RRTPlanner::optimize(Planning::InterpolatedPath &path, const Geometry2d::CompositeShape *obstacles, const MotionConstraints &motionConstraints, Geometry2d::Point vi) { unsigned int start = 0; if (path.empty()) { // Nothing to do return; } vector<Geometry2d::Point> pts; pts.reserve(path.points.size()); // Copy all points that won't be optimized vector<Geometry2d::Point>::const_iterator begin = path.points.begin(); pts.insert(pts.end(), begin, begin + start); // The set of obstacles the starting point was inside of std::set<shared_ptr<Geometry2d::Shape> > hit; again: obstacles->hit(path.points[start], hit); pts.push_back(path.points[start]); // [start, start + 1] is guaranteed not to have a collision because it's already in the path. for (unsigned int end = start + 2; end < path.points.size(); ++end) { std::set<shared_ptr<Geometry2d::Shape> > newHit; obstacles->hit(Geometry2d::Segment(path.points[start], path.points[end]), newHit); try { set_difference(newHit.begin(), newHit.end(), hit.begin(), hit.end(), ExceptionIterator<std::shared_ptr<Geometry2d::Shape>>()); } catch (exception& e) { start = end - 1; goto again; } } // Done with the path pts.push_back(path.points.back()); path.points = pts; cubicBezier(path, obstacles, motionConstraints, vi); } Geometry2d::Point pow(Geometry2d::Point &p1, float i) { return Geometry2d::Point(pow(p1.x, i), pow(p1.y, i)); } using namespace Eigen; float getTime(Planning::InterpolatedPath &path, int index, const MotionConstraints &motionConstraints, float startSpeed, float endSpeed) { return Trapezoidal::getTime(path.length(0,index), path.length(), motionConstraints.maxSpeed, motionConstraints.maxAcceleration, startSpeed, endSpeed); } //TODO: Use targeted end velocity void RRTPlanner::cubicBezier (Planning::InterpolatedPath &path, const Geometry2d::CompositeShape *obstacles, const MotionConstraints &motionConstraints, Geometry2d::Point vi) { int length = path.size(); int curvesNum = length-1; if (curvesNum <= 0) { //TODO return; } //TODO: Get the actual values Geometry2d::Point vf(0,0); vector<double> pointsX(length); vector<double> pointsY(length); vector<double> ks(length-1); vector<double> ks2(length-1); for (int i=0; i<length; i++) { pointsX[i] = path.points[i].x; pointsY[i] = path.points[i].y; } float startSpeed = vi.mag(); float endSpeed = motionConstraints.endSpeed; for (int i=0; i<curvesNum; i++) { ks[i] = 1.0/(getTime(path, i+1, motionConstraints, startSpeed, endSpeed)-getTime(path, i, motionConstraints, startSpeed, endSpeed)); ks2[i] = ks[i]*ks[i]; } VectorXd solutionX = cubicBezierCalc(vi.x, vf.x, pointsX, ks, ks2); VectorXd solutionY = cubicBezierCalc(vi.y, vf.y, pointsY, ks, ks2); Geometry2d::Point p0, p1, p2, p3; vector<Geometry2d::Point> pts; vector<Geometry2d::Point> vels; vector<float> times; const int interpolations = 10; double time=0; for (int i=0; i<curvesNum; i++) // access by reference to avoid copying { p0 = path.points[i]; p3 = path.points[i+1]; p1 = Geometry2d::Point(solutionX(i*2),solutionY(i*2)); p2 = Geometry2d::Point(solutionX(i*2 + 1),solutionY(i*2 + 1)); for (int j=0; j<interpolations; j++) { double k = ks[i]; float t = (((float)j / (float)(interpolations))); Geometry2d::Point temp = pow(1.0-t, 3) * p0 + 3.0* pow(1.0-t, 2)*t*p1 + 3*(1.0-t)*pow(t, 2)*p2 + pow(t, 3)*p3; pts.push_back(temp); t = ((float)j / (float)(interpolations))/k; //3 k (-(A (-1 + k t)^2) + k t (2 C - 3 C k t + D k t) + B (1 - 4 k t + 3 k^2 t^2)) temp = 3*k*(-(p0*pow(-1 + k*t ,2)) + k*t*(2*p2 - 3*p2*k*t + p3*k*t) + p1*(1 - 4*k*t + 3*pow(k,2)*pow(t,2))); vels.push_back(temp); times.push_back(time + t); } time+= 1.0/ks[i]; } pts.push_back(path.points[length-1]); vels.push_back(vf); times.push_back(time); path.points = pts; path.vels = vels; path.times = times; } VectorXd RRTPlanner::cubicBezierCalc (double vi, double vf, vector<double> &points, vector<double> &ks, vector<double> &ks2) { int curvesNum = points.size() - 1; if (curvesNum == 1) { VectorXd vector(2); vector[0] = vi/(3.0*ks[0]) + points[0]; vector[1] = points[curvesNum] - vf/(3*ks[curvesNum-1]); return vector; } else { int matrixSize = curvesNum*2; MatrixXd equations = MatrixXd::Zero(matrixSize, matrixSize); VectorXd answer(matrixSize); equations(0,0) = 1; answer(0) = vi/(3.0*ks[0]) + points[0]; equations(1,matrixSize-1) = 1; answer(1) = points[curvesNum] - vf/(3*ks[curvesNum-1]); int i = 2; for (int n=0; n<curvesNum-1; n++) { equations(i, n*2 + 1) = ks[n]; equations(i, n*2 + 2) = ks[n+1]; answer(i) = (ks[n] + ks[n+1]) * points[n + 1]; i++; } for (int n=0; n<curvesNum-1; n++) { equations(i, n*2) = ks2[n]; equations(i, n*2 + 1) = -2*ks2[n]; equations(i, n*2 + 2) = 2*ks2[n+1]; equations(i, n*2 + 3) = -ks2[n+1]; answer(i) = points[n + 1] * (ks2[n+1] - ks2[n]); i++; } ColPivHouseholderQR<MatrixXd> solver(equations); VectorXd solution = solver.solve(answer); return solution; } } <commit_msg>Set it back to setting the starting speed to 0 always. This is necessary due to #271<commit_after> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <algorithm> #include <Eigen/Dense> #include "RRTPlanner.hpp" #include "motion/TrapezoidalMotion.hpp" #include <Constants.hpp> #include <Utils.hpp> using namespace std; using namespace Planning; Geometry2d::Point Planning::randomPoint() { float x = Field_Dimensions::Current_Dimensions.FloorWidth() * (drand48() - 0.5f); float y = Field_Dimensions::Current_Dimensions.FloorLength() * drand48() - Field_Dimensions::Current_Dimensions.Border(); return Geometry2d::Point(x, y); } RRTPlanner::RRTPlanner() { _maxIterations = 100; } Planning::InterpolatedPath* RRTPlanner::run( const Geometry2d::Point &start, const float angle, const Geometry2d::Point &vel, const MotionConstraints &motionConstraints, const Geometry2d::CompositeShape *obstacles) { Planning::InterpolatedPath *path = new Planning::InterpolatedPath(); Geometry2d::Point goal = *motionConstraints.targetPos; _motionConstraints = motionConstraints; vi = vel; _obstacles = obstacles; // Simple case: no path if (start == goal) { path->points.push_back(start); return path; } /// Locate a non blocked goal point Geometry2d::Point newGoal = goal; if (obstacles && obstacles->hit(goal)) { FixedStepTree goalTree; goalTree.init(goal, obstacles); goalTree.step = .1f; // The starting point is in an obstacle // extend the tree until we find an unobstructed point for (int i= 0 ; i< 100 ; ++i) { Geometry2d::Point r = randomPoint(); //extend to a random point Tree::Point* newPoint = goalTree.extend(r); //if the new point is not blocked //it becomes the new goal if (newPoint && newPoint->hit.empty()) { newGoal = newPoint->pos; break; } } /// see if the new goal is better than old one /// must be at least a robot radius better else the move isn't worth it const float oldDist = _bestGoal.distTo(goal); const float newDist = newGoal.distTo(goal) + Robot_Radius; if (newDist < oldDist || obstacles->hit(_bestGoal)) { _bestGoal = newGoal; } } else { _bestGoal = goal; } /// simple case of direct shot /* if (!obstacles->hit(Geometry2d::Segment(start, _bestGoal))) { path.points.push_back(start); path.points.push_back(_bestGoal); _bestPath = path; return; } */ _fixedStepTree0.init(start, obstacles); _fixedStepTree1.init(_bestGoal, obstacles); _fixedStepTree0.step = _fixedStepTree1.step = .15f; /// run global position best path search Tree* ta = &_fixedStepTree0; Tree* tb = &_fixedStepTree1; for (unsigned int i=0 ; i<_maxIterations; ++i) { Geometry2d::Point r = randomPoint(); Tree::Point* newPoint = ta->extend(r); if (newPoint) { //try to connect the other tree to this point if (tb->connect(newPoint->pos)) { //trees connected //done with global path finding //the path is from start to goal //makePath will handle the rest break; } } swap(ta, tb); } //see if we found a better global path *path = makePath(); if (path->points.empty()) { // FIXME: without these two lines, an empty path is returned which causes errors down the line. path->points.push_back(start); } return path; } Planning::InterpolatedPath update( Planning::InterpolatedPath &origionalPath, const float angle, const Geometry2d::Point& vel, const MotionConstraints &motionConstraints, const Geometry2d::CompositeShape* obstacles) { return InterpolatedPath(); } Planning::InterpolatedPath RRTPlanner::makePath() { Planning::InterpolatedPath newPath; Tree::Point* p0 = _fixedStepTree0.last(); Tree::Point* p1 = _fixedStepTree1.last(); //sanity check if (!p0 || !p1 || p0->pos != p1->pos) { return newPath; } // extract path from RRTs _fixedStepTree0.addPath(newPath, p0);//add the start tree first...normal order (aka from root to p0) _fixedStepTree1.addPath(newPath, p1, true);//add the goal tree in reverse (aka p1 to root) optimize(newPath, _obstacles, _motionConstraints, vi); //TODO evaluate the old path based on the closest segment //and the distance to the endpoint of that segment //Otherwise, a new path will always be shorter than the old given we traveled some /// Conditions to use new path /// 1. old path is empty /// 2. goal changed /// 3. start changed -- maybe (Roman) /// 3. new path is better /// 4. old path not valid (hits obstacles) return newPath; } void RRTPlanner::optimize(Planning::InterpolatedPath &path, const Geometry2d::CompositeShape *obstacles, const MotionConstraints &motionConstraints, Geometry2d::Point vi) { unsigned int start = 0; if (path.empty()) { // Nothing to do return; } vector<Geometry2d::Point> pts; pts.reserve(path.points.size()); // Copy all points that won't be optimized vector<Geometry2d::Point>::const_iterator begin = path.points.begin(); pts.insert(pts.end(), begin, begin + start); // The set of obstacles the starting point was inside of std::set<shared_ptr<Geometry2d::Shape> > hit; again: obstacles->hit(path.points[start], hit); pts.push_back(path.points[start]); // [start, start + 1] is guaranteed not to have a collision because it's already in the path. for (unsigned int end = start + 2; end < path.points.size(); ++end) { std::set<shared_ptr<Geometry2d::Shape> > newHit; obstacles->hit(Geometry2d::Segment(path.points[start], path.points[end]), newHit); try { set_difference(newHit.begin(), newHit.end(), hit.begin(), hit.end(), ExceptionIterator<std::shared_ptr<Geometry2d::Shape>>()); } catch (exception& e) { start = end - 1; goto again; } } // Done with the path pts.push_back(path.points.back()); path.points = pts; cubicBezier(path, obstacles, motionConstraints, vi); } Geometry2d::Point pow(Geometry2d::Point &p1, float i) { return Geometry2d::Point(pow(p1.x, i), pow(p1.y, i)); } using namespace Eigen; float getTime(Planning::InterpolatedPath &path, int index, const MotionConstraints &motionConstraints, float startSpeed, float endSpeed) { return Trapezoidal::getTime(path.length(0,index), path.length(), motionConstraints.maxSpeed, motionConstraints.maxAcceleration, startSpeed, endSpeed); } //TODO: Use targeted end velocity void RRTPlanner::cubicBezier (Planning::InterpolatedPath &path, const Geometry2d::CompositeShape *obstacles, const MotionConstraints &motionConstraints, Geometry2d::Point vi) { int length = path.size(); int curvesNum = length-1; if (curvesNum <= 0) { //TODO return; } //TODO: Get the actual values Geometry2d::Point vf(0,0); vector<double> pointsX(length); vector<double> pointsY(length); vector<double> ks(length-1); vector<double> ks2(length-1); for (int i=0; i<length; i++) { pointsX[i] = path.points[i].x; pointsY[i] = path.points[i].y; } float startSpeed = 0; float endSpeed = motionConstraints.endSpeed; for (int i=0; i<curvesNum; i++) { ks[i] = 1.0/(getTime(path, i+1, motionConstraints, startSpeed, endSpeed)-getTime(path, i, motionConstraints, startSpeed, endSpeed)); ks2[i] = ks[i]*ks[i]; } VectorXd solutionX = cubicBezierCalc(vi.x, vf.x, pointsX, ks, ks2); VectorXd solutionY = cubicBezierCalc(vi.y, vf.y, pointsY, ks, ks2); Geometry2d::Point p0, p1, p2, p3; vector<Geometry2d::Point> pts; vector<Geometry2d::Point> vels; vector<float> times; const int interpolations = 10; double time=0; for (int i=0; i<curvesNum; i++) // access by reference to avoid copying { p0 = path.points[i]; p3 = path.points[i+1]; p1 = Geometry2d::Point(solutionX(i*2),solutionY(i*2)); p2 = Geometry2d::Point(solutionX(i*2 + 1),solutionY(i*2 + 1)); for (int j=0; j<interpolations; j++) { double k = ks[i]; float t = (((float)j / (float)(interpolations))); Geometry2d::Point temp = pow(1.0-t, 3) * p0 + 3.0* pow(1.0-t, 2)*t*p1 + 3*(1.0-t)*pow(t, 2)*p2 + pow(t, 3)*p3; pts.push_back(temp); t = ((float)j / (float)(interpolations))/k; //3 k (-(A (-1 + k t)^2) + k t (2 C - 3 C k t + D k t) + B (1 - 4 k t + 3 k^2 t^2)) temp = 3*k*(-(p0*pow(-1 + k*t ,2)) + k*t*(2*p2 - 3*p2*k*t + p3*k*t) + p1*(1 - 4*k*t + 3*pow(k,2)*pow(t,2))); vels.push_back(temp); times.push_back(time + t); } time+= 1.0/ks[i]; } pts.push_back(path.points[length-1]); vels.push_back(vf); times.push_back(time); path.points = pts; path.vels = vels; path.times = times; } VectorXd RRTPlanner::cubicBezierCalc (double vi, double vf, vector<double> &points, vector<double> &ks, vector<double> &ks2) { int curvesNum = points.size() - 1; if (curvesNum == 1) { VectorXd vector(2); vector[0] = vi/(3.0*ks[0]) + points[0]; vector[1] = points[curvesNum] - vf/(3*ks[curvesNum-1]); return vector; } else { int matrixSize = curvesNum*2; MatrixXd equations = MatrixXd::Zero(matrixSize, matrixSize); VectorXd answer(matrixSize); equations(0,0) = 1; answer(0) = vi/(3.0*ks[0]) + points[0]; equations(1,matrixSize-1) = 1; answer(1) = points[curvesNum] - vf/(3*ks[curvesNum-1]); int i = 2; for (int n=0; n<curvesNum-1; n++) { equations(i, n*2 + 1) = ks[n]; equations(i, n*2 + 2) = ks[n+1]; answer(i) = (ks[n] + ks[n+1]) * points[n + 1]; i++; } for (int n=0; n<curvesNum-1; n++) { equations(i, n*2) = ks2[n]; equations(i, n*2 + 1) = -2*ks2[n]; equations(i, n*2 + 2) = 2*ks2[n+1]; equations(i, n*2 + 3) = -ks2[n+1]; answer(i) = points[n + 1] * (ks2[n+1] - ks2[n]); i++; } ColPivHouseholderQR<MatrixXd> solver(equations); VectorXd solution = solver.solve(answer); return solution; } } <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/alert.hpp> #include <libtorrent/alert_types.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; extern char const* alert_doc; extern char const* alert_msg_doc; extern char const* alert_severity_doc; extern char const* torrent_alert_doc; extern char const* tracker_alert_doc; extern char const* tracker_error_alert_doc; extern char const* tracker_warning_alert_doc; extern char const* tracker_reply_alert_doc; extern char const* tracker_announce_alert_doc; extern char const* hash_failed_alert_doc; extern char const* peer_ban_alert_doc; extern char const* peer_error_alert_doc; extern char const* invalid_request_alert_doc; extern char const* peer_request_doc; extern char const* torrent_finished_alert_doc; extern char const* piece_finished_alert_doc; extern char const* block_finished_alert_doc; extern char const* block_downloading_alert_doc; extern char const* storage_moved_alert_doc; extern char const* torrent_deleted_alert_doc; extern char const* torrent_paused_alert_doc; extern char const* torrent_checked_alert_doc; extern char const* url_seed_alert_doc; extern char const* file_error_alert_doc; extern char const* metadata_failed_alert_doc; extern char const* metadata_received_alert_doc; extern char const* listen_failed_alert_doc; extern char const* listen_succeeded_alert_doc; extern char const* portmap_error_alert_doc; extern char const* portmap_alert_doc; extern char const* fastresume_rejected_alert_doc; extern char const* peer_blocked_alert_doc; extern char const* scrape_reply_alert_doc; extern char const* scrape_failed_alert_doc; extern char const* udp_error_alert_doc; extern char const* external_ip_alert_doc; extern char const* save_resume_data_alert_doc; void bind_alert() { using boost::noncopyable; { scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init) .def("message", &alert::message, alert_msg_doc) .def("what", &alert::what) .def("category", &alert::category) .def("severity", &alert::severity, alert_severity_doc) .def("__str__", &alert::message, alert_msg_doc) ; enum_<alert::severity_t>("severity_levels") .value("debug", alert::debug) .value("info", alert::info) .value("warning", alert::warning) .value("critical", alert::critical) .value("fatal", alert::fatal) .value("none", alert::none) ; enum_<alert::category_t>("category_t") .value("error_notification", alert::error_notification) .value("peer_notification", alert::peer_notification) .value("port_mapping_notification", alert::port_mapping_notification) .value("storage_notification", alert::storage_notification) .value("tracker_notification", alert::tracker_notification) .value("debug_notification", alert::debug_notification) .value("status_notification", alert::status_notification) .value("progress_notification", alert::progress_notification) .value("ip_block_notification", alert::ip_block_notification) .value("all_categories", alert::all_categories) ; } class_<torrent_alert, bases<alert>, noncopyable>( "torrent_alert", torrent_alert_doc, no_init ) .def_readonly("handle", &torrent_alert::handle) ; class_<tracker_alert, bases<torrent_alert>, noncopyable>( "tracker_alert", tracker_alert_doc, no_init ) .def_readonly("url", &tracker_alert::url) ; class_<tracker_error_alert, bases<tracker_alert>, noncopyable>( "tracker_error_alert", tracker_error_alert_doc, no_init ) .def_readonly("times_in_row", &tracker_error_alert::times_in_row) .def_readonly("status_code", &tracker_error_alert::status_code) ; class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>( "tracker_warning_alert", tracker_warning_alert_doc, no_init ); class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>( "tracker_reply_alert", tracker_reply_alert_doc, no_init ) .def_readonly("num_peers", &tracker_reply_alert::num_peers) ; class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>( "tracker_announce_alert", tracker_announce_alert_doc, no_init ); class_<hash_failed_alert, bases<torrent_alert>, noncopyable>( "hash_failed_alert", hash_failed_alert_doc, no_init ) .def_readonly("piece_index", &hash_failed_alert::piece_index) ; class_<peer_ban_alert, bases<torrent_alert>, noncopyable>( "peer_ban_alert", peer_ban_alert_doc, no_init ) .def_readonly("ip", &peer_ban_alert::ip) ; class_<peer_error_alert, bases<alert>, noncopyable>( "peer_error_alert", peer_error_alert_doc, no_init ) .def_readonly("ip", &peer_error_alert::ip) .def_readonly("pid", &peer_error_alert::pid) ; class_<invalid_request_alert, bases<torrent_alert>, noncopyable>( "invalid_request_alert", invalid_request_alert_doc, no_init ) .def_readonly("ip", &invalid_request_alert::ip) .def_readonly("request", &invalid_request_alert::request) .def_readonly("pid", &invalid_request_alert::pid) ; class_<peer_request>("peer_request", peer_request_doc) .def_readonly("piece", &peer_request::piece) .def_readonly("start", &peer_request::start) .def_readonly("length", &peer_request::length) .def(self == self) ; class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>( "torrent_finished_alert", torrent_finished_alert_doc, no_init ); class_<piece_finished_alert, bases<torrent_alert>, noncopyable>( "piece_finished_alert", piece_finished_alert_doc, no_init ) .def_readonly("piece_index", &piece_finished_alert::piece_index) ; class_<block_finished_alert, bases<torrent_alert>, noncopyable>( "block_finished_alert", block_finished_alert_doc, no_init ) .def_readonly("block_index", &block_finished_alert::block_index) .def_readonly("piece_index", &block_finished_alert::piece_index) ; class_<block_downloading_alert, bases<torrent_alert>, noncopyable>( "block_downloading_alert", block_downloading_alert_doc, no_init ) .def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg) .def_readonly("block_index", &block_downloading_alert::block_index) .def_readonly("piece_index", &block_downloading_alert::piece_index) ; class_<storage_moved_alert, bases<torrent_alert>, noncopyable>( "storage_moved_alert", storage_moved_alert_doc, no_init ); class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>( "torrent_deleted_alert", torrent_deleted_alert_doc, no_init ); class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>( "torrent_paused_alert", torrent_paused_alert_doc, no_init ); class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>( "torrent_checked_alert", torrent_checked_alert_doc, no_init ); class_<url_seed_alert, bases<torrent_alert>, noncopyable>( "url_seed_alert", url_seed_alert_doc, no_init ) .def_readonly("url", &url_seed_alert::url) ; class_<file_error_alert, bases<torrent_alert>, noncopyable>( "file_error_alert", file_error_alert_doc, no_init ) .def_readonly("file", &file_error_alert::file) ; class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>( "metadata_failed_alert", metadata_failed_alert_doc, no_init ); class_<metadata_received_alert, bases<torrent_alert>, noncopyable>( "metadata_received_alert", metadata_received_alert_doc, no_init ); class_<listen_failed_alert, bases<alert>, noncopyable>( "listen_failed_alert", listen_failed_alert_doc, no_init ); class_<listen_succeeded_alert, bases<alert>, noncopyable>( "listen_succeeded_alert", listen_succeeded_alert_doc, no_init ) .def_readonly("endpoint", &listen_succeeded_alert::endpoint) ; class_<portmap_error_alert, bases<alert>, noncopyable>( "portmap_error_alert", portmap_error_alert_doc, no_init ) .def_readonly("mapping", &portmap_error_alert::mapping) .def_readonly("type", &portmap_error_alert::type) ; class_<portmap_alert, bases<alert>, noncopyable>( "portmap_alert", portmap_alert_doc, no_init ) .def_readonly("mapping", &portmap_alert::mapping) .def_readonly("external_port", &portmap_alert::external_port) .def_readonly("type", &portmap_alert::type) ; class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>( "fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init ); class_<peer_blocked_alert, bases<alert>, noncopyable>( "peer_blocked_alert", peer_blocked_alert_doc, no_init ) .def_readonly("ip", &peer_blocked_alert::ip) ; class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>( "scrape_reply_alert", scrape_reply_alert_doc, no_init ) .def_readonly("incomplete", &scrape_reply_alert::incomplete) .def_readonly("complete", &scrape_reply_alert::complete) ; class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>( "scrape_failed_alert", scrape_failed_alert_doc, no_init ); class_<udp_error_alert, bases<alert>, noncopyable>( "udp_error_alert", udp_error_alert_doc, no_init ) .def_readonly("endpoint", &udp_error_alert::endpoint) ; class_<external_ip_alert, bases<alert>, noncopyable>( "external_ip_alert", external_ip_alert_doc, no_init ) .def_readonly("external_address", &external_ip_alert::external_address) ; class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_alert", save_resume_data_alert_doc, no_init ) .def_readonly("resume_data", &save_resume_data_alert::resume_data) ; class_<file_renamed_alert, bases<torrent_alert>, noncopyable>( "file_renamed_alert", no_init ) .def_readonly("name", &file_renamed_alert::name) ; class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>( "torrent_resumed_alert", no_init ); class_<state_changed_alert, bases<torrent_alert>, noncopyable>( "state_changed_alert", no_init ) .def_readonly("state", &state_changed_alert::state) ; } <commit_msg>Update alerts in python bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/alert.hpp> #include <libtorrent/alert_types.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; extern char const* alert_doc; extern char const* alert_msg_doc; extern char const* alert_severity_doc; extern char const* torrent_alert_doc; extern char const* tracker_alert_doc; extern char const* tracker_error_alert_doc; extern char const* tracker_warning_alert_doc; extern char const* tracker_reply_alert_doc; extern char const* tracker_announce_alert_doc; extern char const* hash_failed_alert_doc; extern char const* peer_ban_alert_doc; extern char const* peer_error_alert_doc; extern char const* invalid_request_alert_doc; extern char const* peer_request_doc; extern char const* torrent_finished_alert_doc; extern char const* piece_finished_alert_doc; extern char const* block_finished_alert_doc; extern char const* block_downloading_alert_doc; extern char const* storage_moved_alert_doc; extern char const* torrent_deleted_alert_doc; extern char const* torrent_paused_alert_doc; extern char const* torrent_checked_alert_doc; extern char const* url_seed_alert_doc; extern char const* file_error_alert_doc; extern char const* metadata_failed_alert_doc; extern char const* metadata_received_alert_doc; extern char const* listen_failed_alert_doc; extern char const* listen_succeeded_alert_doc; extern char const* portmap_error_alert_doc; extern char const* portmap_alert_doc; extern char const* fastresume_rejected_alert_doc; extern char const* peer_blocked_alert_doc; extern char const* scrape_reply_alert_doc; extern char const* scrape_failed_alert_doc; extern char const* udp_error_alert_doc; extern char const* external_ip_alert_doc; extern char const* save_resume_data_alert_doc; void bind_alert() { using boost::noncopyable; { scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init) .def("message", &alert::message, alert_msg_doc) .def("what", &alert::what) .def("category", &alert::category) .def("severity", &alert::severity, alert_severity_doc) .def("__str__", &alert::message, alert_msg_doc) ; enum_<alert::severity_t>("severity_levels") .value("debug", alert::debug) .value("info", alert::info) .value("warning", alert::warning) .value("critical", alert::critical) .value("fatal", alert::fatal) .value("none", alert::none) ; enum_<alert::category_t>("category_t") .value("error_notification", alert::error_notification) .value("peer_notification", alert::peer_notification) .value("port_mapping_notification", alert::port_mapping_notification) .value("storage_notification", alert::storage_notification) .value("tracker_notification", alert::tracker_notification) .value("debug_notification", alert::debug_notification) .value("status_notification", alert::status_notification) .value("progress_notification", alert::progress_notification) .value("ip_block_notification", alert::ip_block_notification) .value("all_categories", alert::all_categories) ; } class_<torrent_alert, bases<alert>, noncopyable>( "torrent_alert", torrent_alert_doc, no_init ) .def_readonly("handle", &torrent_alert::handle) ; class_<tracker_alert, bases<torrent_alert>, noncopyable>( "tracker_alert", tracker_alert_doc, no_init ) .def_readonly("url", &tracker_alert::url) ; class_<peer_alert, bases<torrent_alert>, noncopyable>( "peer_alert", no_init ) .def_readonly("ip", &peer_alert::ip) .def_readonly("pid", &peer_alert::pid) ; class_<tracker_error_alert, bases<tracker_alert>, noncopyable>( "tracker_error_alert", tracker_error_alert_doc, no_init ) .def_readonly("times_in_row", &tracker_error_alert::times_in_row) .def_readonly("status_code", &tracker_error_alert::status_code) ; class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>( "tracker_warning_alert", tracker_warning_alert_doc, no_init ); class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>( "tracker_reply_alert", tracker_reply_alert_doc, no_init ) .def_readonly("num_peers", &tracker_reply_alert::num_peers) ; class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>( "tracker_announce_alert", tracker_announce_alert_doc, no_init ); class_<hash_failed_alert, bases<torrent_alert>, noncopyable>( "hash_failed_alert", hash_failed_alert_doc, no_init ) .def_readonly("piece_index", &hash_failed_alert::piece_index) ; class_<peer_ban_alert, bases<peer_alert>, noncopyable>( "peer_ban_alert", peer_ban_alert_doc, no_init ); class_<peer_error_alert, bases<peer_alert>, noncopyable>( "peer_error_alert", peer_error_alert_doc, no_init ); class_<invalid_request_alert, bases<peer_alert>, noncopyable>( "invalid_request_alert", invalid_request_alert_doc, no_init ) .def_readonly("request", &invalid_request_alert::request) ; class_<peer_request>("peer_request", peer_request_doc) .def_readonly("piece", &peer_request::piece) .def_readonly("start", &peer_request::start) .def_readonly("length", &peer_request::length) .def(self == self) ; class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>( "torrent_finished_alert", torrent_finished_alert_doc, no_init ); class_<piece_finished_alert, bases<torrent_alert>, noncopyable>( "piece_finished_alert", piece_finished_alert_doc, no_init ) .def_readonly("piece_index", &piece_finished_alert::piece_index) ; class_<block_finished_alert, bases<peer_alert>, noncopyable>( "block_finished_alert", block_finished_alert_doc, no_init ) .def_readonly("block_index", &block_finished_alert::block_index) .def_readonly("piece_index", &block_finished_alert::piece_index) ; class_<block_downloading_alert, bases<peer_alert>, noncopyable>( "block_downloading_alert", block_downloading_alert_doc, no_init ) .def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg) .def_readonly("block_index", &block_downloading_alert::block_index) .def_readonly("piece_index", &block_downloading_alert::piece_index) ; class_<storage_moved_alert, bases<torrent_alert>, noncopyable>( "storage_moved_alert", storage_moved_alert_doc, no_init ); class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>( "torrent_deleted_alert", torrent_deleted_alert_doc, no_init ); class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>( "torrent_paused_alert", torrent_paused_alert_doc, no_init ); class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>( "torrent_checked_alert", torrent_checked_alert_doc, no_init ); class_<url_seed_alert, bases<torrent_alert>, noncopyable>( "url_seed_alert", url_seed_alert_doc, no_init ) .def_readonly("url", &url_seed_alert::url) ; class_<file_error_alert, bases<torrent_alert>, noncopyable>( "file_error_alert", file_error_alert_doc, no_init ) .def_readonly("file", &file_error_alert::file) ; class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>( "metadata_failed_alert", metadata_failed_alert_doc, no_init ); class_<metadata_received_alert, bases<torrent_alert>, noncopyable>( "metadata_received_alert", metadata_received_alert_doc, no_init ); class_<listen_failed_alert, bases<alert>, noncopyable>( "listen_failed_alert", listen_failed_alert_doc, no_init ); class_<listen_succeeded_alert, bases<alert>, noncopyable>( "listen_succeeded_alert", listen_succeeded_alert_doc, no_init ) .def_readonly("endpoint", &listen_succeeded_alert::endpoint) ; class_<portmap_error_alert, bases<alert>, noncopyable>( "portmap_error_alert", portmap_error_alert_doc, no_init ) .def_readonly("mapping", &portmap_error_alert::mapping) .def_readonly("type", &portmap_error_alert::type) ; class_<portmap_alert, bases<alert>, noncopyable>( "portmap_alert", portmap_alert_doc, no_init ) .def_readonly("mapping", &portmap_alert::mapping) .def_readonly("external_port", &portmap_alert::external_port) .def_readonly("type", &portmap_alert::type) ; class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>( "fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init ); class_<peer_blocked_alert, bases<alert>, noncopyable>( "peer_blocked_alert", peer_blocked_alert_doc, no_init ) .def_readonly("ip", &peer_blocked_alert::ip) ; class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>( "scrape_reply_alert", scrape_reply_alert_doc, no_init ) .def_readonly("incomplete", &scrape_reply_alert::incomplete) .def_readonly("complete", &scrape_reply_alert::complete) ; class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>( "scrape_failed_alert", scrape_failed_alert_doc, no_init ); class_<udp_error_alert, bases<alert>, noncopyable>( "udp_error_alert", udp_error_alert_doc, no_init ) .def_readonly("endpoint", &udp_error_alert::endpoint) ; class_<external_ip_alert, bases<alert>, noncopyable>( "external_ip_alert", external_ip_alert_doc, no_init ) .def_readonly("external_address", &external_ip_alert::external_address) ; class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_alert", save_resume_data_alert_doc, no_init ) .def_readonly("resume_data", &save_resume_data_alert::resume_data) ; class_<file_renamed_alert, bases<torrent_alert>, noncopyable>( "file_renamed_alert", no_init ) .def_readonly("name", &file_renamed_alert::name) ; class_<file_rename_failed_alert, bases<torrent_alert>, noncopyable>( "file_rename_failed_alert", no_init ) .def_readonly("index", &file_rename_failed_alert::index) ; class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>( "torrent_resumed_alert", no_init ); class_<state_changed_alert, bases<torrent_alert>, noncopyable>( "state_changed_alert", no_init ) .def_readonly("state", &state_changed_alert::state) ; class_<dht_reply_alert, bases<tracker_alert>, noncopyable>( "dht_reply_alert", no_init ) .def_readonly("num_peers", &dht_reply_alert::num_peers) ; class_<peer_unsnubbed_alert, bases<peer_alert>, noncopyable>( "peer_unsnubbed_alert", no_init ); class_<peer_snubbed_alert, bases<peer_alert>, noncopyable>( "peer_snubbed_alert", no_init ); class_<peer_connect_alert, bases<peer_alert>, noncopyable>( "peer_connect_alert", no_init ); class_<peer_disconnected_alert, bases<peer_alert>, noncopyable>( "peer_disconnected_alert", no_init ); class_<request_dropped_alert, bases<peer_alert>, noncopyable>( "request_dropped_alert", no_init ) .def_readonly("block_index", &request_dropped_alert::block_index) .def_readonly("piece_index", &request_dropped_alert::piece_index) ; class_<block_timeout_alert, bases<peer_alert>, noncopyable>( "block_timeout_alert", no_init ) .def_readonly("block_index", &block_timeout_alert::block_index) .def_readonly("piece_index", &block_timeout_alert::piece_index) ; class_<unwanted_block_alert, bases<peer_alert>, noncopyable>( "unwanted_block_alert", no_init ) .def_readonly("block_index", &unwanted_block_alert::block_index) .def_readonly("piece_index", &unwanted_block_alert::piece_index) ; class_<torrent_delete_failed_alert, bases<torrent_alert>, noncopyable>( "torrent_delete_failed_alert", no_init ); class_<save_resume_data_failed_alert, bases<torrent_alert>, noncopyable>( "save_resume_data_failed_alert", no_init ); } <|endoftext|>
<commit_before>/* * Copyright 2011, Blender Foundation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mesh.h" #include "particles.h" #include "blender_sync.h" #include "blender_util.h" #include "util_foreach.h" CCL_NAMESPACE_BEGIN /* Utilities */ /* Particles Sync */ bool BlenderSync::psys_need_update(BL::ParticleSystem b_psys) { /* Particle data is only needed for * a) Billboard render mode if object's own material uses particle info * b) object/group render mode if any dupli object's material uses particle info * * Note: Meshes have to be synced at this point! */ bool need_update = false; switch (b_psys.settings().render_type()) { /* XXX not implemented yet! * billboards/strands would become part of the mesh data (?), * so the mesh attributes would store whether particle info is required. */ #if 0 case BL::ParticleSettings::render_type_BILLBOARD: case BL::ParticleSettings::render_type_PATH: { /* for strand rendering */ BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob.data(); Mesh *mesh = mesh_map.find(key); if (mesh) { need_update |= mesh->need_attribute(scene, ATTR_STD_PARTICLE) && mesh->need_update; } break; } #endif case BL::ParticleSettings::render_type_OBJECT: { BL::Object b_dupli_ob = b_psys.settings().dupli_object(); if (b_dupli_ob) { BL::ID key = (BKE_object_is_modified(b_dupli_ob))? b_dupli_ob: b_dupli_ob.data(); Mesh *mesh = mesh_map.find(key); if (mesh) { need_update |= mesh->need_attribute(scene, ATTR_STD_PARTICLE) && mesh->need_update; } } break; } case BL::ParticleSettings::render_type_GROUP: { BL::Group b_dupli_group = b_psys.settings().dupli_group(); if (b_dupli_group) { BL::Group::objects_iterator b_gob; for (b_dupli_group.objects.begin(b_gob); b_gob != b_dupli_group.objects.end(); ++b_gob) { BL::ID key = (BKE_object_is_modified(*b_gob))? *b_gob: b_gob->data(); Mesh *mesh = mesh_map.find(key); if (mesh) { need_update |= mesh->need_attribute(scene, ATTR_STD_PARTICLE) && mesh->need_update; } } } break; } default: /* avoid compiler warning */ break; } return need_update; } static bool use_particle_system(BL::ParticleSystem b_psys) { /* only use duplicator particles? disabled particle info for * halo and billboard to reduce particle count. * Probably not necessary since particles don't contain a huge amount * of data compared to other textures. */ #if 0 int render_type = b_psys->settings().render_type(); return (render_type == BL::ParticleSettings::render_type_OBJECT || render_type == BL::ParticleSettings::render_type_GROUP); #endif return true; } static bool use_particle(BL::Particle b_pa) { return b_pa.is_exist() && b_pa.is_visible() && b_pa.alive_state()==BL::Particle::alive_state_ALIVE; } static int psys_count_particles(BL::ParticleSystem b_psys) { int tot = 0; BL::ParticleSystem::particles_iterator b_pa; for(b_psys.particles.begin(b_pa); b_pa != b_psys.particles.end(); ++b_pa) { if(use_particle(*b_pa)) ++tot; } return tot; } int BlenderSync::object_count_particles(BL::Object b_ob) { int tot = 0; BL::Object::particle_systems_iterator b_psys; for(b_ob.particle_systems.begin(b_psys); b_psys != b_ob.particle_systems.end(); ++b_psys) { if (use_particle_system(*b_psys)) tot += psys_count_particles(*b_psys); } return tot; } void BlenderSync::sync_particles(BL::Object b_ob, BL::ParticleSystem b_psys) { /* depending on settings the psys may not even be rendered */ if (!use_particle_system(b_psys)) return; /* key to lookup particle system */ ParticleSystemKey key(b_ob, b_psys); ParticleSystem *psys; /* test if we need to sync */ bool object_updated = false; if(particle_system_map.sync(&psys, b_ob, b_ob, key)) object_updated = true; bool need_update = psys_need_update(b_psys); if (object_updated || need_update) { int tot = psys_count_particles(b_psys); psys->particles.clear(); psys->particles.reserve(tot); int index = 0; BL::ParticleSystem::particles_iterator b_pa; for(b_psys.particles.begin(b_pa); b_pa != b_psys.particles.end(); ++b_pa) { if(use_particle(*b_pa)) { Particle pa; pa.index = index; pa.age = b_scene.frame_current() - b_pa->birth_time(); pa.lifetime = b_pa->lifetime(); pa.location = get_float3(b_pa->location()); pa.rotation = get_float4(b_pa->rotation()); pa.size = b_pa->size(); pa.velocity = get_float3(b_pa->velocity()); pa.angular_velocity = get_float3(b_pa->angular_velocity()); psys->particles.push_back(pa); } ++index; } psys->tag_update(scene); } } void BlenderSync::sync_particle_systems() { /* layer data */ uint scene_layer = render_layer.scene_layer; particle_system_map.pre_sync(); /* object loop */ BL::Scene::objects_iterator b_ob; BL::Scene b_sce = b_scene; for(; b_sce; b_sce = b_sce.background_set()) { for(b_sce.objects.begin(b_ob); b_ob != b_sce.objects.end(); ++b_ob) { bool hide = (render_layer.use_viewport_visibility)? b_ob->hide(): b_ob->hide_render(); uint ob_layer = get_layer(b_ob->layers(), b_ob->layers_local_view(), object_is_light(*b_ob)); CYCLES_LOCAL_LAYER_HACK(render_layer.use_localview, ob_layer); hide = hide || !(ob_layer & scene_layer); if(!hide) { BL::Object::particle_systems_iterator b_psys; for(b_ob->particle_systems.begin(b_psys); b_psys != b_ob->particle_systems.end(); ++b_psys) sync_particles(*b_ob, *b_psys); } } } /* handle removed data and modified pointers */ if(particle_system_map.post_sync()) scene->particle_system_manager->tag_update(scene); } CCL_NAMESPACE_END <commit_msg>Cycles: Fix for particle info node crash: The particle 'alive' state can be set to 'dying', which is just an indicator that the particle will be removed, but it is is used for instancing. This would lead to insufficient texture size and assert crash.<commit_after>/* * Copyright 2011, Blender Foundation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mesh.h" #include "particles.h" #include "blender_sync.h" #include "blender_util.h" #include "util_foreach.h" CCL_NAMESPACE_BEGIN /* Utilities */ /* Particles Sync */ bool BlenderSync::psys_need_update(BL::ParticleSystem b_psys) { /* Particle data is only needed for * a) Billboard render mode if object's own material uses particle info * b) object/group render mode if any dupli object's material uses particle info * * Note: Meshes have to be synced at this point! */ bool need_update = false; switch (b_psys.settings().render_type()) { /* XXX not implemented yet! * billboards/strands would become part of the mesh data (?), * so the mesh attributes would store whether particle info is required. */ #if 0 case BL::ParticleSettings::render_type_BILLBOARD: case BL::ParticleSettings::render_type_PATH: { /* for strand rendering */ BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob.data(); Mesh *mesh = mesh_map.find(key); if (mesh) { need_update |= mesh->need_attribute(scene, ATTR_STD_PARTICLE) && mesh->need_update; } break; } #endif case BL::ParticleSettings::render_type_OBJECT: { BL::Object b_dupli_ob = b_psys.settings().dupli_object(); if (b_dupli_ob) { BL::ID key = (BKE_object_is_modified(b_dupli_ob))? b_dupli_ob: b_dupli_ob.data(); Mesh *mesh = mesh_map.find(key); if (mesh) { need_update |= mesh->need_attribute(scene, ATTR_STD_PARTICLE) && mesh->need_update; } } break; } case BL::ParticleSettings::render_type_GROUP: { BL::Group b_dupli_group = b_psys.settings().dupli_group(); if (b_dupli_group) { BL::Group::objects_iterator b_gob; for (b_dupli_group.objects.begin(b_gob); b_gob != b_dupli_group.objects.end(); ++b_gob) { BL::ID key = (BKE_object_is_modified(*b_gob))? *b_gob: b_gob->data(); Mesh *mesh = mesh_map.find(key); if (mesh) { need_update |= mesh->need_attribute(scene, ATTR_STD_PARTICLE) && mesh->need_update; } } } break; } default: /* avoid compiler warning */ break; } return need_update; } static bool use_particle_system(BL::ParticleSystem b_psys) { /* only use duplicator particles? disabled particle info for * halo and billboard to reduce particle count. * Probably not necessary since particles don't contain a huge amount * of data compared to other textures. */ #if 0 int render_type = b_psys->settings().render_type(); return (render_type == BL::ParticleSettings::render_type_OBJECT || render_type == BL::ParticleSettings::render_type_GROUP); #endif return true; } static bool use_particle(BL::Particle b_pa) { return b_pa.is_exist() && b_pa.is_visible() && (b_pa.alive_state()==BL::Particle::alive_state_ALIVE || b_pa.alive_state()==BL::Particle::alive_state_DYING); } static int psys_count_particles(BL::ParticleSystem b_psys) { int tot = 0; BL::ParticleSystem::particles_iterator b_pa; for(b_psys.particles.begin(b_pa); b_pa != b_psys.particles.end(); ++b_pa) { if(use_particle(*b_pa)) ++tot; } return tot; } int BlenderSync::object_count_particles(BL::Object b_ob) { int tot = 0; BL::Object::particle_systems_iterator b_psys; for(b_ob.particle_systems.begin(b_psys); b_psys != b_ob.particle_systems.end(); ++b_psys) { if (use_particle_system(*b_psys)) tot += psys_count_particles(*b_psys); } return tot; } void BlenderSync::sync_particles(BL::Object b_ob, BL::ParticleSystem b_psys) { /* depending on settings the psys may not even be rendered */ if (!use_particle_system(b_psys)) return; /* key to lookup particle system */ ParticleSystemKey key(b_ob, b_psys); ParticleSystem *psys; /* test if we need to sync */ bool object_updated = false; if(particle_system_map.sync(&psys, b_ob, b_ob, key)) object_updated = true; bool need_update = psys_need_update(b_psys); if (object_updated || need_update) { int tot = psys_count_particles(b_psys); psys->particles.clear(); psys->particles.reserve(tot); int index = 0; BL::ParticleSystem::particles_iterator b_pa; for(b_psys.particles.begin(b_pa); b_pa != b_psys.particles.end(); ++b_pa) { if(use_particle(*b_pa)) { Particle pa; pa.index = index; pa.age = b_scene.frame_current() - b_pa->birth_time(); pa.lifetime = b_pa->lifetime(); pa.location = get_float3(b_pa->location()); pa.rotation = get_float4(b_pa->rotation()); pa.size = b_pa->size(); pa.velocity = get_float3(b_pa->velocity()); pa.angular_velocity = get_float3(b_pa->angular_velocity()); psys->particles.push_back(pa); } ++index; } psys->tag_update(scene); } } void BlenderSync::sync_particle_systems() { /* layer data */ uint scene_layer = render_layer.scene_layer; particle_system_map.pre_sync(); /* object loop */ BL::Scene::objects_iterator b_ob; BL::Scene b_sce = b_scene; for(; b_sce; b_sce = b_sce.background_set()) { for(b_sce.objects.begin(b_ob); b_ob != b_sce.objects.end(); ++b_ob) { bool hide = (render_layer.use_viewport_visibility)? b_ob->hide(): b_ob->hide_render(); uint ob_layer = get_layer(b_ob->layers(), b_ob->layers_local_view(), object_is_light(*b_ob)); CYCLES_LOCAL_LAYER_HACK(render_layer.use_localview, ob_layer); hide = hide || !(ob_layer & scene_layer); if(!hide) { BL::Object::particle_systems_iterator b_psys; for(b_ob->particle_systems.begin(b_psys); b_psys != b_ob->particle_systems.end(); ++b_psys) sync_particles(*b_ob, *b_psys); } } } /* handle removed data and modified pointers */ if(particle_system_map.post_sync()) scene->particle_system_manager->tag_update(scene); } CCL_NAMESPACE_END <|endoftext|>
<commit_before> #include <stdlib.h> #include <functional> #include "gpio.h" #include "odrive_main.h" #include "utils.h" #include "communication/interface_can.hpp" Axis::Axis(const AxisHardwareConfig_t& hw_config, Config_t& config, Encoder& encoder, SensorlessEstimator& sensorless_estimator, Controller& controller, Motor& motor, TrapezoidalTrajectory& trap) : hw_config_(hw_config), config_(config), encoder_(encoder), sensorless_estimator_(sensorless_estimator), controller_(controller), motor_(motor), trap_(trap) { encoder_.axis_ = this; sensorless_estimator_.axis_ = this; controller_.axis_ = this; motor_.axis_ = this; trap_.axis_ = this; decode_step_dir_pins(); } static void step_cb_wrapper(void* ctx) { reinterpret_cast<Axis*>(ctx)->step_cb(); } // @brief Sets up all components of the axis, // such as gate driver and encoder hardware. void Axis::setup() { encoder_.setup(); motor_.setup(); } static void run_state_machine_loop_wrapper(void* ctx) { reinterpret_cast<Axis*>(ctx)->run_state_machine_loop(); reinterpret_cast<Axis*>(ctx)->thread_id_valid_ = false; } // @brief Starts run_state_machine_loop in a new thread void Axis::start_thread() { osThreadDef(thread_def, run_state_machine_loop_wrapper, hw_config_.thread_priority, 0, 4 * 512); thread_id_ = osThreadCreate(osThread(thread_def), this); thread_id_valid_ = true; } // @brief Unblocks the control loop thread. // This is called from the current sense interrupt handler. void Axis::signal_current_meas() { if (thread_id_valid_) osSignalSet(thread_id_, M_SIGNAL_PH_CURRENT_MEAS); } // @brief Blocks until a current measurement is completed // @returns True on success, false otherwise bool Axis::wait_for_current_meas() { return osSignalWait(M_SIGNAL_PH_CURRENT_MEAS, PH_CURRENT_MEAS_TIMEOUT).status == osEventSignal; } // step/direction interface void Axis::step_cb() { if (step_dir_active_) { GPIO_PinState dir_pin = HAL_GPIO_ReadPin(dir_port_, dir_pin_); float dir = (dir_pin == GPIO_PIN_SET) ? 1.0f : -1.0f; controller_.pos_setpoint_ += dir * config_.counts_per_step; } }; void Axis::load_default_step_dir_pin_config( const AxisHardwareConfig_t& hw_config, Config_t* config) { config->step_gpio_pin = hw_config.step_gpio_pin; config->dir_gpio_pin = hw_config.dir_gpio_pin; } void Axis::load_default_can_id(const int& id, Config_t& config){ config.can_node_id = id; } void Axis::decode_step_dir_pins() { step_port_ = get_gpio_port_by_pin(config_.step_gpio_pin); step_pin_ = get_gpio_pin_by_pin(config_.step_gpio_pin); dir_port_ = get_gpio_port_by_pin(config_.dir_gpio_pin); dir_pin_ = get_gpio_pin_by_pin(config_.dir_gpio_pin); } // @brief (de)activates step/dir input void Axis::set_step_dir_active(bool active) { if (active) { // Set up the direction GPIO as input GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = dir_pin_; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(dir_port_, &GPIO_InitStruct); // Subscribe to rising edges of the step GPIO GPIO_subscribe(step_port_, step_pin_, GPIO_PULLDOWN, step_cb_wrapper, this); step_dir_active_ = true; } else { step_dir_active_ = false; // Unsubscribe from step GPIO GPIO_unsubscribe(step_port_, step_pin_); } } // @brief Do axis level checks and call subcomponent do_checks // Returns true if everything is ok. bool Axis::do_checks() { if (!brake_resistor_armed) error_ |= ERROR_BRAKE_RESISTOR_DISARMED; if ((current_state_ != AXIS_STATE_IDLE) && (motor_.armed_state_ == Motor::ARMED_STATE_DISARMED)) // motor got disarmed in something other than the idle loop error_ |= ERROR_MOTOR_DISARMED; if (!(vbus_voltage >= board_config.dc_bus_undervoltage_trip_level)) error_ |= ERROR_DC_BUS_UNDER_VOLTAGE; if (!(vbus_voltage <= board_config.dc_bus_overvoltage_trip_level)) error_ |= ERROR_DC_BUS_OVER_VOLTAGE; // Sub-components should use set_error which will propegate to this error_ motor_.do_checks(); encoder_.do_checks(); // sensorless_estimator_.do_checks(); // controller_.do_checks(); return check_for_errors(); } // @brief Update all esitmators bool Axis::do_updates() { // Sub-components should use set_error which will propegate to this error_ encoder_.update(); sensorless_estimator_.update(); bool ret = check_for_errors(); odCAN->send_heartbeat(this); return ret; } bool Axis::run_lockin_spin() { // Spiral up current for softer rotor lock-in lockin_state_ = LOCKIN_STATE_RAMP; float x = 0.0f; run_control_loop([&]() { float phase = wrap_pm_pi(config_.lockin.ramp_distance * x); float I_mag = config_.lockin.current * x; x += current_meas_period / config_.lockin.ramp_time; if (!motor_.update(I_mag, phase, 0.0f)) return false; return x < 1.0f; }); // Spin states float distance = config_.lockin.ramp_distance; float phase = wrap_pm_pi(distance); float vel = distance / config_.lockin.ramp_time; // Function of states to check if we are done auto spin_done = [&](bool vel_override = false) -> bool { bool done = false; if (config_.lockin.finish_on_vel || vel_override) done = done || fabsf(vel) >= fabsf(config_.lockin.vel); if (config_.lockin.finish_on_distance) done = done || fabsf(distance) >= fabsf(config_.lockin.finish_distance); if (config_.lockin.finish_on_enc_idx) done = done || encoder_.index_found_; return done; }; // Accelerate lockin_state_ = LOCKIN_STATE_ACCELERATE; run_control_loop([&]() { vel += config_.lockin.accel * current_meas_period; distance += vel * current_meas_period; phase = wrap_pm_pi(phase + vel * current_meas_period); if (!motor_.update(config_.lockin.current, phase, vel)) return false; return !spin_done(true); //vel_override to go to next phase }); if (!encoder_.index_found_) encoder_.set_idx_subscribe(true); // Constant speed if (!spin_done()) { lockin_state_ = LOCKIN_STATE_CONST_VEL; vel = config_.lockin.vel; // reset to actual specified vel to avoid small integration error run_control_loop([&]() { distance += vel * current_meas_period; phase = wrap_pm_pi(phase + vel * current_meas_period); if (!motor_.update(config_.lockin.current, phase, vel)) return false; return !spin_done(); }); } lockin_state_ = LOCKIN_STATE_INACTIVE; return check_for_errors(); } // Note run_sensorless_control_loop and run_closed_loop_control_loop are very similar and differ only in where we get the estimate from. bool Axis::run_sensorless_control_loop() { run_control_loop([this](){ if (controller_.config_.control_mode >= Controller::CTRL_MODE_POSITION_CONTROL) return error_ |= ERROR_POS_CTRL_DURING_SENSORLESS, false; // Note that all estimators are updated in the loop prefix in run_control_loop float current_setpoint; if (!controller_.update(sensorless_estimator_.pll_pos_, sensorless_estimator_.vel_estimate_, &current_setpoint)) return error_ |= ERROR_CONTROLLER_FAILED, false; if (!motor_.update(current_setpoint, sensorless_estimator_.phase_, sensorless_estimator_.vel_estimate_)) return false; // set_error should update axis.error_ return true; }); return check_for_errors(); } bool Axis::run_closed_loop_control_loop() { // To avoid any transient on startup, we intialize the setpoint to be the current position controller_.pos_setpoint_ = encoder_.pos_estimate_; set_step_dir_active(config_.enable_step_dir); run_control_loop([this](){ // Note that all estimators are updated in the loop prefix in run_control_loop float current_setpoint; if (!controller_.update(encoder_.pos_estimate_, encoder_.vel_estimate_, &current_setpoint)) return error_ |= ERROR_CONTROLLER_FAILED, false; //TODO: Make controller.set_error float phase_vel = 2*M_PI * encoder_.vel_estimate_ / (float)encoder_.config_.cpr * motor_.config_.pole_pairs; if (!motor_.update(current_setpoint, encoder_.phase_, phase_vel)) return false; // set_error should update axis.error_ return true; }); set_step_dir_active(false); return check_for_errors(); } bool Axis::run_idle_loop() { // run_control_loop ignores missed modulation timing updates // if and only if we're in AXIS_STATE_IDLE safety_critical_disarm_motor_pwm(motor_); run_control_loop([this]() { return true; }); return check_for_errors(); } // Infinite loop that does calibration and enters main control loop as appropriate void Axis::run_state_machine_loop() { // Allocate the map for anti-cogging algorithm and initialize all values to 0.0f // TODO: Move this somewhere else // TODO: respect changes of CPR int encoder_cpr = encoder_.config_.cpr; controller_.anticogging_.cogging_map = (float*)malloc(encoder_cpr * sizeof(float)); if (controller_.anticogging_.cogging_map != NULL) { for (int i = 0; i < encoder_cpr; i++) { controller_.anticogging_.cogging_map[i] = 0.0f; } } // arm! motor_.arm(); for (;;) { // Load the task chain if a specific request is pending if (requested_state_ != AXIS_STATE_UNDEFINED) { size_t pos = 0; if (requested_state_ == AXIS_STATE_STARTUP_SEQUENCE) { if (config_.startup_motor_calibration) task_chain_[pos++] = AXIS_STATE_MOTOR_CALIBRATION; if (config_.startup_encoder_index_search && encoder_.config_.use_index) task_chain_[pos++] = AXIS_STATE_ENCODER_INDEX_SEARCH; if (config_.startup_encoder_offset_calibration) task_chain_[pos++] = AXIS_STATE_ENCODER_OFFSET_CALIBRATION; if (config_.startup_closed_loop_control) task_chain_[pos++] = AXIS_STATE_CLOSED_LOOP_CONTROL; else if (config_.startup_sensorless_control) task_chain_[pos++] = AXIS_STATE_SENSORLESS_CONTROL; task_chain_[pos++] = AXIS_STATE_IDLE; } else if (requested_state_ == AXIS_STATE_FULL_CALIBRATION_SEQUENCE) { task_chain_[pos++] = AXIS_STATE_MOTOR_CALIBRATION; if (encoder_.config_.use_index) task_chain_[pos++] = AXIS_STATE_ENCODER_INDEX_SEARCH; task_chain_[pos++] = AXIS_STATE_ENCODER_OFFSET_CALIBRATION; task_chain_[pos++] = AXIS_STATE_IDLE; } else if (requested_state_ != AXIS_STATE_UNDEFINED) { task_chain_[pos++] = requested_state_; task_chain_[pos++] = AXIS_STATE_IDLE; } task_chain_[pos++] = AXIS_STATE_UNDEFINED; // TODO: bounds checking requested_state_ = AXIS_STATE_UNDEFINED; // Auto-clear any invalid state error error_ &= ~ERROR_INVALID_STATE; } // Note that current_state is a reference to task_chain_[0] // Run the specified state // Handlers should exit if requested_state != AXIS_STATE_UNDEFINED bool status; switch (current_state_) { case AXIS_STATE_MOTOR_CALIBRATION: { status = motor_.run_calibration(); } break; case AXIS_STATE_ENCODER_INDEX_SEARCH: { if (!motor_.is_calibrated_) goto invalid_state_label; if (encoder_.config_.idx_search_unidirectional && motor_.config_.direction==0) goto invalid_state_label; status = encoder_.run_index_search(); } break; case AXIS_STATE_ENCODER_DIR_FIND: { if (!motor_.is_calibrated_) goto invalid_state_label; status = encoder_.run_direction_find(); } break; case AXIS_STATE_ENCODER_OFFSET_CALIBRATION: { if (!motor_.is_calibrated_) goto invalid_state_label; status = encoder_.run_offset_calibration(); } break; case AXIS_STATE_LOCKIN_SPIN: { if (!motor_.is_calibrated_ || motor_.config_.direction==0) goto invalid_state_label; status = run_lockin_spin(); } break; case AXIS_STATE_SENSORLESS_CONTROL: { if (!motor_.is_calibrated_ || motor_.config_.direction==0) goto invalid_state_label; status = run_lockin_spin(); // TODO: restart if desired if (status) { // call to controller.reset() that happend when arming means that vel_setpoint // is zeroed. So we make the setpoint the spinup target for smooth transition. controller_.vel_setpoint_ = config_.lockin.vel; status = run_sensorless_control_loop(); } } break; case AXIS_STATE_CLOSED_LOOP_CONTROL: { if (!motor_.is_calibrated_ || motor_.config_.direction==0) goto invalid_state_label; if (!encoder_.is_ready_) goto invalid_state_label; status = run_closed_loop_control_loop(); } break; case AXIS_STATE_IDLE: { run_idle_loop(); status = motor_.arm(); // done with idling - try to arm the motor } break; default: invalid_state_label: error_ |= ERROR_INVALID_STATE; status = false; // this will set the state to idle break; } // If the state failed, go to idle, else advance task chain if (!status) current_state_ = AXIS_STATE_IDLE; else memcpy(task_chain_, task_chain_ + 1, sizeof(task_chain_) - sizeof(task_chain_[0])); } } <commit_msg>Fix minor CppCheck warning<commit_after> #include <stdlib.h> #include <functional> #include "gpio.h" #include "odrive_main.h" #include "utils.h" #include "communication/interface_can.hpp" Axis::Axis(const AxisHardwareConfig_t& hw_config, Config_t& config, Encoder& encoder, SensorlessEstimator& sensorless_estimator, Controller& controller, Motor& motor, TrapezoidalTrajectory& trap) : hw_config_(hw_config), config_(config), encoder_(encoder), sensorless_estimator_(sensorless_estimator), controller_(controller), motor_(motor), trap_(trap) { encoder_.axis_ = this; sensorless_estimator_.axis_ = this; controller_.axis_ = this; motor_.axis_ = this; trap_.axis_ = this; decode_step_dir_pins(); } static void step_cb_wrapper(void* ctx) { reinterpret_cast<Axis*>(ctx)->step_cb(); } // @brief Sets up all components of the axis, // such as gate driver and encoder hardware. void Axis::setup() { encoder_.setup(); motor_.setup(); } static void run_state_machine_loop_wrapper(void* ctx) { reinterpret_cast<Axis*>(ctx)->run_state_machine_loop(); reinterpret_cast<Axis*>(ctx)->thread_id_valid_ = false; } // @brief Starts run_state_machine_loop in a new thread void Axis::start_thread() { osThreadDef(thread_def, run_state_machine_loop_wrapper, hw_config_.thread_priority, 0, 4 * 512); thread_id_ = osThreadCreate(osThread(thread_def), this); thread_id_valid_ = true; } // @brief Unblocks the control loop thread. // This is called from the current sense interrupt handler. void Axis::signal_current_meas() { if (thread_id_valid_) osSignalSet(thread_id_, M_SIGNAL_PH_CURRENT_MEAS); } // @brief Blocks until a current measurement is completed // @returns True on success, false otherwise bool Axis::wait_for_current_meas() { return osSignalWait(M_SIGNAL_PH_CURRENT_MEAS, PH_CURRENT_MEAS_TIMEOUT).status == osEventSignal; } // step/direction interface void Axis::step_cb() { if (step_dir_active_) { GPIO_PinState dir_pin = HAL_GPIO_ReadPin(dir_port_, dir_pin_); float dir = (dir_pin == GPIO_PIN_SET) ? 1.0f : -1.0f; controller_.pos_setpoint_ += dir * config_.counts_per_step; } }; void Axis::load_default_step_dir_pin_config( const AxisHardwareConfig_t& hw_config, Config_t* config) { config->step_gpio_pin = hw_config.step_gpio_pin; config->dir_gpio_pin = hw_config.dir_gpio_pin; } void Axis::load_default_can_id(const int& id, Config_t& config){ config.can_node_id = id; } void Axis::decode_step_dir_pins() { step_port_ = get_gpio_port_by_pin(config_.step_gpio_pin); step_pin_ = get_gpio_pin_by_pin(config_.step_gpio_pin); dir_port_ = get_gpio_port_by_pin(config_.dir_gpio_pin); dir_pin_ = get_gpio_pin_by_pin(config_.dir_gpio_pin); } // @brief (de)activates step/dir input void Axis::set_step_dir_active(bool active) { if (active) { // Set up the direction GPIO as input GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = dir_pin_; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(dir_port_, &GPIO_InitStruct); // Subscribe to rising edges of the step GPIO GPIO_subscribe(step_port_, step_pin_, GPIO_PULLDOWN, step_cb_wrapper, this); step_dir_active_ = true; } else { step_dir_active_ = false; // Unsubscribe from step GPIO GPIO_unsubscribe(step_port_, step_pin_); } } // @brief Do axis level checks and call subcomponent do_checks // Returns true if everything is ok. bool Axis::do_checks() { if (!brake_resistor_armed) error_ |= ERROR_BRAKE_RESISTOR_DISARMED; if ((current_state_ != AXIS_STATE_IDLE) && (motor_.armed_state_ == Motor::ARMED_STATE_DISARMED)) // motor got disarmed in something other than the idle loop error_ |= ERROR_MOTOR_DISARMED; if (!(vbus_voltage >= board_config.dc_bus_undervoltage_trip_level)) error_ |= ERROR_DC_BUS_UNDER_VOLTAGE; if (!(vbus_voltage <= board_config.dc_bus_overvoltage_trip_level)) error_ |= ERROR_DC_BUS_OVER_VOLTAGE; // Sub-components should use set_error which will propegate to this error_ motor_.do_checks(); encoder_.do_checks(); // sensorless_estimator_.do_checks(); // controller_.do_checks(); return check_for_errors(); } // @brief Update all esitmators bool Axis::do_updates() { // Sub-components should use set_error which will propegate to this error_ encoder_.update(); sensorless_estimator_.update(); bool ret = check_for_errors(); odCAN->send_heartbeat(this); return ret; } bool Axis::run_lockin_spin() { // Spiral up current for softer rotor lock-in lockin_state_ = LOCKIN_STATE_RAMP; float x = 0.0f; run_control_loop([&]() { float phase = wrap_pm_pi(config_.lockin.ramp_distance * x); float I_mag = config_.lockin.current * x; x += current_meas_period / config_.lockin.ramp_time; if (!motor_.update(I_mag, phase, 0.0f)) return false; return x < 1.0f; }); // Spin states float distance = config_.lockin.ramp_distance; float phase = wrap_pm_pi(distance); float vel = distance / config_.lockin.ramp_time; // Function of states to check if we are done auto spin_done = [&](bool vel_override = false) -> bool { bool done = false; if (config_.lockin.finish_on_vel || vel_override) done = done || fabsf(vel) >= fabsf(config_.lockin.vel); if (config_.lockin.finish_on_distance) done = done || fabsf(distance) >= fabsf(config_.lockin.finish_distance); if (config_.lockin.finish_on_enc_idx) done = done || encoder_.index_found_; return done; }; // Accelerate lockin_state_ = LOCKIN_STATE_ACCELERATE; run_control_loop([&]() { vel += config_.lockin.accel * current_meas_period; distance += vel * current_meas_period; phase = wrap_pm_pi(phase + vel * current_meas_period); if (!motor_.update(config_.lockin.current, phase, vel)) return false; return !spin_done(true); //vel_override to go to next phase }); if (!encoder_.index_found_) encoder_.set_idx_subscribe(true); // Constant speed if (!spin_done()) { lockin_state_ = LOCKIN_STATE_CONST_VEL; vel = config_.lockin.vel; // reset to actual specified vel to avoid small integration error run_control_loop([&]() { distance += vel * current_meas_period; phase = wrap_pm_pi(phase + vel * current_meas_period); if (!motor_.update(config_.lockin.current, phase, vel)) return false; return !spin_done(); }); } lockin_state_ = LOCKIN_STATE_INACTIVE; return check_for_errors(); } // Note run_sensorless_control_loop and run_closed_loop_control_loop are very similar and differ only in where we get the estimate from. bool Axis::run_sensorless_control_loop() { run_control_loop([this](){ if (controller_.config_.control_mode >= Controller::CTRL_MODE_POSITION_CONTROL) return error_ |= ERROR_POS_CTRL_DURING_SENSORLESS, false; // Note that all estimators are updated in the loop prefix in run_control_loop float current_setpoint; if (!controller_.update(sensorless_estimator_.pll_pos_, sensorless_estimator_.vel_estimate_, &current_setpoint)) return error_ |= ERROR_CONTROLLER_FAILED, false; if (!motor_.update(current_setpoint, sensorless_estimator_.phase_, sensorless_estimator_.vel_estimate_)) return false; // set_error should update axis.error_ return true; }); return check_for_errors(); } bool Axis::run_closed_loop_control_loop() { // To avoid any transient on startup, we intialize the setpoint to be the current position controller_.pos_setpoint_ = encoder_.pos_estimate_; set_step_dir_active(config_.enable_step_dir); run_control_loop([this](){ // Note that all estimators are updated in the loop prefix in run_control_loop float current_setpoint; if (!controller_.update(encoder_.pos_estimate_, encoder_.vel_estimate_, &current_setpoint)) return error_ |= ERROR_CONTROLLER_FAILED, false; //TODO: Make controller.set_error float phase_vel = 2*M_PI * encoder_.vel_estimate_ / (float)encoder_.config_.cpr * motor_.config_.pole_pairs; if (!motor_.update(current_setpoint, encoder_.phase_, phase_vel)) return false; // set_error should update axis.error_ return true; }); set_step_dir_active(false); return check_for_errors(); } bool Axis::run_idle_loop() { // run_control_loop ignores missed modulation timing updates // if and only if we're in AXIS_STATE_IDLE safety_critical_disarm_motor_pwm(motor_); run_control_loop([this]() { return true; }); return check_for_errors(); } // Infinite loop that does calibration and enters main control loop as appropriate void Axis::run_state_machine_loop() { // Allocate the map for anti-cogging algorithm and initialize all values to 0.0f // TODO: Move this somewhere else // TODO: respect changes of CPR int encoder_cpr = encoder_.config_.cpr; controller_.anticogging_.cogging_map = (float*)malloc(encoder_cpr * sizeof(float)); if (controller_.anticogging_.cogging_map != NULL) { for (int i = 0; i < encoder_cpr; i++) { controller_.anticogging_.cogging_map[i] = 0.0f; } } // arm! motor_.arm(); for (;;) { // Load the task chain if a specific request is pending if (requested_state_ != AXIS_STATE_UNDEFINED) { size_t pos = 0; if (requested_state_ == AXIS_STATE_STARTUP_SEQUENCE) { if (config_.startup_motor_calibration) task_chain_[pos++] = AXIS_STATE_MOTOR_CALIBRATION; if (config_.startup_encoder_index_search && encoder_.config_.use_index) task_chain_[pos++] = AXIS_STATE_ENCODER_INDEX_SEARCH; if (config_.startup_encoder_offset_calibration) task_chain_[pos++] = AXIS_STATE_ENCODER_OFFSET_CALIBRATION; if (config_.startup_closed_loop_control) task_chain_[pos++] = AXIS_STATE_CLOSED_LOOP_CONTROL; else if (config_.startup_sensorless_control) task_chain_[pos++] = AXIS_STATE_SENSORLESS_CONTROL; task_chain_[pos++] = AXIS_STATE_IDLE; } else if (requested_state_ == AXIS_STATE_FULL_CALIBRATION_SEQUENCE) { task_chain_[pos++] = AXIS_STATE_MOTOR_CALIBRATION; if (encoder_.config_.use_index) task_chain_[pos++] = AXIS_STATE_ENCODER_INDEX_SEARCH; task_chain_[pos++] = AXIS_STATE_ENCODER_OFFSET_CALIBRATION; task_chain_[pos++] = AXIS_STATE_IDLE; } else if (requested_state_ != AXIS_STATE_UNDEFINED) { task_chain_[pos++] = requested_state_; task_chain_[pos++] = AXIS_STATE_IDLE; } task_chain_[pos++] = AXIS_STATE_UNDEFINED; // TODO: bounds checking requested_state_ = AXIS_STATE_UNDEFINED; // Auto-clear any invalid state error error_ &= ~ERROR_INVALID_STATE; } // Note that current_state is a reference to task_chain_[0] // Run the specified state // Handlers should exit if requested_state != AXIS_STATE_UNDEFINED bool status; switch (current_state_) { case AXIS_STATE_MOTOR_CALIBRATION: { status = motor_.run_calibration(); } break; case AXIS_STATE_ENCODER_INDEX_SEARCH: { if (!motor_.is_calibrated_) goto invalid_state_label; if (encoder_.config_.idx_search_unidirectional && motor_.config_.direction==0) goto invalid_state_label; status = encoder_.run_index_search(); } break; case AXIS_STATE_ENCODER_DIR_FIND: { if (!motor_.is_calibrated_) goto invalid_state_label; status = encoder_.run_direction_find(); } break; case AXIS_STATE_ENCODER_OFFSET_CALIBRATION: { if (!motor_.is_calibrated_) goto invalid_state_label; status = encoder_.run_offset_calibration(); } break; case AXIS_STATE_LOCKIN_SPIN: { if (!motor_.is_calibrated_ || motor_.config_.direction==0) goto invalid_state_label; status = run_lockin_spin(); } break; case AXIS_STATE_SENSORLESS_CONTROL: { if (!motor_.is_calibrated_ || motor_.config_.direction==0) goto invalid_state_label; status = run_lockin_spin(); // TODO: restart if desired if (status) { // call to controller.reset() that happend when arming means that vel_setpoint // is zeroed. So we make the setpoint the spinup target for smooth transition. controller_.vel_setpoint_ = config_.lockin.vel; status = run_sensorless_control_loop(); } } break; case AXIS_STATE_CLOSED_LOOP_CONTROL: { if (!motor_.is_calibrated_ || motor_.config_.direction==0) goto invalid_state_label; if (!encoder_.is_ready_) goto invalid_state_label; status = run_closed_loop_control_loop(); } break; case AXIS_STATE_IDLE: { run_idle_loop(); status = motor_.arm(); // done with idling - try to arm the motor } break; default: invalid_state_label: error_ |= ERROR_INVALID_STATE; status = false; // this will set the state to idle break; } // If the state failed, go to idle, else advance task chain if (!status) current_state_ = AXIS_STATE_IDLE; else memcpy(task_chain_, task_chain_ + 1, sizeof(task_chain_) - sizeof(task_chain_[0])); } } <|endoftext|>
<commit_before>#include "connection.h" #include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> const size_t K = 1024; const size_t M = 1024*K; const size_t MAX_MSG = 256*K; const size_t READ_BLOCK = MAX_MSG*2; const size_t SEND_BUF = 16*M; const size_t SEND_BUF_EMERGENCY = 18*M; const size_t SEND_BUF_LOW_WATER_MARK = 2*MAX_MSG; namespace asio = boost::asio; namespace chrono = boost::chrono; using namespace std; using namespace bithorde; template <typename Protocol> class ConnectionImpl : public Connection { typedef typename Protocol::socket Socket; typedef typename Protocol::endpoint EndPoint; boost::shared_ptr<Socket> _socket; public: ConnectionImpl(boost::asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, const EndPoint& addr) : Connection(ioSvc, stats), _socket(new Socket(ioSvc)) { _socket->connect(addr); } ConnectionImpl(boost::asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, boost::shared_ptr<Socket>& socket) : Connection(ioSvc, stats) { _socket = socket; } ~ConnectionImpl() { close(); } void trySend() { if (auto msg = _sndQueue.firstMessage()) { _socket->async_write_some(asio::buffer(msg->buf), boost::bind(&Connection::onWritten, shared_from_this(), asio::placeholders::error, asio::placeholders::bytes_transferred) ); } } void tryRead() { _socket->async_read_some(asio::buffer(_rcvBuf.allocate(MAX_MSG), MAX_MSG), boost::bind(&Connection::onRead, shared_from_this(), asio::placeholders::error, asio::placeholders::bytes_transferred ) ); } void close() { if (_socket->is_open()) { _socket->close(); disconnected(); } } }; Message::Deadline Message::NEVER(Message::Deadline::max()); Message::Deadline Message::in(int msec) { return Clock::now()+chrono::milliseconds(msec); } Message::Message(Deadline expires) : expires(expires) { } MessageQueue::MessageQueue() : _size(0) {} std::string MessageQueue::_empty; bool MessageQueue::empty() const { return _queue.empty(); } void MessageQueue::enqueue(Message* msg) { _queue.push_back(msg); _size += msg->buf.size(); } const Message* MessageQueue::firstMessage() { auto now = chrono::steady_clock::now(); while (_queue.size() && _queue.front()->expires < now) { _size -= _queue.front()->buf.size(); delete _queue.front(); _queue.pop_front(); } if (_queue.empty()) { return NULL; } else { _queue.front()->expires = chrono::steady_clock::time_point::max(); return _queue.front(); } } void MessageQueue::pop(size_t amount) { BOOST_ASSERT(_queue.size() > 0); auto msg = _queue.front(); BOOST_ASSERT(amount <= msg->buf.size()); if (amount == msg->buf.size()) { delete msg; _queue.pop_front(); } else { msg->buf = msg->buf.substr(amount); } _size -= amount; } size_t MessageQueue::size() const { return _size; } ConnectionStats::ConnectionStats(const TimerService::Ptr& ts) : _ts(ts), incomingMessagesCurrent(*_ts, "msgs/s", boost::posix_time::seconds(1), 0.2), incomingBitrateCurrent(*_ts, "bit/s", boost::posix_time::seconds(1), 0.2), outgoingMessagesCurrent(*_ts, "msgs/s", boost::posix_time::seconds(1), 0.2), outgoingBitrateCurrent(*_ts, "bit/s", boost::posix_time::seconds(1), 0.2), incomingMessages("msgs"), incomingBytes("bytes"), outgoingMessages("msgs"), outgoingBytes("bytes") { } Connection::Connection(asio::io_service & ioSvc, const ConnectionStats::Ptr& stats) : _state(Connected), _ioSvc(ioSvc), _stats(stats) { } Connection::Pointer Connection::create(asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, const asio::ip::tcp::endpoint& addr) { Pointer c(new ConnectionImpl<asio::ip::tcp>(ioSvc, stats, addr)); c->tryRead(); return c; } Connection::Pointer Connection::create(asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, boost::shared_ptr< asio::ip::tcp::socket >& socket) { Pointer c(new ConnectionImpl<asio::ip::tcp>(ioSvc, stats, socket)); c->tryRead(); return c; } Connection::Pointer Connection::create(asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, const asio::local::stream_protocol::endpoint& addr) { Pointer c(new ConnectionImpl<asio::local::stream_protocol>(ioSvc, stats, addr)); c->tryRead(); return c; } Connection::Pointer Connection::create(asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, boost::shared_ptr< asio::local::stream_protocol::socket >& socket) { Pointer c(new ConnectionImpl<asio::local::stream_protocol>(ioSvc, stats, socket)); c->tryRead(); return c; } void Connection::onRead(const boost::system::error_code& err, size_t count) { if (err || (count == 0)) { close(); return; } else { _rcvBuf.charge(count); _stats->incomingBitrateCurrent += count*8; _stats->incomingBytes += count; } google::protobuf::io::CodedInputStream stream((::google::protobuf::uint8*)_rcvBuf.ptr, _rcvBuf.size); bool res = true; size_t remains; while (res) { remains = stream.BytesUntilLimit(); uint32_t tag = stream.ReadTag(); if (tag == 0) break; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { case HandShake: if (_state != Connected) goto proto_error; res = dequeue<bithorde::HandShake>(HandShake, stream); break; case BindRead: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::BindRead>(BindRead, stream); break; case AssetStatus: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::AssetStatus>(AssetStatus, stream); break; case ReadRequest: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::Read::Request>(ReadRequest, stream); break; case ReadResponse: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::Read::Response>(ReadResponse, stream); break; case BindWrite: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::BindWrite>(BindWrite, stream); break; case DataSegment: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::DataSegment>(DataSegment, stream); break; case HandShakeConfirmed: if (_state != AwaitingAuth) goto proto_error; res = dequeue<bithorde::HandShakeConfirmed>(HandShakeConfirmed, stream); break; case Ping: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::Ping>(Ping, stream); break; default: cerr << "BitHorde protocol warning: unknown message tag" << endl; res = ::google::protobuf::internal::WireFormatLite::SkipMessage(&stream); } } _rcvBuf.pop(_rcvBuf.size-remains); tryRead(); return; proto_error: cerr << "ERROR: BitHorde Protocol Error, Disconnecting" << endl; close(); return; } template <class T> bool Connection::dequeue(MessageType type, ::google::protobuf::io::CodedInputStream &stream) { bool res; T msg; uint32_t length; if (!stream.ReadVarint32(&length)) return false; uint32_t bytesLeft = stream.BytesUntilLimit(); if (length > bytesLeft) return false; _stats->incomingMessages += 1; _stats->incomingMessagesCurrent += 1; ::google::protobuf::io::CodedInputStream::Limit limit = stream.PushLimit(length); if ((res = msg.MergePartialFromCodedStream(&stream))) { message(type, msg); } stream.PopLimit(limit); return res; } ConnectionStats::Ptr Connection::stats() { return _stats; } bool Connection::sendMessage(Connection::MessageType type, const google::protobuf::Message& msg, const Message::Deadline& expires, bool prioritized) { size_t bufLimit = prioritized ? SEND_BUF_EMERGENCY : SEND_BUF; if (_sndQueue.size() > bufLimit) return false; bool wasEmpty = _sndQueue.empty(); // Encode { auto buf = new Message(expires); ::google::protobuf::io::StringOutputStream of(&buf->buf); ::google::protobuf::io::CodedOutputStream stream(&of); stream.WriteTag(::google::protobuf::internal::WireFormatLite::MakeTag(type, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED)); stream.WriteVarint32(msg.ByteSize()); bool encoded = msg.SerializeToCodedStream(&stream); BOOST_ASSERT(encoded); _sndQueue.enqueue(buf); } _stats->outgoingMessages += 1; _stats->outgoingMessagesCurrent += 1; // Push out at once unless _queued; if (wasEmpty) trySend(); return true; } void Connection::onWritten(const boost::system::error_code& err, size_t written) { if ((!err) && (written > 0)) { _stats->outgoingBitrateCurrent += written*8; _stats->outgoingBytes += written; _sndQueue.pop(written); trySend(); if (_sndQueue.size() < SEND_BUF_LOW_WATER_MARK) writable(); } else { cerr << "Failed to write. Disconnecting..." << endl; close(); } } <commit_msg>[lib/connection]Fix broken serialization-code.<commit_after>#include "connection.h" #include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> const size_t K = 1024; const size_t M = 1024*K; const size_t MAX_MSG = 256*K; const size_t READ_BLOCK = MAX_MSG*2; const size_t SEND_BUF = 16*M; const size_t SEND_BUF_EMERGENCY = 18*M; const size_t SEND_BUF_LOW_WATER_MARK = 2*MAX_MSG; namespace asio = boost::asio; namespace chrono = boost::chrono; using namespace std; using namespace bithorde; template <typename Protocol> class ConnectionImpl : public Connection { typedef typename Protocol::socket Socket; typedef typename Protocol::endpoint EndPoint; boost::shared_ptr<Socket> _socket; public: ConnectionImpl(boost::asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, const EndPoint& addr) : Connection(ioSvc, stats), _socket(new Socket(ioSvc)) { _socket->connect(addr); } ConnectionImpl(boost::asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, boost::shared_ptr<Socket>& socket) : Connection(ioSvc, stats) { _socket = socket; } ~ConnectionImpl() { close(); } void trySend() { if (auto msg = _sndQueue.firstMessage()) { _socket->async_write_some(asio::buffer(msg->buf), boost::bind(&Connection::onWritten, shared_from_this(), asio::placeholders::error, asio::placeholders::bytes_transferred) ); } } void tryRead() { _socket->async_read_some(asio::buffer(_rcvBuf.allocate(MAX_MSG), MAX_MSG), boost::bind(&Connection::onRead, shared_from_this(), asio::placeholders::error, asio::placeholders::bytes_transferred ) ); } void close() { if (_socket->is_open()) { _socket->close(); disconnected(); } } }; Message::Deadline Message::NEVER(Message::Deadline::max()); Message::Deadline Message::in(int msec) { return Clock::now()+chrono::milliseconds(msec); } Message::Message(Deadline expires) : expires(expires) { } MessageQueue::MessageQueue() : _size(0) {} std::string MessageQueue::_empty; bool MessageQueue::empty() const { return _queue.empty(); } void MessageQueue::enqueue(Message* msg) { _queue.push_back(msg); _size += msg->buf.size(); } const Message* MessageQueue::firstMessage() { auto now = chrono::steady_clock::now(); while (_queue.size() && _queue.front()->expires < now) { _size -= _queue.front()->buf.size(); delete _queue.front(); _queue.pop_front(); } if (_queue.empty()) { return NULL; } else { _queue.front()->expires = chrono::steady_clock::time_point::max(); return _queue.front(); } } void MessageQueue::pop(size_t amount) { BOOST_ASSERT(_queue.size() > 0); auto msg = _queue.front(); BOOST_ASSERT(amount <= msg->buf.size()); if (amount == msg->buf.size()) { delete msg; _queue.pop_front(); } else { msg->buf = msg->buf.substr(amount); } _size -= amount; } size_t MessageQueue::size() const { return _size; } ConnectionStats::ConnectionStats(const TimerService::Ptr& ts) : _ts(ts), incomingMessagesCurrent(*_ts, "msgs/s", boost::posix_time::seconds(1), 0.2), incomingBitrateCurrent(*_ts, "bit/s", boost::posix_time::seconds(1), 0.2), outgoingMessagesCurrent(*_ts, "msgs/s", boost::posix_time::seconds(1), 0.2), outgoingBitrateCurrent(*_ts, "bit/s", boost::posix_time::seconds(1), 0.2), incomingMessages("msgs"), incomingBytes("bytes"), outgoingMessages("msgs"), outgoingBytes("bytes") { } Connection::Connection(asio::io_service & ioSvc, const ConnectionStats::Ptr& stats) : _state(Connected), _ioSvc(ioSvc), _stats(stats) { } Connection::Pointer Connection::create(asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, const asio::ip::tcp::endpoint& addr) { Pointer c(new ConnectionImpl<asio::ip::tcp>(ioSvc, stats, addr)); c->tryRead(); return c; } Connection::Pointer Connection::create(asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, boost::shared_ptr< asio::ip::tcp::socket >& socket) { Pointer c(new ConnectionImpl<asio::ip::tcp>(ioSvc, stats, socket)); c->tryRead(); return c; } Connection::Pointer Connection::create(asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, const asio::local::stream_protocol::endpoint& addr) { Pointer c(new ConnectionImpl<asio::local::stream_protocol>(ioSvc, stats, addr)); c->tryRead(); return c; } Connection::Pointer Connection::create(asio::io_service& ioSvc, const ConnectionStats::Ptr& stats, boost::shared_ptr< asio::local::stream_protocol::socket >& socket) { Pointer c(new ConnectionImpl<asio::local::stream_protocol>(ioSvc, stats, socket)); c->tryRead(); return c; } void Connection::onRead(const boost::system::error_code& err, size_t count) { if (err || (count == 0)) { close(); return; } else { _rcvBuf.charge(count); _stats->incomingBitrateCurrent += count*8; _stats->incomingBytes += count; } google::protobuf::io::CodedInputStream stream((::google::protobuf::uint8*)_rcvBuf.ptr, _rcvBuf.size); bool res = true; size_t remains; while (res) { remains = stream.BytesUntilLimit(); uint32_t tag = stream.ReadTag(); if (tag == 0) break; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { case HandShake: if (_state != Connected) goto proto_error; res = dequeue<bithorde::HandShake>(HandShake, stream); break; case BindRead: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::BindRead>(BindRead, stream); break; case AssetStatus: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::AssetStatus>(AssetStatus, stream); break; case ReadRequest: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::Read::Request>(ReadRequest, stream); break; case ReadResponse: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::Read::Response>(ReadResponse, stream); break; case BindWrite: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::BindWrite>(BindWrite, stream); break; case DataSegment: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::DataSegment>(DataSegment, stream); break; case HandShakeConfirmed: if (_state != AwaitingAuth) goto proto_error; res = dequeue<bithorde::HandShakeConfirmed>(HandShakeConfirmed, stream); break; case Ping: if (_state == Authenticated) goto proto_error; res = dequeue<bithorde::Ping>(Ping, stream); break; default: cerr << "BitHorde protocol warning: unknown message tag" << endl; res = ::google::protobuf::internal::WireFormatLite::SkipMessage(&stream); } } _rcvBuf.pop(_rcvBuf.size-remains); tryRead(); return; proto_error: cerr << "ERROR: BitHorde Protocol Error, Disconnecting" << endl; close(); return; } template <class T> bool Connection::dequeue(MessageType type, ::google::protobuf::io::CodedInputStream &stream) { bool res; T msg; uint32_t length; if (!stream.ReadVarint32(&length)) return false; uint32_t bytesLeft = stream.BytesUntilLimit(); if (length > bytesLeft) return false; _stats->incomingMessages += 1; _stats->incomingMessagesCurrent += 1; ::google::protobuf::io::CodedInputStream::Limit limit = stream.PushLimit(length); if ((res = msg.MergePartialFromCodedStream(&stream))) { message(type, msg); } stream.PopLimit(limit); return res; } ConnectionStats::Ptr Connection::stats() { return _stats; } bool Connection::sendMessage(Connection::MessageType type, const google::protobuf::Message& msg, const Message::Deadline& expires, bool prioritized) { size_t bufLimit = prioritized ? SEND_BUF_EMERGENCY : SEND_BUF; if (_sndQueue.size() > bufLimit) return false; bool wasEmpty = _sndQueue.empty(); auto buf = new Message(expires); // Encode { ::google::protobuf::io::StringOutputStream of(&buf->buf); ::google::protobuf::io::CodedOutputStream stream(&of); stream.WriteTag(::google::protobuf::internal::WireFormatLite::MakeTag(type, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED)); stream.WriteVarint32(msg.ByteSize()); bool encoded = msg.SerializeToCodedStream(&stream); BOOST_ASSERT(encoded); } _sndQueue.enqueue(buf); _stats->outgoingMessages += 1; _stats->outgoingMessagesCurrent += 1; // Push out at once unless _queued; if (wasEmpty) trySend(); return true; } void Connection::onWritten(const boost::system::error_code& err, size_t written) { if ((!err) && (written > 0)) { _stats->outgoingBitrateCurrent += written*8; _stats->outgoingBytes += written; _sndQueue.pop(written); trySend(); if (_sndQueue.size() < SEND_BUF_LOW_WATER_MARK) writable(); } else { cerr << "Failed to write. Disconnecting..." << endl; close(); } } <|endoftext|>
<commit_before>## This file is a template. The comment below is emitted ## into the rendered file; feel free to edit this file. // !!! WARNING: This is a GENERATED Code..Please do NOT Edit !!! <% interfaceDict = {} %>\ %for key in sensorDict.iterkeys(): <% sensor = sensorDict[key] serviceInterface = sensor["serviceInterface"] if serviceInterface == "org.freedesktop.DBus.Properties": updateFunc = "set::" getFunc = "get::" elif serviceInterface == "xyz.openbmc_project.Inventory.Manager": updateFunc = "notify::" getFunc = "inventory::get::" else: assert "Un-supported interface: " + serviceInterface endif if serviceInterface not in interfaceDict: interfaceDict[serviceInterface] = {} interfaceDict[serviceInterface]["updateFunc"] = updateFunc interfaceDict[serviceInterface]["getFunc"] = getFunc %>\ % endfor #include "types.hpp" #include "sensordatahandler.hpp" using namespace ipmi::sensor; extern const IdInfoMap sensors = { % for key in sensorDict.iterkeys(): % if key: {${key},{ <% sensor = sensorDict[key] interfaces = sensor["interfaces"] path = sensor["path"] serviceInterface = sensor["serviceInterface"] sensorType = sensor["sensorType"] entityID = sensor.get("entityID", 0) instance = sensor.get("entityInstance", 0) readingType = sensor["sensorReadingType"] multiplier = sensor.get("multiplierM", 1) offsetB = sensor.get("offsetB", 0) exp = sensor.get("bExp", 0) rExp = sensor.get("rExp", 0) unit = sensor.get("unit", "") scale = sensor.get("scale", 0) hasScale = "true" if "scale" in sensor.keys() else "false" valueReadingType = sensor["readingType"] sensorNamePattern = sensor.get("sensorNamePattern", "nameLeaf") sensorNameFunc = "get::" + sensorNamePattern updateFunc = interfaceDict[serviceInterface]["updateFunc"] updateFunc += sensor["readingType"] getFunc = interfaceDict[serviceInterface]["getFunc"] getFunc += sensor["readingType"] if "readingAssertion" == valueReadingType or "readingData" == valueReadingType: for interface,properties in interfaces.items(): for dbus_property,property_value in properties.items(): for offset,values in property_value["Offsets"].items(): valueType = values["type"] updateFunc = "set::" + valueReadingType + "<" + valueType + ">" getFunc = "get::" + valueReadingType + "<" + valueType + ">" sensorInterface = serviceInterface if serviceInterface == "org.freedesktop.DBus.Properties": sensorInterface = next(iter(interfaces)) mutability = sensor.get("mutability", "Mutability::Read") %> ${entityID},${instance},${sensorType},"${path}","${sensorInterface}", ${readingType},${multiplier},${offsetB},${exp}, ${offsetB * pow(10,exp)}, ${rExp}, ${hasScale},${scale},"${unit}", ${updateFunc},${getFunc},Mutability(${mutability}),${sensorNameFunc},{ % for interface,properties in interfaces.items(): {"${interface}",{ % for dbus_property,property_value in properties.items(): {"${dbus_property}",{ <% try: preReq = property_value["Prereqs"] except KeyError, e: preReq = dict() %>\ { % for preOffset,preValues in preReq.items(): { ${preOffset},{ % for name,value in preValues.items(): % if name == "type": <% continue %>\ % endif <% value = str(value).lower() %>\ ${value}, % endfor } }, % endfor }, { % for offset,values in property_value["Offsets"].items(): { ${offset},{ % if offset == 0xFF: }}, <% continue %>\ % endif <% valueType = values["type"] %>\ <% try: skip = values["skipOn"] if skip == "assert": skipVal = "SkipAssertion::ASSERT" elif skip == "deassert": skipVal = "SkipAssertion::DEASSERT" else: assert "Unknown skip value " + str(skip) except KeyError, e: skipVal = "SkipAssertion::NONE" %>\ ${skipVal}, % for name,value in values.items(): % if name == "type" or name == "skipOn": <% continue %>\ % endif % if valueType == "string": std::string("${value}"), % elif valueType == "bool": <% value = str(value).lower() %>\ ${value}, % else: ${value}, % endif % endfor } }, % endfor }}}, % endfor }}, % endfor }, }}, % endif % endfor }; <commit_msg>Fix the exponent B in writesensors mako template<commit_after>## This file is a template. The comment below is emitted ## into the rendered file; feel free to edit this file. // !!! WARNING: This is a GENERATED Code..Please do NOT Edit !!! <% interfaceDict = {} %>\ %for key in sensorDict.iterkeys(): <% sensor = sensorDict[key] serviceInterface = sensor["serviceInterface"] if serviceInterface == "org.freedesktop.DBus.Properties": updateFunc = "set::" getFunc = "get::" elif serviceInterface == "xyz.openbmc_project.Inventory.Manager": updateFunc = "notify::" getFunc = "inventory::get::" else: assert "Un-supported interface: " + serviceInterface endif if serviceInterface not in interfaceDict: interfaceDict[serviceInterface] = {} interfaceDict[serviceInterface]["updateFunc"] = updateFunc interfaceDict[serviceInterface]["getFunc"] = getFunc %>\ % endfor #include "types.hpp" #include "sensordatahandler.hpp" using namespace ipmi::sensor; extern const IdInfoMap sensors = { % for key in sensorDict.iterkeys(): % if key: {${key},{ <% sensor = sensorDict[key] interfaces = sensor["interfaces"] path = sensor["path"] serviceInterface = sensor["serviceInterface"] sensorType = sensor["sensorType"] entityID = sensor.get("entityID", 0) instance = sensor.get("entityInstance", 0) readingType = sensor["sensorReadingType"] multiplier = sensor.get("multiplierM", 1) offsetB = sensor.get("offsetB", 0) bExp = sensor.get("bExp", 0) rExp = sensor.get("rExp", 0) unit = sensor.get("unit", "") scale = sensor.get("scale", 0) hasScale = "true" if "scale" in sensor.keys() else "false" valueReadingType = sensor["readingType"] sensorNamePattern = sensor.get("sensorNamePattern", "nameLeaf") sensorNameFunc = "get::" + sensorNamePattern updateFunc = interfaceDict[serviceInterface]["updateFunc"] updateFunc += sensor["readingType"] getFunc = interfaceDict[serviceInterface]["getFunc"] getFunc += sensor["readingType"] if "readingAssertion" == valueReadingType or "readingData" == valueReadingType: for interface,properties in interfaces.items(): for dbus_property,property_value in properties.items(): for offset,values in property_value["Offsets"].items(): valueType = values["type"] updateFunc = "set::" + valueReadingType + "<" + valueType + ">" getFunc = "get::" + valueReadingType + "<" + valueType + ">" sensorInterface = serviceInterface if serviceInterface == "org.freedesktop.DBus.Properties": sensorInterface = next(iter(interfaces)) mutability = sensor.get("mutability", "Mutability::Read") %> ${entityID},${instance},${sensorType},"${path}","${sensorInterface}", ${readingType},${multiplier},${offsetB},${bExp}, ${offsetB * pow(10,bExp)}, ${rExp}, ${hasScale},${scale},"${unit}", ${updateFunc},${getFunc},Mutability(${mutability}),${sensorNameFunc},{ % for interface,properties in interfaces.items(): {"${interface}",{ % for dbus_property,property_value in properties.items(): {"${dbus_property}",{ <% try: preReq = property_value["Prereqs"] except KeyError, e: preReq = dict() %>\ { % for preOffset,preValues in preReq.items(): { ${preOffset},{ % for name,value in preValues.items(): % if name == "type": <% continue %>\ % endif <% value = str(value).lower() %>\ ${value}, % endfor } }, % endfor }, { % for offset,values in property_value["Offsets"].items(): { ${offset},{ % if offset == 0xFF: }}, <% continue %>\ % endif <% valueType = values["type"] %>\ <% try: skip = values["skipOn"] if skip == "assert": skipVal = "SkipAssertion::ASSERT" elif skip == "deassert": skipVal = "SkipAssertion::DEASSERT" else: assert "Unknown skip value " + str(skip) except KeyError, e: skipVal = "SkipAssertion::NONE" %>\ ${skipVal}, % for name,value in values.items(): % if name == "type" or name == "skipOn": <% continue %>\ % endif % if valueType == "string": std::string("${value}"), % elif valueType == "bool": <% value = str(value).lower() %>\ ${value}, % else: ${value}, % endif % endfor } }, % endfor }}}, % endfor }}, % endfor }, }}, % endif % endfor }; <|endoftext|>
<commit_before>/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2017 ArkGame authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "AFCNetClient.h" #include <string.h> #if ARK_PLATFORM == PLATFORM_WIN #include <WS2tcpip.h> #include <winsock2.h> #pragma comment(lib,"Ws2_32.lib") #pragma comment(lib,"event.lib") #pragma comment(lib,"event_core.lib") #elif ARK_PLATFORM == PLATFORM_APPLE #include <arpa/inet.h> #endif #include "event2/bufferevent_struct.h" #include "event2/event.h" bool AFCNetClient::Execute() { ProcessMsgLogicThread(); return true; } void AFCNetClient::ProcessMsgLogicThread() { { AFScopeRdLock xGuard(mRWLock); ProcessMsgLogicThread(m_pClientObject.get()); } if(NULL != m_pClientObject.get() && m_pClientObject->NeedRemove()) { AFScopeWrLock xGuard(mRWLock); m_pClientObject.release(); } } void AFCNetClient::ProcessMsgLogicThread(NetObject* pEntity) { if(pEntity == nullptr) { return; } //Handle Msg; const int nReceiveCount = pEntity->mqMsgFromNet.Count(); for(size_t i = 0; (i < nReceiveCount); i++) { MsgFromNetInfo* pMsgFromNet(NULL); if(!pEntity->mqMsgFromNet.Pop(pMsgFromNet)) { break; } if(!pMsgFromNet) { continue; } switch(pMsgFromNet->nType) { case RECIVEDATA: { int nRet = 0; if(mRecvCB) { mRecvCB(pMsgFromNet->xHead, pMsgFromNet->xHead.GetMsgID(), pMsgFromNet->strMsg.c_str(), pMsgFromNet->strMsg.size(), pEntity->GetClientID()); } } break; case CONNECTED: { mEventCB((NetEventType)pMsgFromNet->nType, pMsgFromNet->xClientID, mnServerID); } break; case DISCONNECTED: { mEventCB((NetEventType)pMsgFromNet->nType, pMsgFromNet->xClientID, mnServerID); pEntity->SetNeedRemove(true); } break; default: break; } delete pMsgFromNet; } } void AFCNetClient::Initialization(const std::string& strAddrPort, const int nServerID) { #ifdef _MSC_VER WSADATA wsa_data; WSAStartup(MAKEWORD(2, 2), &wsa_data); #endif mstrIPPort = strAddrPort; mnServerID = nServerID; m_pThread = std::make_unique<evpp::EventLoopThread>(); m_pThread->set_name("TCPClientThread"); m_pThread->Start(); m_pClient = std::make_unique<evpp::TCPClient>(m_pThread->loop(), mstrIPPort, "TCPPingPongClient"); m_pClient->SetConnectionCallback(std::bind(&AFCNetClient::OnClientConnectionInner,this, std::placeholders::_1)); m_pClient->SetMessageCallback(std::bind(&AFCNetClient::OnMessageInner, this, std::placeholders::_1, std::placeholders::_2)); m_pClient->set_auto_reconnect(false); m_pClient->Connect(); bWorking = true; } bool AFCNetClient::Final() { if(!CloseSocketAll()) { //add log } m_pThread->Stop(true); bWorking = false; return true; } bool AFCNetClient::CloseSocketAll() { m_pClient->Disconnect(); return true; } bool AFCNetClient::SendMsg(const char* msg, const uint32_t nLen, const AFGUID& xClient) { if(m_pClient->conn().get()) { m_pClient->conn()->Send(msg, nLen); } return false; } bool AFCNetClient::CloseNetObject(const AFGUID& xClient) { m_pClient->Disconnect(); return true; } bool AFCNetClient::DismantleNet(NetObject* pEntity) { for(; pEntity->GetBuffLen() >= AFIMsgHead::ARK_MSG_HEAD_LENGTH;) { AFCMsgHead xHead; int nMsgBodyLength = DeCode(pEntity->GetBuff(), pEntity->GetBuffLen(), xHead); if(nMsgBodyLength >= 0 && xHead.GetMsgID() > 0) { MsgFromNetInfo* pNetInfo = new MsgFromNetInfo(pEntity->GetConnPtr()); pNetInfo->xHead = xHead; pNetInfo->nType = RECIVEDATA; pNetInfo->strMsg.append(pEntity->GetBuff() + AFIMsgHead::ARK_MSG_HEAD_LENGTH, nMsgBodyLength); pEntity->mqMsgFromNet.Push(pNetInfo); int nNewSize = pEntity->RemoveBuff(nMsgBodyLength + AFIMsgHead::ARK_MSG_HEAD_LENGTH); } else { break; } } return true; } void AFCNetClient::log_cb(int severity, const char* msg) { } bool AFCNetClient::IsServer() { return false; } bool AFCNetClient::Log(int severity, const char* msg) { log_cb(severity, msg); return true; } bool AFCNetClient::StopAfter(double dTime) { m_pThread->loop()->RunAfter(evpp::Duration(dTime), [&]() { bWorking = false; }); return true; } void AFCNetClient::OnClientConnection(const evpp::TCPConnPtr& conn, void* pData) { AFCNetClient * pClient = (AFCNetClient*)(pData); if(pClient) { pClient->OnClientConnectionInner(conn); } } void AFCNetClient::OnClientConnectionInner(const evpp::TCPConnPtr& conn) { if(conn->IsConnected()) { conn->SetTCPNoDelay(true); MsgFromNetInfo* pMsg = new MsgFromNetInfo(conn); pMsg->xClientID = conn->id(); pMsg->nType = CONNECTED; { AFScopeWrLock xGuard(mRWLock); NetObject* pEntity = new NetObject(this, pMsg->xClientID, conn); conn->set_context(evpp::Any(pEntity)); m_pClientObject.reset(pEntity); pEntity->mqMsgFromNet.Push(pMsg); } } else { MsgFromNetInfo* pMsg = new MsgFromNetInfo(conn); pMsg->xClientID = conn->id(); pMsg->nType = DISCONNECTED; //主线程不能直接删除。不然这里就野了 if(!conn->context().IsEmpty()) { NetObject* pEntity = evpp::any_cast<NetObject*>(conn->context()); pEntity->mqMsgFromNet.Push(pMsg); conn->set_context(evpp::Any(nullptr)); } } } void AFCNetClient::OnMessage(const evpp::TCPConnPtr& conn, evpp::Buffer* msg, void* pData) { AFCNetClient * pNet = (AFCNetClient*)pData; if(pNet) { pNet->OnMessageInner(conn, msg); } } void AFCNetClient::OnMessageInner(const evpp::TCPConnPtr& conn, evpp::Buffer* msg) { if(msg == nullptr) { return; } nReceiverSize += msg->length(); NetObject* pEntity = evpp::any_cast<NetObject*>(conn->context()); if(pEntity == nullptr) { return; } evpp::Slice xMsgBuff; xMsgBuff = msg->NextAll(); int nRet = pEntity->AddBuff(xMsgBuff.data(), xMsgBuff.size()); bool bRet = DismantleNet(pEntity); if(!bRet) { //add log } } bool AFCNetClient::SendMsgWithOutHead(const int16_t nMsgID, const char* msg, const uint32_t nLen, const AFGUID & xClientID, const AFGUID& xPlayerID) { std::string strOutData; AFCMsgHead xHead; xHead.SetMsgID(nMsgID); xHead.SetPlayerID(xPlayerID); xHead.SetBodyLength(nLen); int nAllLen = EnCode(xHead, msg, nLen, strOutData); if(nAllLen == nLen + AFIMsgHead::ARK_MSG_HEAD_LENGTH) { return SendMsg(strOutData.c_str(), strOutData.length(), xClientID); } return false; } int AFCNetClient::EnCode(const AFCMsgHead& xHead, const char* strData, const uint32_t unDataLen, std::string& strOutData) { char szHead[AFIMsgHead::ARK_MSG_HEAD_LENGTH] = { 0 }; int nSize = xHead.EnCode(szHead); strOutData.clear(); strOutData.append(szHead, AFIMsgHead::ARK_MSG_HEAD_LENGTH); strOutData.append(strData, unDataLen); return xHead.GetBodyLength() + AFIMsgHead::ARK_MSG_HEAD_LENGTH; } int AFCNetClient::DeCode(const char* strData, const uint32_t unAllLen, AFCMsgHead & xHead) { if(unAllLen < AFIMsgHead::ARK_MSG_HEAD_LENGTH) { return -1; } if(AFIMsgHead::ARK_MSG_HEAD_LENGTH != xHead.DeCode(strData)) { return -2; } if(xHead.GetBodyLength() > (unAllLen - AFIMsgHead::ARK_MSG_HEAD_LENGTH)) { return -3; } return xHead.GetBodyLength(); }<commit_msg>add STL include file<commit_after>/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2017 ArkGame authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <string.h> #include <memory> #include "AFCNetClient.h" #if ARK_PLATFORM == PLATFORM_WIN #include <WS2tcpip.h> #include <winsock2.h> #pragma comment(lib,"Ws2_32.lib") #pragma comment(lib,"event.lib") #pragma comment(lib,"event_core.lib") #elif ARK_PLATFORM == PLATFORM_APPLE #include <arpa/inet.h> #endif #include "event2/bufferevent_struct.h" #include "event2/event.h" bool AFCNetClient::Execute() { ProcessMsgLogicThread(); return true; } void AFCNetClient::ProcessMsgLogicThread() { { AFScopeRdLock xGuard(mRWLock); ProcessMsgLogicThread(m_pClientObject.get()); } if(NULL != m_pClientObject.get() && m_pClientObject->NeedRemove()) { AFScopeWrLock xGuard(mRWLock); m_pClientObject.release(); } } void AFCNetClient::ProcessMsgLogicThread(NetObject* pEntity) { if(pEntity == nullptr) { return; } //Handle Msg; const int nReceiveCount = pEntity->mqMsgFromNet.Count(); for(size_t i = 0; (i < nReceiveCount); i++) { MsgFromNetInfo* pMsgFromNet(NULL); if(!pEntity->mqMsgFromNet.Pop(pMsgFromNet)) { break; } if(!pMsgFromNet) { continue; } switch(pMsgFromNet->nType) { case RECIVEDATA: { int nRet = 0; if(mRecvCB) { mRecvCB(pMsgFromNet->xHead, pMsgFromNet->xHead.GetMsgID(), pMsgFromNet->strMsg.c_str(), pMsgFromNet->strMsg.size(), pEntity->GetClientID()); } } break; case CONNECTED: { mEventCB((NetEventType)pMsgFromNet->nType, pMsgFromNet->xClientID, mnServerID); } break; case DISCONNECTED: { mEventCB((NetEventType)pMsgFromNet->nType, pMsgFromNet->xClientID, mnServerID); pEntity->SetNeedRemove(true); } break; default: break; } delete pMsgFromNet; } } void AFCNetClient::Initialization(const std::string& strAddrPort, const int nServerID) { #ifdef _MSC_VER WSADATA wsa_data; WSAStartup(MAKEWORD(2, 2), &wsa_data); #endif mstrIPPort = strAddrPort; mnServerID = nServerID; m_pThread = std::make_unique<evpp::EventLoopThread>(); m_pThread->set_name("TCPClientThread"); m_pThread->Start(); m_pClient = std::make_unique<evpp::TCPClient>(m_pThread->loop(), mstrIPPort, "TCPPingPongClient"); m_pClient->SetConnectionCallback(std::bind(&AFCNetClient::OnClientConnectionInner,this, std::placeholders::_1)); m_pClient->SetMessageCallback(std::bind(&AFCNetClient::OnMessageInner, this, std::placeholders::_1, std::placeholders::_2)); m_pClient->set_auto_reconnect(false); m_pClient->Connect(); bWorking = true; } bool AFCNetClient::Final() { if(!CloseSocketAll()) { //add log } m_pThread->Stop(true); bWorking = false; return true; } bool AFCNetClient::CloseSocketAll() { m_pClient->Disconnect(); return true; } bool AFCNetClient::SendMsg(const char* msg, const uint32_t nLen, const AFGUID& xClient) { if(m_pClient->conn().get()) { m_pClient->conn()->Send(msg, nLen); } return false; } bool AFCNetClient::CloseNetObject(const AFGUID& xClient) { m_pClient->Disconnect(); return true; } bool AFCNetClient::DismantleNet(NetObject* pEntity) { for(; pEntity->GetBuffLen() >= AFIMsgHead::ARK_MSG_HEAD_LENGTH;) { AFCMsgHead xHead; int nMsgBodyLength = DeCode(pEntity->GetBuff(), pEntity->GetBuffLen(), xHead); if(nMsgBodyLength >= 0 && xHead.GetMsgID() > 0) { MsgFromNetInfo* pNetInfo = new MsgFromNetInfo(pEntity->GetConnPtr()); pNetInfo->xHead = xHead; pNetInfo->nType = RECIVEDATA; pNetInfo->strMsg.append(pEntity->GetBuff() + AFIMsgHead::ARK_MSG_HEAD_LENGTH, nMsgBodyLength); pEntity->mqMsgFromNet.Push(pNetInfo); int nNewSize = pEntity->RemoveBuff(nMsgBodyLength + AFIMsgHead::ARK_MSG_HEAD_LENGTH); } else { break; } } return true; } void AFCNetClient::log_cb(int severity, const char* msg) { } bool AFCNetClient::IsServer() { return false; } bool AFCNetClient::Log(int severity, const char* msg) { log_cb(severity, msg); return true; } bool AFCNetClient::StopAfter(double dTime) { m_pThread->loop()->RunAfter(evpp::Duration(dTime), [&]() { bWorking = false; }); return true; } void AFCNetClient::OnClientConnection(const evpp::TCPConnPtr& conn, void* pData) { AFCNetClient * pClient = (AFCNetClient*)(pData); if(pClient) { pClient->OnClientConnectionInner(conn); } } void AFCNetClient::OnClientConnectionInner(const evpp::TCPConnPtr& conn) { if(conn->IsConnected()) { conn->SetTCPNoDelay(true); MsgFromNetInfo* pMsg = new MsgFromNetInfo(conn); pMsg->xClientID = conn->id(); pMsg->nType = CONNECTED; { AFScopeWrLock xGuard(mRWLock); NetObject* pEntity = new NetObject(this, pMsg->xClientID, conn); conn->set_context(evpp::Any(pEntity)); m_pClientObject.reset(pEntity); pEntity->mqMsgFromNet.Push(pMsg); } } else { MsgFromNetInfo* pMsg = new MsgFromNetInfo(conn); pMsg->xClientID = conn->id(); pMsg->nType = DISCONNECTED; //主线程不能直接删除。不然这里就野了 if(!conn->context().IsEmpty()) { NetObject* pEntity = evpp::any_cast<NetObject*>(conn->context()); pEntity->mqMsgFromNet.Push(pMsg); conn->set_context(evpp::Any(nullptr)); } } } void AFCNetClient::OnMessage(const evpp::TCPConnPtr& conn, evpp::Buffer* msg, void* pData) { AFCNetClient * pNet = (AFCNetClient*)pData; if(pNet) { pNet->OnMessageInner(conn, msg); } } void AFCNetClient::OnMessageInner(const evpp::TCPConnPtr& conn, evpp::Buffer* msg) { if(msg == nullptr) { return; } nReceiverSize += msg->length(); NetObject* pEntity = evpp::any_cast<NetObject*>(conn->context()); if(pEntity == nullptr) { return; } evpp::Slice xMsgBuff; xMsgBuff = msg->NextAll(); int nRet = pEntity->AddBuff(xMsgBuff.data(), xMsgBuff.size()); bool bRet = DismantleNet(pEntity); if(!bRet) { //add log } } bool AFCNetClient::SendMsgWithOutHead(const int16_t nMsgID, const char* msg, const uint32_t nLen, const AFGUID & xClientID, const AFGUID& xPlayerID) { std::string strOutData; AFCMsgHead xHead; xHead.SetMsgID(nMsgID); xHead.SetPlayerID(xPlayerID); xHead.SetBodyLength(nLen); int nAllLen = EnCode(xHead, msg, nLen, strOutData); if(nAllLen == nLen + AFIMsgHead::ARK_MSG_HEAD_LENGTH) { return SendMsg(strOutData.c_str(), strOutData.length(), xClientID); } return false; } int AFCNetClient::EnCode(const AFCMsgHead& xHead, const char* strData, const uint32_t unDataLen, std::string& strOutData) { char szHead[AFIMsgHead::ARK_MSG_HEAD_LENGTH] = { 0 }; int nSize = xHead.EnCode(szHead); strOutData.clear(); strOutData.append(szHead, AFIMsgHead::ARK_MSG_HEAD_LENGTH); strOutData.append(strData, unDataLen); return xHead.GetBodyLength() + AFIMsgHead::ARK_MSG_HEAD_LENGTH; } int AFCNetClient::DeCode(const char* strData, const uint32_t unAllLen, AFCMsgHead & xHead) { if(unAllLen < AFIMsgHead::ARK_MSG_HEAD_LENGTH) { return -1; } if(AFIMsgHead::ARK_MSG_HEAD_LENGTH != xHead.DeCode(strData)) { return -2; } if(xHead.GetBodyLength() > (unAllLen - AFIMsgHead::ARK_MSG_HEAD_LENGTH)) { return -3; } return xHead.GetBodyLength(); }<|endoftext|>
<commit_before>#pragma once #include <Llama.h> #include <Sprite.h> #include <Texture.h> #include <MeshInterface.h> #include <Easing.h> Llama::Llama(Shader * _shader) : llama(new Sprite(_shader)), isHopping(false), hopSpeed(1.f), hopDuration(1.f), hopLength(5.f), hopHeight(2.f), currHopTime(0.f) { Texture * texture = new Texture("assets/textures/PureBread-logo.png", true, false); texture->load(); llama->mesh->pushTexture2D(texture); childTransform->addChild(llama); } Llama::~Llama(){ } void Llama::update(Step * _step){ Entity::update(_step); if (isHopping){ currHopTime += _step->deltaTime; if (targets.size() > 0 && childTransform->getTranslationVector().x >= targets.at(0).x){ targets.erase(targets.begin()); if (targets.size() > 0){ setPath(glm::vec2(childTransform->getTranslationVector().x, childTransform->getTranslationVector().y), targets.at(0)); } } float ly = currHopTime / hopDuration <= 0.5 ? Easing::easeOutSine(currHopTime, 0, hopHeight, hopDuration) : Easing::easeOutBounce(currHopTime, hopHeight, -hopHeight, hopDuration); childTransform->translate(deltaX * _step->deltaTime * hopSpeed, deltaY * _step->deltaTime * hopSpeed, 0); llama->childTransform->translate(0, ly, 0, false); if (currHopTime >= hopDuration){ isHopping = false; } } } void Llama::addTarget(glm::vec2 _target){ targets.push_back(_target); if (targets.size() == 1){ setPath(glm::vec2(childTransform->getTranslationVector().x, childTransform->getTranslationVector().y), targets.at(0)); } } void Llama::setPath(glm::vec2 _startPos, glm::vec2 _targetPos){ pathP1 = _startPos; pathP2 = _targetPos; deltaX = pathP2.x - pathP1.x; deltaY = pathP2.y - pathP1.y; } void Llama::hop(){ if (!isHopping && targets.size() > 0){ isHopping = true; //hopStartPos = glm::vec2(childTransform->getTranslationVector().x, childTransform->getTranslationVector().y); //hopEndPos = getPointOnPath(hopLength); currHopTime = 0.f; } } glm::vec2 Llama::getPointOnPath(float _distance){ // get vector glm::vec2 v = glm::vec2(pathP2.x - pathP1.x, pathP2.y - pathP1.y); v = glm::normalize(v); glm::vec2 p = pathP1 + v * hopLength; return p; } <commit_msg>used logo tex from scenario instead of manually loading it<commit_after>#pragma once #include <Llama.h> #include <Sprite.h> #include <Texture.h> #include <MeshInterface.h> #include <Easing.h> #include <MY_ResourceManager.h> Llama::Llama(Shader * _shader) : llama(new Sprite(_shader)), isHopping(false), hopSpeed(1.f), hopDuration(1.f), hopLength(5.f), hopHeight(2.f), currHopTime(0.f) { llama->mesh->pushTexture2D(MY_ResourceManager::scenario->getTexture("LOGO")->texture); childTransform->addChild(llama); } Llama::~Llama(){ } void Llama::update(Step * _step){ Entity::update(_step); if (isHopping){ currHopTime += _step->deltaTime; if (targets.size() > 0 && childTransform->getTranslationVector().x >= targets.at(0).x){ targets.erase(targets.begin()); if (targets.size() > 0){ setPath(glm::vec2(childTransform->getTranslationVector().x, childTransform->getTranslationVector().y), targets.at(0)); } } float ly = currHopTime / hopDuration <= 0.5 ? Easing::easeOutSine(currHopTime, 0, hopHeight, hopDuration) : Easing::easeOutBounce(currHopTime, hopHeight, -hopHeight, hopDuration); childTransform->translate(deltaX * _step->deltaTime * hopSpeed, deltaY * _step->deltaTime * hopSpeed, 0); llama->childTransform->translate(0, ly, 0, false); if (currHopTime >= hopDuration){ isHopping = false; } } } void Llama::addTarget(glm::vec2 _target){ targets.push_back(_target); if (targets.size() == 1){ setPath(glm::vec2(childTransform->getTranslationVector().x, childTransform->getTranslationVector().y), targets.at(0)); } } void Llama::setPath(glm::vec2 _startPos, glm::vec2 _targetPos){ pathP1 = _startPos; pathP2 = _targetPos; deltaX = pathP2.x - pathP1.x; deltaY = pathP2.y - pathP1.y; } void Llama::hop(){ if (!isHopping && targets.size() > 0){ isHopping = true; //hopStartPos = glm::vec2(childTransform->getTranslationVector().x, childTransform->getTranslationVector().y); //hopEndPos = getPointOnPath(hopLength); currHopTime = 0.f; } } glm::vec2 Llama::getPointOnPath(float _distance){ // get vector glm::vec2 v = glm::vec2(pathP2.x - pathP1.x, pathP2.y - pathP1.y); v = glm::normalize(v); glm::vec2 p = pathP1 + v * hopLength; return p; } <|endoftext|>
<commit_before>/* * This file is part of PlantLight application. * * 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. * */ /* * Built for Attiny85 1Mhz, using AVR USBasp programmer. * VERSION 0.2 */ #include <Arduino.h> #include <TinyWireM.h> #include <BH1750FVI.h> #include <DS1307RTC.h> #define RELAY_SW 4 // Relay out pin #define CMD_MAN 1 // Manual light switch USI_TWI bus; // TinyWireM instance (I2C bus) BH1750FVI BH1750(bus); RTC_DS1307 RTC(bus); void setup() { Serial.begin(9600); // Init serial band rate pinMode(RELAY_SW, OUTPUT); pinMode(CMD_MAN, INPUT_PULLUP); // I2C begin() is called BEFORE sensors library "begin" methods: // it is called just once for all the sensors. bus.begin(); // Sensors initialization // Light sensor BH1750.powerOn(); // Real time clock RTC.sqw(0); if (!RTC.isrunning()) { Serial.println("RTC is NOT running!"); RTC.adjust(DateTime(__DATE__, __TIME__)); } } void log(DateTime dt, uint16_t lt) { Serial.print(dt.year(), DEC); Serial.print('/'); Serial.print(dt.month(), DEC); Serial.print('/'); Serial.print(dt.day(), DEC); Serial.print(' '); Serial.print(dt.hour(), DEC); Serial.print(':'); Serial.print(dt.minute(), DEC); Serial.print(':'); Serial.print(dt.second(), DEC); Serial.print(' '); Serial.println(lt); } boolean relayState = 0; uint16_t lux = 0; DateTime now; void loop() { lux = BH1750.getLightIntensity(); // Get lux value now = RTC.now(); log(now, lux); if (lux <= 10 || !digitalRead(CMD_MAN)) { relayState = true; } else relayState = false; digitalWrite(RELAY_SW, relayState); delay(10000); } <commit_msg>Changes for test with complete circuit and manual command<commit_after>/* * This file is part of PlantLight application. * * 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. * */ /* * Built for Attiny85 1Mhz, using AVR USBasp programmer. * VERSION 0.3 */ #include <Arduino.h> #include <TinyWireM.h> #include <BH1750FVI.h> #include <DS1307RTC.h> #define RELAY_SW_OUT 4 // Relay out pin #define CMD_MAN_IN 1 // Manual light switch USI_TWI bus; // TinyWireM instance (I2C bus) BH1750FVI BH1750(bus); RTC_DS1307 RTC(bus); long unsigned int startTime = 0; void setup() { Serial.begin(9600); // Init serial band rate pinMode(RELAY_SW_OUT, OUTPUT); pinMode(CMD_MAN_IN, INPUT_PULLUP); // I2C begin() is called BEFORE sensors library "begin" methods: // it is called just once for all the sensors. bus.begin(); // Sensors initialization // Light sensor BH1750.powerOn(); BH1750.setMode(BH1750_CONTINUOUS_HIGH_RES_MODE_2); BH1750.setMtreg(250); // Real time clock RTC.sqw(0); if (!RTC.isrunning()) { Serial.println("RTC is NOT running!"); RTC.adjust(DateTime(__DATE__, __TIME__)); } startTime = millis(); } void log(DateTime dt, float lt) { Serial.print(dt.year(), DEC); Serial.print('/'); Serial.print(dt.month(), DEC); Serial.print('/'); Serial.print(dt.day(), DEC); Serial.print(' '); Serial.print(dt.hour(), DEC); Serial.print(':'); Serial.print(dt.minute(), DEC); Serial.print(':'); Serial.print(dt.second(), DEC); Serial.print(' '); Serial.println(lt); } boolean relayState = 0; float lux = 0; DateTime now; uint8_t btnInCounter = 0; void loop() { if (!digitalRead(CMD_MAN_IN)) { if (btnInCounter < 10) { btnInCounter++; } } else { btnInCounter = 0; } if (millis() - startTime >= 500) { startTime = millis(); lux = BH1750.getLightIntensity(); // Get lux value now = RTC.now(); log(now, lux); if (btnInCounter >= 10) { relayState = true; } else if (lux <= 10) { relayState = true; } else { relayState = false; } digitalWrite(RELAY_SW_OUT, relayState); } } <|endoftext|>
<commit_before>//put global includes in 'BasicIncludes' // hi #include "BasicIncludes.h" #include "rand.h" #include "Camera.h" #include "Input.h" #include "Object.h" #include "Terrain.h" //Function List void Update(double); void Draw(); void CameraInput(); void MouseInput(); void InitializeWindow(); void Terminate(); void Run(); //Variables GLFWwindow* mainThread; glm::uvec2 SCREEN_SIZE; Camera camera = Camera(); glm::vec2 mouseChangeDegrees; double deltaTime; std::vector<Object*> objects; void Terminate() { glfwTerminate(); exit(0); } void InitializeWindow() { if (!glfwInit()) { Terminate(); } //set screen size const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); SCREEN_SIZE = glm::uvec2(720,720); //basic aa done for us ;D glfwWindowHint(GLFW_SAMPLES, 16); glfwWindowHint(GLFW_VISIBLE, GL_TRUE); //can change the screen setting later //if (window == FULLSCREEN) { // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // mainThread = glfwCreateWindow(SCREEN_SIZE.x, SCREEN_SIZE.y, "LifeSim", glfwGetPrimaryMonitor(), NULL); //} //else if (window == WINDOWED) { glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); mainThread = glfwCreateWindow(SCREEN_SIZE.x, SCREEN_SIZE.y, "LifeSim", NULL, NULL); //} //else if (BORDERLESS) { // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); // glfwWindowHint(GLFW_RED_BITS, mode->redBits); // glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); // glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); // glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); // mainThread = glfwCreateWindow(mode->width, mode->height, "LifeSim", glfwGetPrimaryMonitor(), NULL); //} if (!mainThread) { glfwTerminate(); throw std::runtime_error("GLFW window failed"); } glfwMakeContextCurrent(mainThread); // initialise GLEW if (glewInit() != GLEW_OK) { throw std::runtime_error("glewInit failed"); } glewExperimental = GL_TRUE; //stops glew crashing on OSX :-/ glfwSetInputMode(mainThread, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0, SCREEN_SIZE.y / 2.0); //Discard all the errors while (glGetError() != GL_NO_ERROR) {} glEnable(GL_DEPTH_TEST); // enable depth-testing glDepthMask(GL_TRUE); // turn on glDepthFunc(GL_LEQUAL); glDepthRange(0.0f, 1.0f); glEnable(GL_TEXTURE_2D); mouseChangeDegrees = glm::vec2(0); // setup camera camera.setViewportAspectRatio(SCREEN_SIZE.x / (float)SCREEN_SIZE.y); camera.setPosition(glm::vec3(0.0f, METER, (METER))); camera.offsetOrientation(45.0f, 45); //unsigned concurentThreadsSupported = std::thread::hardware_concurrency(); //threads = new ThreadPool(concurentThreadsSupported); //for keyboard controls glfwSetKeyCallback(mainThread, InputKeyboardCallback); SetInputWindow(mainThread); } void Run() { deltaTime = 1.0 / 60; InitializeWindow(); Terrain testObj = Terrain(); Object* terrain = &testObj; objects.push_back(terrain); //timer info for loop double t = 0.0f; double currentTime = glfwGetTime(); double accumulator = 0.0f; glfwPollEvents(); //stop loop when glfw exit is called glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0f, SCREEN_SIZE.y / 2.0f); while (!glfwWindowShouldClose(mainThread)) { double newTime = glfwGetTime(); double frameTime = newTime - currentTime; //std::cout << "FPS:: " <<1.0f / frameTime << std::endl; //setting up timers if (frameTime > 0.25) { frameTime = 0.25; } currentTime = newTime; accumulator += frameTime; //# of updates based on accumulated time while (accumulator >= deltaTime) { MouseInput();//update mouse change glfwPollEvents(); //executes all set input callbacks CameraInput(); //bypasses input system for direct camera manipulation Update(deltaTime); //updates all objects based on the constant deltaTime. t += deltaTime; accumulator -= deltaTime; } //draw glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Draw(); glfwSwapBuffers(mainThread); } } void MouseInput() { double xPos; double yPos; glfwGetCursorPos(mainThread, &xPos, &yPos); xPos -= (SCREEN_SIZE.x / 2.0); yPos -= (SCREEN_SIZE.y / 2.0); mouseChangeDegrees.x = (float)(xPos / SCREEN_SIZE.x *camera.fieldOfView().x); mouseChangeDegrees.y = (float)(yPos / SCREEN_SIZE.y *camera.fieldOfView().y); /*std::cout << "Change in x (mouse): " << mouseChangeDegrees.x << std::endl; std::cout << "Change in y (mouse): " << mouseChangeDegrees.y << std::endl;*/ camera.offsetOrientation(mouseChangeDegrees.x, mouseChangeDegrees.y); glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0f, SCREEN_SIZE.y / 2.0f); } void CameraInput() { double moveSpeed; if (glfwGetKey(mainThread, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) { moveSpeed = 9 * METER * deltaTime; } else if (glfwGetKey(mainThread, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) { moveSpeed = 1 * METER * deltaTime; } else { moveSpeed = 4.5 * METER * deltaTime; } if (glfwGetKey(mainThread, GLFW_KEY_S) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -camera.forward()); } else if (glfwGetKey(mainThread, GLFW_KEY_W) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * camera.forward()); } if (glfwGetKey(mainThread, GLFW_KEY_A) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -camera.right()); } else if (glfwGetKey(mainThread, GLFW_KEY_D) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * camera.right()); } if (glfwGetKey(mainThread, GLFW_KEY_Z) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -glm::vec3(0, 1, 0)); } else if (glfwGetKey(mainThread, GLFW_KEY_X) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * glm::vec3(0, 1, 0)); } } void Update(double dt) { } void Draw() { for (int i = 0; i < objects.size();i++){ objects[i]->Draw(camera); } } int main(){ Run(); Terminate(); return 0; } <commit_msg>eSCAPE NOW CLOSES DOWN<commit_after>//put global includes in 'BasicIncludes' // hi #include "BasicIncludes.h" #include "rand.h" #include "Camera.h" #include "Input.h" #include "Object.h" #include "Terrain.h" //Function List void Update(double); void Draw(); void CameraInput(); void MouseInput(); void InitializeWindow(); void Terminate(); void Run(); //Variables GLFWwindow* mainThread; glm::uvec2 SCREEN_SIZE; Camera camera = Camera(); glm::vec2 mouseChangeDegrees; double deltaTime; std::vector<Object*> objects; void Terminate() { glfwTerminate(); exit(0); } void InitializeWindow() { if (!glfwInit()) { Terminate(); } //set screen size const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); SCREEN_SIZE = glm::uvec2(720,720); //basic aa done for us ;D glfwWindowHint(GLFW_SAMPLES, 16); glfwWindowHint(GLFW_VISIBLE, GL_TRUE); //can change the screen setting later //if (window == FULLSCREEN) { // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // mainThread = glfwCreateWindow(SCREEN_SIZE.x, SCREEN_SIZE.y, "LifeSim", glfwGetPrimaryMonitor(), NULL); //} //else if (window == WINDOWED) { glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); mainThread = glfwCreateWindow(SCREEN_SIZE.x, SCREEN_SIZE.y, "LifeSim", NULL, NULL); //} //else if (BORDERLESS) { // glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); // glfwWindowHint(GLFW_RED_BITS, mode->redBits); // glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits); // glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits); // glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate); // mainThread = glfwCreateWindow(mode->width, mode->height, "LifeSim", glfwGetPrimaryMonitor(), NULL); //} if (!mainThread) { glfwTerminate(); throw std::runtime_error("GLFW window failed"); } glfwMakeContextCurrent(mainThread); // initialise GLEW if (glewInit() != GLEW_OK) { throw std::runtime_error("glewInit failed"); } glewExperimental = GL_TRUE; //stops glew crashing on OSX :-/ glfwSetInputMode(mainThread, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0, SCREEN_SIZE.y / 2.0); //Discard all the errors while (glGetError() != GL_NO_ERROR) {} glEnable(GL_DEPTH_TEST); // enable depth-testing glDepthMask(GL_TRUE); // turn on glDepthFunc(GL_LEQUAL); glDepthRange(0.0f, 1.0f); glEnable(GL_TEXTURE_2D); mouseChangeDegrees = glm::vec2(0); // setup camera camera.setViewportAspectRatio(SCREEN_SIZE.x / (float)SCREEN_SIZE.y); camera.setPosition(glm::vec3(0.0f, METER, (METER))); camera.offsetOrientation(45.0f, 45); //unsigned concurentThreadsSupported = std::thread::hardware_concurrency(); //threads = new ThreadPool(concurentThreadsSupported); //for keyboard controls glfwSetKeyCallback(mainThread, InputKeyboardCallback); SetInputWindow(mainThread); } void Run() { SetKey(GLFW_KEY_ESCAPE, std::bind(&Terminate)); deltaTime = 1.0 / 60; InitializeWindow(); Terrain testObj = Terrain(); Object* terrain = &testObj; objects.push_back(terrain); //timer info for loop double t = 0.0f; double currentTime = glfwGetTime(); double accumulator = 0.0f; glfwPollEvents(); //stop loop when glfw exit is called glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0f, SCREEN_SIZE.y / 2.0f); while (!glfwWindowShouldClose(mainThread)) { double newTime = glfwGetTime(); double frameTime = newTime - currentTime; //std::cout << "FPS:: " <<1.0f / frameTime << std::endl; //setting up timers if (frameTime > 0.25) { frameTime = 0.25; } currentTime = newTime; accumulator += frameTime; //# of updates based on accumulated time while (accumulator >= deltaTime) { MouseInput();//update mouse change glfwPollEvents(); //executes all set input callbacks CameraInput(); //bypasses input system for direct camera manipulation Update(deltaTime); //updates all objects based on the constant deltaTime. t += deltaTime; accumulator -= deltaTime; } //draw glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Draw(); glfwSwapBuffers(mainThread); } } void MouseInput() { double xPos; double yPos; glfwGetCursorPos(mainThread, &xPos, &yPos); xPos -= (SCREEN_SIZE.x / 2.0); yPos -= (SCREEN_SIZE.y / 2.0); mouseChangeDegrees.x = (float)(xPos / SCREEN_SIZE.x *camera.fieldOfView().x); mouseChangeDegrees.y = (float)(yPos / SCREEN_SIZE.y *camera.fieldOfView().y); /*std::cout << "Change in x (mouse): " << mouseChangeDegrees.x << std::endl; std::cout << "Change in y (mouse): " << mouseChangeDegrees.y << std::endl;*/ camera.offsetOrientation(mouseChangeDegrees.x, mouseChangeDegrees.y); glfwSetCursorPos(mainThread, SCREEN_SIZE.x / 2.0f, SCREEN_SIZE.y / 2.0f); } void CameraInput() { double moveSpeed; if (glfwGetKey(mainThread, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) { moveSpeed = 9 * METER * deltaTime; } else if (glfwGetKey(mainThread, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) { moveSpeed = 1 * METER * deltaTime; } else { moveSpeed = 4.5 * METER * deltaTime; } if (glfwGetKey(mainThread, GLFW_KEY_S) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -camera.forward()); } else if (glfwGetKey(mainThread, GLFW_KEY_W) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * camera.forward()); } if (glfwGetKey(mainThread, GLFW_KEY_A) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -camera.right()); } else if (glfwGetKey(mainThread, GLFW_KEY_D) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * camera.right()); } if (glfwGetKey(mainThread, GLFW_KEY_Z) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * -glm::vec3(0, 1, 0)); } else if (glfwGetKey(mainThread, GLFW_KEY_X) == GLFW_PRESS) { camera.offsetPosition(float(moveSpeed) * glm::vec3(0, 1, 0)); } } void Update(double dt) { } void Draw() { for (int i = 0; i < objects.size();i++){ objects[i]->Draw(camera); } } int main(){ Run(); Terminate(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/atom_bindings.h" #include <algorithm> #include <iostream> #include <string> #include "atom/common/atom_version.h" #include "atom/common/chrome_version.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "base/logging.h" #include "base/sys_info.h" #include "native_mate/dictionary.h" namespace atom { namespace { // Dummy class type that used for crashing the program. struct DummyClass { bool crash; }; // Called when there is a fatal error in V8, we just crash the process here so // we can get the stack trace. void FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; AtomBindings::Crash(); } } // namespace AtomBindings::AtomBindings(uv_loop_t* loop) { uv_async_init(loop, &call_next_tick_async_, OnCallNextTick); call_next_tick_async_.data = this; metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics(); } AtomBindings::~AtomBindings() { uv_close(reinterpret_cast<uv_handle_t*>(&call_next_tick_async_), nullptr); } void AtomBindings::BindTo(v8::Isolate* isolate, v8::Local<v8::Object> process) { v8::V8::SetFatalErrorHandler(FatalErrorCallback); mate::Dictionary dict(isolate, process); dict.SetMethod("crash", &AtomBindings::Crash); dict.SetMethod("hang", &Hang); dict.SetMethod("log", &Log); dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo); dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo); dict.SetMethod("getCPUUsage", base::Bind(&AtomBindings::GetCPUUsage, base::Unretained(this))); dict.SetMethod("getIOCounters", &GetIOCounters); #if defined(OS_POSIX) dict.SetMethod("setFdLimit", &base::SetFdLimit); #endif dict.SetMethod("activateUvLoop", base::Bind(&AtomBindings::ActivateUVLoop, base::Unretained(this))); #if defined(MAS_BUILD) dict.Set("mas", true); #endif mate::Dictionary versions; if (dict.Get("versions", &versions)) { // TODO(kevinsawicki): Make read-only in 2.0 to match node versions.Set(ATOM_PROJECT_NAME, ATOM_VERSION_STRING); versions.Set("chrome", CHROME_VERSION_STRING); } } void AtomBindings::EnvironmentDestroyed(node::Environment* env) { auto it = std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env); if (it != pending_next_ticks_.end()) pending_next_ticks_.erase(it); } void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) { node::Environment* env = node::Environment::GetCurrent(isolate); if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) != pending_next_ticks_.end()) return; pending_next_ticks_.push_back(env); uv_async_send(&call_next_tick_async_); } // static void AtomBindings::OnCallNextTick(uv_async_t* handle) { AtomBindings* self = static_cast<AtomBindings*>(handle->data); for (std::list<node::Environment*>::const_iterator it = self->pending_next_ticks_.begin(); it != self->pending_next_ticks_.end(); ++it) { node::InternalCallbackScope scope( *it, v8::Local<v8::Object>(), {0, 0}, node::InternalCallbackScope::kAllowEmptyResource); } self->pending_next_ticks_.clear(); } // static void AtomBindings::Log(const base::string16& message) { std::cout << message << std::flush; } // static void AtomBindings::Crash() { static_cast<DummyClass*>(nullptr)->crash = true; } // static void AtomBindings::Hang() { for (;;) base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1)); } // static v8::Local<v8::Value> AtomBindings::GetProcessMemoryInfo(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("workingSetSize", static_cast<double>(metrics->GetWorkingSetSize() >> 10)); dict.Set("peakWorkingSetSize", static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10)); size_t private_bytes, shared_bytes; if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) { dict.Set("privateBytes", static_cast<double>(private_bytes >> 10)); dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10)); } return dict.GetHandle(); } // static v8::Local<v8::Value> AtomBindings::GetSystemMemoryInfo(v8::Isolate* isolate, mate::Arguments* args) { base::SystemMemoryInfoKB mem_info; if (!base::GetSystemMemoryInfo(&mem_info)) { args->ThrowError("Unable to retrieve system memory information"); return v8::Undefined(isolate); } mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("total", mem_info.total); // See Chromium's "base/process/process_metrics.h" for an explanation. int free = #if defined(OS_WIN) mem_info.avail_phys; #else mem_info.free; #endif dict.Set("free", free); // NB: These return bogus values on macOS #if !defined(OS_MACOSX) dict.Set("swapTotal", mem_info.swap_total); dict.Set("swapFree", mem_info.swap_free); #endif return dict.GetHandle(); } v8::Local<v8::Value> AtomBindings::GetCPUUsage(v8::Isolate* isolate) { mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); int processor_count = base::SysInfo::NumberOfProcessors(); dict.Set("percentCPUUsage", metrics_->GetPlatformIndependentCPUUsage() / processor_count); // NB: This will throw NOTIMPLEMENTED() on Windows // For backwards compatibility, we'll return 0 #if !defined(OS_WIN) dict.Set("idleWakeupsPerSecond", metrics_->GetIdleWakeupsPerSecond()); #else dict.Set("idleWakeupsPerSecond", 0); #endif return dict.GetHandle(); } // static v8::Local<v8::Value> AtomBindings::GetIOCounters(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); base::IoCounters io_counters; mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); if (metrics->GetIOCounters(&io_counters)) { dict.Set("readOperationCount", io_counters.ReadOperationCount); dict.Set("writeOperationCount", io_counters.WriteOperationCount); dict.Set("otherOperationCount", io_counters.OtherOperationCount); dict.Set("readTransferCount", io_counters.ReadTransferCount); dict.Set("writeTransferCount", io_counters.WriteTransferCount); dict.Set("otherTransferCount", io_counters.OtherTransferCount); } return dict.GetHandle(); } } // namespace atom <commit_msg>Enter context scope before InternalCallbackScope<commit_after>// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/common/api/atom_bindings.h" #include <algorithm> #include <iostream> #include <string> #include "atom/common/api/locker.h" #include "atom/common/atom_version.h" #include "atom/common/chrome_version.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/node_includes.h" #include "base/logging.h" #include "base/sys_info.h" #include "native_mate/dictionary.h" namespace atom { namespace { // Dummy class type that used for crashing the program. struct DummyClass { bool crash; }; // Called when there is a fatal error in V8, we just crash the process here so // we can get the stack trace. void FatalErrorCallback(const char* location, const char* message) { LOG(ERROR) << "Fatal error in V8: " << location << " " << message; AtomBindings::Crash(); } } // namespace AtomBindings::AtomBindings(uv_loop_t* loop) { uv_async_init(loop, &call_next_tick_async_, OnCallNextTick); call_next_tick_async_.data = this; metrics_ = base::ProcessMetrics::CreateCurrentProcessMetrics(); } AtomBindings::~AtomBindings() { uv_close(reinterpret_cast<uv_handle_t*>(&call_next_tick_async_), nullptr); } void AtomBindings::BindTo(v8::Isolate* isolate, v8::Local<v8::Object> process) { v8::V8::SetFatalErrorHandler(FatalErrorCallback); mate::Dictionary dict(isolate, process); dict.SetMethod("crash", &AtomBindings::Crash); dict.SetMethod("hang", &Hang); dict.SetMethod("log", &Log); dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo); dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo); dict.SetMethod("getCPUUsage", base::Bind(&AtomBindings::GetCPUUsage, base::Unretained(this))); dict.SetMethod("getIOCounters", &GetIOCounters); #if defined(OS_POSIX) dict.SetMethod("setFdLimit", &base::SetFdLimit); #endif dict.SetMethod("activateUvLoop", base::Bind(&AtomBindings::ActivateUVLoop, base::Unretained(this))); #if defined(MAS_BUILD) dict.Set("mas", true); #endif mate::Dictionary versions; if (dict.Get("versions", &versions)) { // TODO(kevinsawicki): Make read-only in 2.0 to match node versions.Set(ATOM_PROJECT_NAME, ATOM_VERSION_STRING); versions.Set("chrome", CHROME_VERSION_STRING); } } void AtomBindings::EnvironmentDestroyed(node::Environment* env) { auto it = std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env); if (it != pending_next_ticks_.end()) pending_next_ticks_.erase(it); } void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) { node::Environment* env = node::Environment::GetCurrent(isolate); if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) != pending_next_ticks_.end()) return; pending_next_ticks_.push_back(env); uv_async_send(&call_next_tick_async_); } // static void AtomBindings::OnCallNextTick(uv_async_t* handle) { AtomBindings* self = static_cast<AtomBindings*>(handle->data); for (std::list<node::Environment*>::const_iterator it = self->pending_next_ticks_.begin(); it != self->pending_next_ticks_.end(); ++it) { node::Environment* env = *it; mate::Locker locker(env->isolate()); v8::Context::Scope context_scope(env->context()); node::InternalCallbackScope scope( env, v8::Local<v8::Object>(), {0, 0}, node::InternalCallbackScope::kAllowEmptyResource); } self->pending_next_ticks_.clear(); } // static void AtomBindings::Log(const base::string16& message) { std::cout << message << std::flush; } // static void AtomBindings::Crash() { static_cast<DummyClass*>(nullptr)->crash = true; } // static void AtomBindings::Hang() { for (;;) base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1)); } // static v8::Local<v8::Value> AtomBindings::GetProcessMemoryInfo(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("workingSetSize", static_cast<double>(metrics->GetWorkingSetSize() >> 10)); dict.Set("peakWorkingSetSize", static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10)); size_t private_bytes, shared_bytes; if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) { dict.Set("privateBytes", static_cast<double>(private_bytes >> 10)); dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10)); } return dict.GetHandle(); } // static v8::Local<v8::Value> AtomBindings::GetSystemMemoryInfo(v8::Isolate* isolate, mate::Arguments* args) { base::SystemMemoryInfoKB mem_info; if (!base::GetSystemMemoryInfo(&mem_info)) { args->ThrowError("Unable to retrieve system memory information"); return v8::Undefined(isolate); } mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); dict.Set("total", mem_info.total); // See Chromium's "base/process/process_metrics.h" for an explanation. int free = #if defined(OS_WIN) mem_info.avail_phys; #else mem_info.free; #endif dict.Set("free", free); // NB: These return bogus values on macOS #if !defined(OS_MACOSX) dict.Set("swapTotal", mem_info.swap_total); dict.Set("swapFree", mem_info.swap_free); #endif return dict.GetHandle(); } v8::Local<v8::Value> AtomBindings::GetCPUUsage(v8::Isolate* isolate) { mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); int processor_count = base::SysInfo::NumberOfProcessors(); dict.Set("percentCPUUsage", metrics_->GetPlatformIndependentCPUUsage() / processor_count); // NB: This will throw NOTIMPLEMENTED() on Windows // For backwards compatibility, we'll return 0 #if !defined(OS_WIN) dict.Set("idleWakeupsPerSecond", metrics_->GetIdleWakeupsPerSecond()); #else dict.Set("idleWakeupsPerSecond", 0); #endif return dict.GetHandle(); } // static v8::Local<v8::Value> AtomBindings::GetIOCounters(v8::Isolate* isolate) { std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateCurrentProcessMetrics()); base::IoCounters io_counters; mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate); if (metrics->GetIOCounters(&io_counters)) { dict.Set("readOperationCount", io_counters.ReadOperationCount); dict.Set("writeOperationCount", io_counters.WriteOperationCount); dict.Set("otherOperationCount", io_counters.OtherOperationCount); dict.Set("readTransferCount", io_counters.ReadTransferCount); dict.Set("writeTransferCount", io_counters.WriteTransferCount); dict.Set("otherTransferCount", io_counters.OtherTransferCount); } return dict.GetHandle(); } } // namespace atom <|endoftext|>
<commit_before>#include <values.h> #include "LinearAlgebra.hh" #include "util.hh" namespace LinearAlgebra { double spd_log_determinant(const Matrix &A) { assert(A.rows()==A.cols()); //assert(is_spd(A)); LaGenMatDouble chol; cholesky_factor(A, chol); double log_det=0; for (int i=0; i<chol.rows(); i++) log_det += log(chol(i,i)); log_det *= 2; return log_det; } double spd_determinant(const Matrix &A) { assert(A.rows()==A.cols()); //assert(is_spd(A)); LaGenMatDouble chol; cholesky_factor(A, chol); double det=1; for (int i=0; i<chol.rows(); i++) det *= chol(i,i); det *=det; return det; } double determinant(const Matrix &A) { assert(A.rows()==A.cols()); LaGenMatDouble B(A); LaVectorDouble eigvals(A.cols()); LaEigSolveSymmetricVecIP(B, eigvals); double det=1; for (int i=0; i<eigvals.size(); i++) det *= eigvals(i); return det; } double log_determinant(const Matrix &A) { assert(A.rows()==A.cols()); LaGenMatDouble B(A); LaVectorDouble eigvals(A.cols()); LaEigSolveSymmetricVecIP(B, eigvals); double log_det=0; for (int i=0; i<eigvals.size(); i++) log_det += util::safe_log(eigvals(i)); return log_det; } double full_matrix_determinant(const Matrix &A ) { Matrix An(A.copy()); assert(A.rows()==A.cols()); LaVectorLongInt pivots(A.cols()); LUFactorizeIP(An, pivots); double detA = 1; for (int i = 0; i < A.cols(); ++i) detA *= A(i, i); return detA; } double full_matrix_log_determinant(const Matrix &A ) { Matrix An(A.copy()); assert(A.rows()==A.cols()); LaVectorLongInt pivots(A.cols()); LUFactorizeIP(An, pivots); double detA = 0; for (int i = 0; i < A.cols(); ++i) detA += util::safe_log(A(i, i)*A(i,i)); return detA * 0.5; } void matrix_power(const Matrix &A, Matrix &B, double power) { LaVectorDouble D = LaVectorDouble(A.rows(),1); LaGenMatDouble V = LaGenMatDouble(A); LaEigSolveSymmetricVecIP(V, D); LaGenMatDouble V_inverse = LaGenMatDouble(V); LaVectorLongInt pivots(A.rows()); LUFactorizeIP(V_inverse, pivots); LaLUInverseIP(V_inverse, pivots); B.resize(A.rows(), A.cols()); LaGenMatDouble t=LaGenMatDouble::zeros(A.rows()); LaGenMatDouble t2=LaGenMatDouble::zeros(A.rows()); for (int i=0; i<t.rows(); i++) t(i,i)=pow(D(i),power); Blas_Mat_Mat_Mult(V, t, t2, 1.0, 0.0); Blas_Mat_Mat_Mult(t2, V_inverse, B, 1.0, 0.0); } void cholesky_factor(const Matrix &A, Matrix &B) { assert(A.rows() == A.cols()); //assert(is_spd(A)); B.resize(A.rows(), A.cols()); B.copy(A); for (int j=0; j<B.rows(); j++) { for (int k=0; k<j; k++) for (int i=j; i<B.rows(); i++) B(i,j) = B(i,j)-B(i,k)*B(j,k); B(j,j) = sqrt(B(j,j)); for (int k=j+1; k<B.rows(); k++) B(k,j) = B(k,j)/B(j,j); } for (int i=0; i<B.rows(); i++) for (int j=i+1; j<B.cols(); j++) B(i,j) = 0; } void generalized_eigenvalues(const Matrix &A, const Matrix &B, Vector &eigvals, Matrix &eigvecs) { assert(A.rows()==A.cols()); assert(B.rows()==B.cols()); assert(A.rows()==B.rows()); assert(is_spd(B)); LaGenMatDouble B_negsqrt; LaGenMatDouble t(A); eigvals.resize(A.rows(),1); eigvecs.resize(A.rows(),A.cols()); matrix_power(B, B_negsqrt, -0.5); Blas_Mat_Mat_Mult(B_negsqrt, A, t, 1.0, 0.0); Blas_Mat_Mat_Mult(t, B_negsqrt, eigvecs, 1.0, 0.0); LaEigSolveSymmetricVecIP(eigvecs, eigvals); } void generalized_eigenvalues(const Matrix &A, const Matrix &B, LaVectorComplex &eigvals, LaGenMatComplex &eigvecs) { assert(A.rows()==A.cols()); assert(B.rows()==B.cols()); assert(A.rows()==B.rows()); assert(is_spd(B)); LaGenMatDouble B_negsqrt; LaGenMatDouble t(A); LaGenMatDouble t2(A); eigvals.resize(A.rows(),1); eigvecs.resize(A.rows(),A.cols()); matrix_power(B, B_negsqrt, -0.5); Blas_Mat_Mat_Mult(B_negsqrt, A, t, 1.0, 0.0); Blas_Mat_Mat_Mult(t, B_negsqrt, t2, 1.0, 0.0); LaGenMatComplex c(t2); LaEigSolve(c, eigvals, eigvecs); } void map_m2v(const Matrix &m, Vector &v) { assert(m.rows()==m.cols()); int dim=m.rows(), pos=0; v.resize((int)(dim*(dim+1)/2),1); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Multiply off-diagonal elements by sqrt(2) // to preserve inner products if (i==j) v(pos)=m(i,j); else v(pos)=sqrt(2)*m(i,j); ++pos; } } void map_v2m(const Vector &v, Matrix &m) { // Deduce the matrix dimensions; numel(v)=dim*(dim+1)/2 int dim=(int)(0.5*sqrt(1+8*v.size())-0.5); int pos=0; float a=1/sqrt(2); assert(int(dim*(dim+1)/2)==v.size()); m.resize(dim,dim); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Divide off-diagonal elements by sqrt(2) if (i==j) m(j,j) = v(pos); else { m(i,j) = a*v(pos); m(j,i) = a*v(pos); } ++pos; } } /* void map_mtlm2v(const Matrix &m, LaVectorDouble &v) { assert(m.nrows()==m.ncols()); int dim=m.nrows(), pos=0; v.resize((int)(dim*(dim+1)/2),1); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Multiply off-diagonal elements by sqrt(2) // to preserve inner products if (i==j) v(pos)=m(i,j); else v(pos)=sqrt(2)*m(i,j); ++pos; } } void map_v2mtlm(const Vector &v, Matrix &m) { // Deduce the matrix dimensions; numel(v)=dim*(dim+1)/2 int dim=(int)(0.5*sqrt(1+8*v.size())-0.5); int pos=0; float a=1/sqrt(2); assert(int(dim*(dim+1)/2)==v.size()); m.resize(dim,dim); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Divide off-diagonal elements by sqrt(2) if (i==j) m(j,j) = v(pos); else { m(i,j) = a*v(pos); m(j,i) = a*v(pos); } ++pos; } } */ #ifdef USE_SUBSPACE_COV void map_hclv2lapackm(const HCL_RnVector_d &v, Matrix &m) { // Deduce the matrix dimensions; numel(v)=dim*(dim+1)/2 int dim=(int)(0.5*sqrt(1+8*v.Dim())-0.5); int pos=0; float a=1/sqrt(2); assert(int(dim*(dim+1)/2)==v.Dim()); m.resize(dim,dim); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Divide off-diagonal elements by sqrt(2) if (i==j) m(j,j) = v(pos); else { m(i,j) = a*v(pos); m(j,i) = a*v(pos); } ++pos; } } void map_lapackm2hclv(const Matrix &m, HCL_RnVector_d &v) { assert(m.rows()==m.cols()); assert(m.rows()==v.Dim()); int dim=m.rows(), pos=0; for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Multiply off-diagonal elements by sqrt(2) // to preserve inner products if (i==j) v(pos)=m(i,j); else v(pos)=sqrt(2)*m(i,j); ++pos; } } #endif /* double cond(const Matrix &m) { assert(m.nrows()==m.ncols()); LaGenMatDouble temp(m.nrows(), m.ncols()); for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) temp(i,j)=m(i,j); return cond(temp); } */ double cond(const Matrix &m) { assert(m.rows()==m.cols()); double min=DBL_MAX; double max=-DBL_MAX; LaGenMatDouble a(m); LaVectorDouble eigs(m.rows()); LaEigSolveSymmetricVecIP(a, eigs); for (int i=0; i<eigs.size(); i++) { if (eigs(i)<min) min=eigs(i); if (eigs(i)>max) max=eigs(i); } return max/min; } /* bool is_spd(const Matrix &m) { assert(m.nrows()==m.ncols()); LaGenMatDouble temp(m.nrows(), m.ncols()); for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) temp(i,j)=m(i,j); return is_spd(temp); } */ bool is_spd(const Matrix &m) { assert(m.rows()==m.cols()); LaGenMatDouble t=LaGenMatDouble(m); LaVectorDouble eigs=LaVectorDouble(m.rows()); LaEigSolveSymmetricVecIP(t,eigs); for (int i=0; i<eigs.size(); i++) { // std::cout << eigs(i) << std::endl; if (eigs(i)<=0) return false; } return true; } /* bool is_singular(const Matrix &m) { assert(m.nrows()==m.ncols()); LaGenMatDouble temp(m.nrows(), m.ncols()); for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) temp(i,j)=m(i,j); return is_singular(temp); } */ bool is_singular(const Matrix &m) { assert(m.rows()==m.cols()); LaGenMatDouble a(m); LaVectorDouble eigs(m.rows()); LaEigSolveSymmetricVecIP(a, eigs); for (int i=0; i<eigs.size(); i++) if (abs(eigs(i))<0.00000001) return true; return false; } /* void force_min_eig(Matrix &m, double min_eig) { assert(m.nrows()==m.ncols()); // Map to Lapack++ matrix LaGenMatDouble temp(m.nrows(), m.ncols()); for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) temp(i,j)=m(i,j); // Force minimum eigenvalues force_min_eig(temp, min_eig); // Map back to MTL matrix for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) m(i,j)=temp(i,j); } */ void force_min_eig(Matrix &m, double min_eig) { assert(m.rows()==m.cols()); LaGenMatDouble eigv(m); LaVectorDouble eigs_vector(m.rows()); LaGenMatDouble eigs = LaGenMatDouble::zeros(m.rows()); LaGenMatDouble temp(m.rows(), m.cols()); LaEigSolveSymmetricVecIP(eigv, eigs_vector); for (int i=0; i<m.rows(); i++) eigs(i,i)=std::max(min_eig, eigs_vector(i)); // Calculate EIGV*EIGS*EIGV' Blas_Mat_Mat_Mult(eigv, eigs, temp, 1.0, 0.0); Blas_Mat_Mat_Trans_Mult(temp, eigv, m, 1.0, 0.0); } void inverse(const Matrix &m, Matrix &inv) { inv.copy(m); LaVectorLongInt pivots(m.rows()); LUFactorizeIP(inv, pivots); LaLUInverseIP(inv, pivots); } } <commit_msg>Changed abs -> fabs<commit_after>#include <values.h> #include "LinearAlgebra.hh" #include "util.hh" namespace LinearAlgebra { double spd_log_determinant(const Matrix &A) { assert(A.rows()==A.cols()); //assert(is_spd(A)); LaGenMatDouble chol; cholesky_factor(A, chol); double log_det=0; for (int i=0; i<chol.rows(); i++) log_det += log(chol(i,i)); log_det *= 2; return log_det; } double spd_determinant(const Matrix &A) { assert(A.rows()==A.cols()); //assert(is_spd(A)); LaGenMatDouble chol; cholesky_factor(A, chol); double det=1; for (int i=0; i<chol.rows(); i++) det *= chol(i,i); det *=det; return det; } double determinant(const Matrix &A) { assert(A.rows()==A.cols()); LaGenMatDouble B(A); LaVectorDouble eigvals(A.cols()); LaEigSolveSymmetricVecIP(B, eigvals); double det=1; for (int i=0; i<eigvals.size(); i++) det *= eigvals(i); return det; } double log_determinant(const Matrix &A) { assert(A.rows()==A.cols()); LaGenMatDouble B(A); LaVectorDouble eigvals(A.cols()); LaEigSolveSymmetricVecIP(B, eigvals); double log_det=0; for (int i=0; i<eigvals.size(); i++) log_det += util::safe_log(eigvals(i)); return log_det; } double full_matrix_determinant(const Matrix &A ) { Matrix An(A.copy()); assert(A.rows()==A.cols()); LaVectorLongInt pivots(A.cols()); LUFactorizeIP(An, pivots); double detA = 1; for (int i = 0; i < A.cols(); ++i) detA *= A(i, i); return detA; } double full_matrix_log_determinant(const Matrix &A ) { Matrix An(A.copy()); assert(A.rows()==A.cols()); LaVectorLongInt pivots(A.cols()); LUFactorizeIP(An, pivots); double detA = 0; for (int i = 0; i < A.cols(); ++i) detA += util::safe_log(A(i, i)*A(i,i)); return detA * 0.5; } void matrix_power(const Matrix &A, Matrix &B, double power) { LaVectorDouble D = LaVectorDouble(A.rows(),1); LaGenMatDouble V = LaGenMatDouble(A); LaEigSolveSymmetricVecIP(V, D); LaGenMatDouble V_inverse = LaGenMatDouble(V); LaVectorLongInt pivots(A.rows()); LUFactorizeIP(V_inverse, pivots); LaLUInverseIP(V_inverse, pivots); B.resize(A.rows(), A.cols()); LaGenMatDouble t=LaGenMatDouble::zeros(A.rows()); LaGenMatDouble t2=LaGenMatDouble::zeros(A.rows()); for (int i=0; i<t.rows(); i++) t(i,i)=pow(D(i),power); Blas_Mat_Mat_Mult(V, t, t2, 1.0, 0.0); Blas_Mat_Mat_Mult(t2, V_inverse, B, 1.0, 0.0); } void cholesky_factor(const Matrix &A, Matrix &B) { assert(A.rows() == A.cols()); //assert(is_spd(A)); B.resize(A.rows(), A.cols()); B.copy(A); for (int j=0; j<B.rows(); j++) { for (int k=0; k<j; k++) for (int i=j; i<B.rows(); i++) B(i,j) = B(i,j)-B(i,k)*B(j,k); B(j,j) = sqrt(B(j,j)); for (int k=j+1; k<B.rows(); k++) B(k,j) = B(k,j)/B(j,j); } for (int i=0; i<B.rows(); i++) for (int j=i+1; j<B.cols(); j++) B(i,j) = 0; } void generalized_eigenvalues(const Matrix &A, const Matrix &B, Vector &eigvals, Matrix &eigvecs) { assert(A.rows()==A.cols()); assert(B.rows()==B.cols()); assert(A.rows()==B.rows()); assert(is_spd(B)); LaGenMatDouble B_negsqrt; LaGenMatDouble t(A); eigvals.resize(A.rows(),1); eigvecs.resize(A.rows(),A.cols()); matrix_power(B, B_negsqrt, -0.5); Blas_Mat_Mat_Mult(B_negsqrt, A, t, 1.0, 0.0); Blas_Mat_Mat_Mult(t, B_negsqrt, eigvecs, 1.0, 0.0); LaEigSolveSymmetricVecIP(eigvecs, eigvals); } void generalized_eigenvalues(const Matrix &A, const Matrix &B, LaVectorComplex &eigvals, LaGenMatComplex &eigvecs) { assert(A.rows()==A.cols()); assert(B.rows()==B.cols()); assert(A.rows()==B.rows()); assert(is_spd(B)); LaGenMatDouble B_negsqrt; LaGenMatDouble t(A); LaGenMatDouble t2(A); eigvals.resize(A.rows(),1); eigvecs.resize(A.rows(),A.cols()); matrix_power(B, B_negsqrt, -0.5); Blas_Mat_Mat_Mult(B_negsqrt, A, t, 1.0, 0.0); Blas_Mat_Mat_Mult(t, B_negsqrt, t2, 1.0, 0.0); LaGenMatComplex c(t2); LaEigSolve(c, eigvals, eigvecs); } void map_m2v(const Matrix &m, Vector &v) { assert(m.rows()==m.cols()); int dim=m.rows(), pos=0; v.resize((int)(dim*(dim+1)/2),1); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Multiply off-diagonal elements by sqrt(2) // to preserve inner products if (i==j) v(pos)=m(i,j); else v(pos)=sqrt(2)*m(i,j); ++pos; } } void map_v2m(const Vector &v, Matrix &m) { // Deduce the matrix dimensions; numel(v)=dim*(dim+1)/2 int dim=(int)(0.5*sqrt(1+8*v.size())-0.5); int pos=0; float a=1/sqrt(2); assert(int(dim*(dim+1)/2)==v.size()); m.resize(dim,dim); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Divide off-diagonal elements by sqrt(2) if (i==j) m(j,j) = v(pos); else { m(i,j) = a*v(pos); m(j,i) = a*v(pos); } ++pos; } } /* void map_mtlm2v(const Matrix &m, LaVectorDouble &v) { assert(m.nrows()==m.ncols()); int dim=m.nrows(), pos=0; v.resize((int)(dim*(dim+1)/2),1); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Multiply off-diagonal elements by sqrt(2) // to preserve inner products if (i==j) v(pos)=m(i,j); else v(pos)=sqrt(2)*m(i,j); ++pos; } } void map_v2mtlm(const Vector &v, Matrix &m) { // Deduce the matrix dimensions; numel(v)=dim*(dim+1)/2 int dim=(int)(0.5*sqrt(1+8*v.size())-0.5); int pos=0; float a=1/sqrt(2); assert(int(dim*(dim+1)/2)==v.size()); m.resize(dim,dim); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Divide off-diagonal elements by sqrt(2) if (i==j) m(j,j) = v(pos); else { m(i,j) = a*v(pos); m(j,i) = a*v(pos); } ++pos; } } */ #ifdef USE_SUBSPACE_COV void map_hclv2lapackm(const HCL_RnVector_d &v, Matrix &m) { // Deduce the matrix dimensions; numel(v)=dim*(dim+1)/2 int dim=(int)(0.5*sqrt(1+8*v.Dim())-0.5); int pos=0; float a=1/sqrt(2); assert(int(dim*(dim+1)/2)==v.Dim()); m.resize(dim,dim); for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Divide off-diagonal elements by sqrt(2) if (i==j) m(j,j) = v(pos); else { m(i,j) = a*v(pos); m(j,i) = a*v(pos); } ++pos; } } void map_lapackm2hclv(const Matrix &m, HCL_RnVector_d &v) { assert(m.rows()==m.cols()); assert(m.rows()==v.Dim()); int dim=m.rows(), pos=0; for (int i=0; i<dim; i++) for (int j=0; j<=i; j++) { // Multiply off-diagonal elements by sqrt(2) // to preserve inner products if (i==j) v(pos)=m(i,j); else v(pos)=sqrt(2)*m(i,j); ++pos; } } #endif /* double cond(const Matrix &m) { assert(m.nrows()==m.ncols()); LaGenMatDouble temp(m.nrows(), m.ncols()); for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) temp(i,j)=m(i,j); return cond(temp); } */ double cond(const Matrix &m) { assert(m.rows()==m.cols()); double min=DBL_MAX; double max=-DBL_MAX; LaGenMatDouble a(m); LaVectorDouble eigs(m.rows()); LaEigSolveSymmetricVecIP(a, eigs); for (int i=0; i<eigs.size(); i++) { if (eigs(i)<min) min=eigs(i); if (eigs(i)>max) max=eigs(i); } return max/min; } /* bool is_spd(const Matrix &m) { assert(m.nrows()==m.ncols()); LaGenMatDouble temp(m.nrows(), m.ncols()); for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) temp(i,j)=m(i,j); return is_spd(temp); } */ bool is_spd(const Matrix &m) { assert(m.rows()==m.cols()); LaGenMatDouble t=LaGenMatDouble(m); LaVectorDouble eigs=LaVectorDouble(m.rows()); LaEigSolveSymmetricVecIP(t,eigs); for (int i=0; i<eigs.size(); i++) { // std::cout << eigs(i) << std::endl; if (eigs(i)<=0) return false; } return true; } /* bool is_singular(const Matrix &m) { assert(m.nrows()==m.ncols()); LaGenMatDouble temp(m.nrows(), m.ncols()); for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) temp(i,j)=m(i,j); return is_singular(temp); } */ bool is_singular(const Matrix &m) { assert(m.rows()==m.cols()); LaGenMatDouble a(m); LaVectorDouble eigs(m.rows()); LaEigSolveSymmetricVecIP(a, eigs); for (int i=0; i<eigs.size(); i++) if (fabs(eigs(i))<0.00000001) return true; return false; } /* void force_min_eig(Matrix &m, double min_eig) { assert(m.nrows()==m.ncols()); // Map to Lapack++ matrix LaGenMatDouble temp(m.nrows(), m.ncols()); for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) temp(i,j)=m(i,j); // Force minimum eigenvalues force_min_eig(temp, min_eig); // Map back to MTL matrix for (unsigned int i=0; i<m.nrows(); i++) for (unsigned int j=0; j<m.ncols(); j++) m(i,j)=temp(i,j); } */ void force_min_eig(Matrix &m, double min_eig) { assert(m.rows()==m.cols()); LaGenMatDouble eigv(m); LaVectorDouble eigs_vector(m.rows()); LaGenMatDouble eigs = LaGenMatDouble::zeros(m.rows()); LaGenMatDouble temp(m.rows(), m.cols()); LaEigSolveSymmetricVecIP(eigv, eigs_vector); for (int i=0; i<m.rows(); i++) eigs(i,i)=std::max(min_eig, eigs_vector(i)); // Calculate EIGV*EIGS*EIGV' Blas_Mat_Mat_Mult(eigv, eigs, temp, 1.0, 0.0); Blas_Mat_Mat_Trans_Mult(temp, eigv, m, 1.0, 0.0); } void inverse(const Matrix &m, Matrix &inv) { inv.copy(m); LaVectorLongInt pivots(m.rows()); LUFactorizeIP(inv, pivots); LaLUInverseIP(inv, pivots); } } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <iostream.h> #include <fstream.h> /** * Requires GAlib from http://lancet.mit.edu/ga/ to run. */ #include <ga/ga.h> #include <ga/GARealGenome.h> #include <ga/GARealGenome.C> extern "C" { #include "tmp/scores.h" #include "tmp/tests.h" } // --------------------------------------------------------------------------- int threshold = 5; // threshold of spam vs. non-spam int nn, ny, yn, yy; // simple number of y/n diagnoses // These floats are the same as above, but incorrect scores are penalised // by how wrong they are. // float nyscore, ynscore; float nybias = 5.0; int sleepTime = 0; // time to sleep during runs float float_num_spam; float float_num_nonspam; // --------------------------------------------------------------------------- void printhits (FILE *fout) { if (num_tests == 0) { num_tests = 1; } fprintf (fout, "# SUMMARY: %6d / %6d\n#\n", ny, yn); fprintf (fout, "# Correctly non-spam: %6d %3.2f%% (%3.2f%% overall)\n", nn, (nn / (float) num_nonspam) * 100.0, (nn / (float) num_tests) * 100.0); fprintf (fout, "# Correctly spam: %6d %3.2f%% (%3.2f%% overall)\n", yy, (yy / (float) num_spam) * 100.0, (yy / (float) num_tests) * 100.0); fprintf (fout, "# False positives: %6d %3.2f%% (%3.2f%% overall, %6.0f adjusted)\n", ny, (ny / (float) num_nonspam) * 100.0, (ny / (float) num_tests) * 100.0, nyscore); fprintf (fout, "# False negatives: %6d %3.2f%% (%3.2f%% overall, %6.0f adjusted)\n", yn, (yn / (float) num_spam) * 100.0, (yn / (float) num_tests) * 100.0, ynscore); fprintf (fout, "# TOTAL: %6d %3.2f%%\n#\n", num_tests, 100.0); } // --------------------------------------------------------------------------- void writescores (FILE *fout) { int i; float score; for (i = 0; i < num_scores-1; i++) { score = scores[i]; fprintf (fout, "score %-30s %2.1f\n", score_names[i], score); } } // --------------------------------------------------------------------------- void fullcounthitsfromscores () { int file; float hits; int i; int overthresh; int nyint = 0; int ynint = 0; nn = ny = yn = yy = 0; for (file = 0; file < num_tests; file++) { hits = 0.0; for (i = num_tests_hit[file]-1; i >= 0; i--) { hits += scores[tests_hit[file][i]]; } overthresh = (hits >= threshold); // we use the xxscore vars as a weighted "crapness" score; ie. // higher is worse. incorrect diagnoses add (1 + incorrectness) // to them, where "incorrectness" is (num_points_over_threshold) / 5.0. // // This way, massively-incorrect scores are massively penalised. if (is_spam[file]) { if (overthresh) { yy++; } else { yn++; nyint += (int) (hits - threshold) + 5; } } else { if (overthresh) { ny++; ynint += (int) (threshold - hits) + 5; } else { nn++; } } } nyscore = ((float) nyint); // / 5.0; ynscore = ((float) ynint); // / 5.0; } void quickcounthitsfromscores () { int file; float hits; int i; int overthresh; int nyint = 0; int ynint = 0; for (file = 0; file < num_tests; file++) { hits = 0.0; for (i = num_tests_hit[file]-1; i >= 0; i--) { hits += scores[tests_hit[file][i]]; } // Craig: good tips, this should be faster overthresh = (hits >= threshold); if (is_spam[file]) { if (!overthresh) { ynint += (int) (threshold - hits) + 5; } } else { if (overthresh) { nyint += (int) (hits - threshold) + 5; } } } nyscore = ((float) nyint); // / 5.0; ynscore = ((float) ynint); // / 5.0; } // --------------------------------------------------------------------------- void copygenometoscores (GARealGenome &genome) { int i; for (i = 0; i < num_scores; i++) { if (is_mutatable[i]) { scores[i] = genome[i]; if (scores[i] == 0.0) { scores[i] = 0.1; } else if (scores[i] < range_lo[i]) { scores[i] = range_lo[i]; } else if (scores[i] > range_hi[i]) { scores[i] = range_hi[i]; } } else { scores[i] = bestscores[i]; // use the standard one } } } void fullcounthitsfromgenome (GARealGenome &genome) { if (genome.length() != num_scores) { cerr << "len != numscores: "<<genome.length()<<" "<<num_scores<<endl; exit(1); } copygenometoscores (genome); fullcounthitsfromscores (); } void quickcounthitsfromgenome (GARealGenome &genome) { copygenometoscores (genome); quickcounthitsfromscores (); } // --------------------------------------------------------------------------- // add up all the incorrect diagnoses, and use that as the fitness // score. Since we're trying to minimise the objective, this should // work OK -- we want it to be as low as possible. // float objective(GAGenome & c) { GARealGenome &genome = (GARealGenome &) c; quickcounthitsfromgenome(genome); if (sleepTime) { usleep(sleepTime); } // old old version; just use the # of messages // return ((float) yn + (ny * nybias)); // old version: use the proportion of messages to messages in the // correct category. //return (float) ((yn / (float) num_spam) //+ ((ny * nybias) / (float) num_nonspam)); // new version: similar to above, but penalise scores that // are way off. return (float) ((ynscore / float_num_spam) + ((nyscore * nybias) / float_num_nonspam)); } // --------------------------------------------------------------------------- void write_to_file (GARealGenome &genome, const char *fname) { FILE *fout; char namebuf[255]; fullcounthitsfromgenome (genome); snprintf (namebuf, 255, "%s", fname); fout = fopen (namebuf, "w"); printhits (fout); writescores (fout); fclose (fout); } // --------------------------------------------------------------------------- void fill_allele_set (GARealAlleleSetArray *setary) { float hi, lo; int i; for (i = 0; i < num_scores; i++) { if (is_mutatable[i]) { hi = range_hi[i]; lo = range_lo[i]; } else { hi = bestscores[i]; lo = bestscores[i]; } setary->add (lo, hi); } } // --------------------------------------------------------------------------- void usage () { cerr << "usage: evolve -s size [args]\n" << "\n" << " -z sleeptime = time to sleep in msecs (0 default, 10 = 33% cpu usage)\n" << " -s size = population size (300 recommended)\n" << " -b nybias = bias towards false negatives (5.0 default)\n" << "\n" << " -g ngens = generations to run (1500 default)\n" << " -c conv = run until convergence (1.00 default)\n" << " -m npops = migration with multi populations (5 default)\n" << "\n" << " -g and -c are mutually exclusive.\n" << " Steady-state mode is default, unless -m is used -- but currently\n" << " -m is unimplemented; you need to edit code to do it. sorry.\n" <<endl; exit (30); } int main (int argc, char **argv) { int arg; int demeMode = 0; int convergeMode = 0; int justCount = 0; int npops = 5; // num pops (for deme mode) int popsize = 0; // population size int generations = 1500; // generations to run float pconv = 1.00; // threshhold for when we have converged int nconv = 300; // how many gens back to check for convergence while ((arg = getopt (argc, argv, "b:c:s:m:g:Cz:")) != -1) { switch (arg) { case 'b': nybias = atof(optarg); break; case 's': popsize = atoi(optarg); break; case 'm': demeMode = 1; fprintf (stderr, "Deme mode not supported through cmdline args yet\n"); usage(); npops = atoi(optarg); break; case 'c': convergeMode = 1; pconv = atof(optarg); break; case 'C': justCount = 1; break; case 'g': demeMode = 0; generations = atoi(optarg); break; case 'z': sleepTime = atoi(optarg); break; case '?': usage(); break; } } loadscores (); loadtests (); float_num_spam = (float) num_spam; float_num_nonspam = (float) num_nonspam; if (justCount) { cout << "Counts for current genome:" << endl; // copy the base scores to the "scores" array int i; for (i = 0; i < num_scores; i++) { scores[i] = bestscores[i]; } fullcounthitsfromscores(); printhits (stdout); exit (0); } if (popsize == 0) { usage(); } GARandomSeed(); // use time ^ $$ // allow scores from -0.5 to 4.0 inclusive, in jumps of 0.1 // each test has it's own range within this GARealAlleleSetArray allelesetarray; fill_allele_set (&allelesetarray); GARealGenome genome(allelesetarray, objective); // use our score-perturbing initialiser, the default // gaussian mutator, and crossover. // don't let the genome change its length genome.resizeBehaviour (num_scores, num_scores); // steady-state seems to give best results GASteadyStateGA ga(genome); // incremental, faster but not as good //GAIncrementalGA ga(genome); //GADemeGA ga(genome); //ga.nPopulations(npops); ga.populationSize(popsize); if (convergeMode) { ga.pConvergence(pconv); ga.nConvergence(nconv); ga.terminator(GAGeneticAlgorithm::TerminateUponConvergence); } else { ga.set(gaNnGenerations, generations); // number of generations } ga.minimize(); // we want to minimize the objective ga.set(gaNpCrossover, 0.6); // probability of crossover ga.set(gaNpMutation, 0.05); // probability of mutation ga.set(gaNscoreFrequency, 1); // how often to record scores ga.set(gaNflushFrequency, 20); // how often to dump scores to file ga.set(gaNselectScores, // which scores should we track? GAStatistics::AllScores); ga.set(gaNscoreFilename, "evolve.scores"); ga.parameters(argc, argv); unlink ("evolve.scores"); cout << "Run this to watch progress scores:" << endl << "\ttail -f evolve.scores" << endl; cout << "evolving...\n"; int gens = 0; while(!ga.done()) { ga.step(); gens++; if (gens % 5 == 0) { cout << "."; cout.flush(); if (gens % 300 == 0) { cout << "\nProgress: gen=" << gens << " convergence=" << ga.statistics().convergence() << ":\n"; genome = ga.statistics().bestIndividual(); fullcounthitsfromgenome (genome); printhits (stdout); write_to_file (genome, "tmp/results.in_progress"); } } } cout << endl; genome = ga.statistics().bestIndividual(); cout << "Best genome found:" << endl; fullcounthitsfromgenome (genome); printhits (stdout); //cout << "Stats:\n" << ga.statistics() << endl; write_to_file (genome, "results.evolved"); cout << "Scores for this genome written to \"results.evolved\"." << endl; return 0; } <commit_msg>more frequent dumps<commit_after>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <iostream.h> #include <fstream.h> /** * Requires GAlib from http://lancet.mit.edu/ga/ to run. */ #include <ga/ga.h> #include <ga/GARealGenome.h> #include <ga/GARealGenome.C> extern "C" { #include "tmp/scores.h" #include "tmp/tests.h" } // --------------------------------------------------------------------------- int threshold = 5; // threshold of spam vs. non-spam int nn, ny, yn, yy; // simple number of y/n diagnoses // These floats are the same as above, but incorrect scores are penalised // by how wrong they are. // float nyscore, ynscore; float nybias = 5.0; int sleepTime = 0; // time to sleep during runs float float_num_spam; float float_num_nonspam; // --------------------------------------------------------------------------- void printhits (FILE *fout) { if (num_tests == 0) { num_tests = 1; } fprintf (fout, "# SUMMARY: %6d / %6d\n#\n", ny, yn); fprintf (fout, "# Correctly non-spam: %6d %3.2f%% (%3.2f%% overall)\n", nn, (nn / (float) num_nonspam) * 100.0, (nn / (float) num_tests) * 100.0); fprintf (fout, "# Correctly spam: %6d %3.2f%% (%3.2f%% overall)\n", yy, (yy / (float) num_spam) * 100.0, (yy / (float) num_tests) * 100.0); fprintf (fout, "# False positives: %6d %3.2f%% (%3.2f%% overall, %6.0f adjusted)\n", ny, (ny / (float) num_nonspam) * 100.0, (ny / (float) num_tests) * 100.0, nyscore); fprintf (fout, "# False negatives: %6d %3.2f%% (%3.2f%% overall, %6.0f adjusted)\n", yn, (yn / (float) num_spam) * 100.0, (yn / (float) num_tests) * 100.0, ynscore); fprintf (fout, "# TOTAL: %6d %3.2f%%\n#\n", num_tests, 100.0); } // --------------------------------------------------------------------------- void writescores (FILE *fout) { int i; float score; for (i = 0; i < num_scores-1; i++) { score = scores[i]; fprintf (fout, "score %-30s %2.1f\n", score_names[i], score); } } // --------------------------------------------------------------------------- void fullcounthitsfromscores () { int file; float hits; int i; int overthresh; int nyint = 0; int ynint = 0; nn = ny = yn = yy = 0; for (file = 0; file < num_tests; file++) { hits = 0.0; for (i = num_tests_hit[file]-1; i >= 0; i--) { hits += scores[tests_hit[file][i]]; } overthresh = (hits >= threshold); // we use the xxscore vars as a weighted "crapness" score; ie. // higher is worse. incorrect diagnoses add (1 + incorrectness) // to them, where "incorrectness" is (num_points_over_threshold) / 5.0. // // This way, massively-incorrect scores are massively penalised. if (is_spam[file]) { if (overthresh) { yy++; } else { yn++; nyint += (int) (hits - threshold) + 5; } } else { if (overthresh) { ny++; ynint += (int) (threshold - hits) + 5; } else { nn++; } } } nyscore = ((float) nyint); // / 5.0; ynscore = ((float) ynint); // / 5.0; } void quickcounthitsfromscores () { int file; float hits; int i; int overthresh; int nyint = 0; int ynint = 0; for (file = 0; file < num_tests; file++) { hits = 0.0; for (i = num_tests_hit[file]-1; i >= 0; i--) { hits += scores[tests_hit[file][i]]; } // Craig: good tips, this should be faster overthresh = (hits >= threshold); if (is_spam[file]) { if (!overthresh) { ynint += (int) (threshold - hits) + 5; } } else { if (overthresh) { nyint += (int) (hits - threshold) + 5; } } } nyscore = ((float) nyint); // / 5.0; ynscore = ((float) ynint); // / 5.0; } // --------------------------------------------------------------------------- void copygenometoscores (GARealGenome &genome) { int i; for (i = 0; i < num_scores; i++) { if (is_mutatable[i]) { scores[i] = genome[i]; if (scores[i] == 0.0) { scores[i] = 0.1; } else if (scores[i] < range_lo[i]) { scores[i] = range_lo[i]; } else if (scores[i] > range_hi[i]) { scores[i] = range_hi[i]; } } else { scores[i] = bestscores[i]; // use the standard one } } } void fullcounthitsfromgenome (GARealGenome &genome) { if (genome.length() != num_scores) { cerr << "len != numscores: "<<genome.length()<<" "<<num_scores<<endl; exit(1); } copygenometoscores (genome); fullcounthitsfromscores (); } void quickcounthitsfromgenome (GARealGenome &genome) { copygenometoscores (genome); quickcounthitsfromscores (); } // --------------------------------------------------------------------------- // add up all the incorrect diagnoses, and use that as the fitness // score. Since we're trying to minimise the objective, this should // work OK -- we want it to be as low as possible. // float objective(GAGenome & c) { GARealGenome &genome = (GARealGenome &) c; quickcounthitsfromgenome(genome); if (sleepTime) { usleep(sleepTime); } // old old version; just use the # of messages // return ((float) yn + (ny * nybias)); // old version: use the proportion of messages to messages in the // correct category. //return (float) ((yn / (float) num_spam) //+ ((ny * nybias) / (float) num_nonspam)); // new version: similar to above, but penalise scores that // are way off. return (float) ((ynscore / float_num_spam) + ((nyscore * nybias) / float_num_nonspam)); } // --------------------------------------------------------------------------- void write_to_file (GARealGenome &genome, const char *fname) { FILE *fout; char namebuf[255]; fullcounthitsfromgenome (genome); snprintf (namebuf, 255, "%s", fname); fout = fopen (namebuf, "w"); printhits (fout); writescores (fout); fclose (fout); } // --------------------------------------------------------------------------- void fill_allele_set (GARealAlleleSetArray *setary) { float hi, lo; int i; for (i = 0; i < num_scores; i++) { if (is_mutatable[i]) { hi = range_hi[i]; lo = range_lo[i]; } else { hi = bestscores[i]; lo = bestscores[i]; } setary->add (lo, hi); } } // --------------------------------------------------------------------------- void usage () { cerr << "usage: evolve -s size [args]\n" << "\n" << " -z sleeptime = time to sleep in msecs (0 default, 10 = 33% cpu usage)\n" << " -s size = population size (300 recommended)\n" << " -b nybias = bias towards false negatives (5.0 default)\n" << "\n" << " -g ngens = generations to run (1500 default)\n" << " -c conv = run until convergence (1.00 default)\n" << " -m npops = migration with multi populations (5 default)\n" << "\n" << " -g and -c are mutually exclusive.\n" << " Steady-state mode is default, unless -m is used -- but currently\n" << " -m is unimplemented; you need to edit code to do it. sorry.\n" <<endl; exit (30); } int main (int argc, char **argv) { int arg; int demeMode = 0; int convergeMode = 0; int justCount = 0; int npops = 5; // num pops (for deme mode) int popsize = 0; // population size int generations = 1500; // generations to run float pconv = 1.00; // threshhold for when we have converged int nconv = 300; // how many gens back to check for convergence while ((arg = getopt (argc, argv, "b:c:s:m:g:Cz:")) != -1) { switch (arg) { case 'b': nybias = atof(optarg); break; case 's': popsize = atoi(optarg); break; case 'm': demeMode = 1; fprintf (stderr, "Deme mode not supported through cmdline args yet\n"); usage(); npops = atoi(optarg); break; case 'c': convergeMode = 1; pconv = atof(optarg); break; case 'C': justCount = 1; break; case 'g': demeMode = 0; generations = atoi(optarg); break; case 'z': sleepTime = atoi(optarg); break; case '?': usage(); break; } } loadscores (); loadtests (); float_num_spam = (float) num_spam; float_num_nonspam = (float) num_nonspam; if (justCount) { cout << "Counts for current genome:" << endl; // copy the base scores to the "scores" array int i; for (i = 0; i < num_scores; i++) { scores[i] = bestscores[i]; } fullcounthitsfromscores(); printhits (stdout); exit (0); } if (popsize == 0) { usage(); } GARandomSeed(); // use time ^ $$ // allow scores from -0.5 to 4.0 inclusive, in jumps of 0.1 // each test has it's own range within this GARealAlleleSetArray allelesetarray; fill_allele_set (&allelesetarray); GARealGenome genome(allelesetarray, objective); // use our score-perturbing initialiser, the default // gaussian mutator, and crossover. // don't let the genome change its length genome.resizeBehaviour (num_scores, num_scores); // steady-state seems to give best results GASteadyStateGA ga(genome); // incremental, faster but not as good //GAIncrementalGA ga(genome); //GADemeGA ga(genome); //ga.nPopulations(npops); ga.populationSize(popsize); if (convergeMode) { ga.pConvergence(pconv); ga.nConvergence(nconv); ga.terminator(GAGeneticAlgorithm::TerminateUponConvergence); } else { ga.set(gaNnGenerations, generations); // number of generations } ga.minimize(); // we want to minimize the objective ga.set(gaNpCrossover, 0.6); // probability of crossover ga.set(gaNpMutation, 0.05); // probability of mutation ga.set(gaNscoreFrequency, 1); // how often to record scores ga.set(gaNflushFrequency, 20); // how often to dump scores to file ga.set(gaNselectScores, // which scores should we track? GAStatistics::AllScores); ga.set(gaNscoreFilename, "evolve.scores"); ga.parameters(argc, argv); unlink ("evolve.scores"); cout << "Run this to watch progress scores:" << endl << "\ttail -f evolve.scores" << endl; cout << "evolving...\n"; int gens = 0; while(!ga.done()) { ga.step(); gens++; if (gens % 5 == 0) { cout << "."; cout.flush(); if (gens % 30 == 0) { cout << "\nProgress: gen=" << gens << " convergence=" << ga.statistics().convergence() << ":\n"; } genome = ga.statistics().bestIndividual(); fullcounthitsfromgenome (genome); printhits (stdout); write_to_file (genome, "results.evolved"); } } cout << endl; cout << "Best genome found:" << endl; genome = ga.statistics().bestIndividual(); fullcounthitsfromgenome (genome); printhits (stdout); write_to_file (genome, "results.evolved"); cout << "Scores for this genome written to \"results.evolved\"." << endl; return 0; } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #pragma once #ifndef NET_IP6_ADDR_HPP #define NET_IP6_ADDR_HPP #include <common> #include <net/util.hpp> #include <cstdlib> #include <string> namespace net { namespace ip6 { /** * This type is thrown when creating an instance of Addr * with a std::string that doesn't represent a valid IPv6 * Address */ struct Invalid_Address : public std::runtime_error { using runtime_error::runtime_error; }; //< struct Invalid_Address /** * IPv6 Address representation */ struct Addr { constexpr Addr() noexcept : i32{{0, 0, 0, 0}} {} Addr(uint16_t a1, uint16_t a2, uint16_t b1, uint16_t b2, uint16_t c1, uint16_t c2, uint16_t d1, uint16_t d2) { i16[0] = htons(a1); i16[1] = htons(a2); i16[2] = htons(b1); i16[3] = htons(b2); i16[4] = htons(c1); i16[5] = htons(c2); i16[6] = htons(d1); i16[7] = htons(d2); } Addr(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { i32[0] = htonl(a); i32[1] = htonl(b); i32[2] = htonl(c); i32[3] = htonl(d); } Addr(const Addr& a) noexcept : i64{a.i64} {} Addr(Addr&& a) noexcept : i64{std::move(a.i64)} {} // returns this IPv6 Address as a string std::string str() const { char ipv6_addr[40]; snprintf(ipv6_addr, sizeof(ipv6_addr), "%0x:%0x:%0x:%0x:%0x:%0x:%0x:%0x", ntohs(i16[0]), ntohs(i16[1]), ntohs(i16[2]), ntohs(i16[3]), ntohs(i16[4]), ntohs(i16[5]), ntohs(i16[6]), ntohs(i16[7])); return ipv6_addr; } /** * Get a string representation of this type * * @return A string representation of this type */ std::string to_string() const { return str(); } // multicast IPv6 Addresses static const Addr node_all_nodes; // RFC 4921 static const Addr node_all_routers; // RFC 4921 static const Addr node_mDNSv6; // RFC 6762 (multicast DNSv6) // unspecified link-local Address static const Addr link_unspecified; static const Addr addr_any; // RFC 4291 2.4.6: // Link-Local Addresses are designed to be used for Addressing on a // neighbor discovery, or when no routers are present. // single link for purposes such as automatic Address configuration, static const Addr link_all_nodes; // RFC 4921 static const Addr link_all_routers; // RFC 4921 static const Addr link_mDNSv6; // RFC 6762 static const Addr link_dhcp_servers; // RFC 3315 static const Addr site_dhcp_servers; // RFC 3315 // returns true if this Addr is a IPv6 multicast Address bool is_multicast() const { /** RFC 4291 2.7 Multicast Addresses An IPv6 multicast Address is an identifier for a group of interfaces (typically on different nodes). An interface may belong to any number of multicast groups. Multicast Addresses have the following format: | 8 | 4 | 4 | 112 bits | +------ -+----+----+---------------------------------------------+ |11111111|flgs|scop| group ID | +--------+----+----+---------------------------------------------+ **/ return ((ntohs(i16[0]) & 0xFF00) == 0xFF00); } bool is_solicit_multicast() const { return ((ntohs(i32[0]) ^ (0xff020000)) | ntohs(i32[1]) | (ntohs(i32[2]) ^ (0x00000001)) | (ntohs(i32[3]) ^ 0xff)) == 0; } uint8_t* data() { return reinterpret_cast<uint8_t*> (i16.data()); } Addr& solicit(const Addr other) noexcept { i32[0] = htonl(0xFF020000); i32[1] = 0; i32[2] = htonl(0x1); i32[3] = htonl(0xFF000000) | other.i32[3]; return *this; } /** * **/ bool is_loopback() const noexcept { return i32[0] == 0 && i32[1] == 0 && i32[2] == 0 && ntohl(i32[3]) == 1; } template <typename T> T get_part(const uint8_t n) const { static_assert(std::is_same_v<T, uint8_t> or std::is_same_v<T, uint16_t> or std::is_same_v<T, uint32_t>, "Unallowed T"); if constexpr (std::is_same_v<T, uint8_t>) { Expects(n < 16); return i8[n]; } else if constexpr (std::is_same_v<T, uint16_t>) { Expects(n < 8); return i16[n]; } else if constexpr (std::is_same_v<T, uint32_t>) { Expects(n < 4); return i32[n]; } } /** * Assignment operator */ Addr& operator=(const Addr& other) noexcept { i64 = other.i64; return *this; } Addr& operator=(Addr&& other) noexcept { i64 = std::move(other.i64); return *this; } /** * Operator to check for equality */ bool operator==(const Addr& other) const noexcept { return i32 == other.i32; } /** * Operator to check for inequality */ bool operator!=(const Addr& other) const noexcept { return not (*this == other); } /** * Operator to check for greater-than relationship */ bool operator>(const Addr& other) const noexcept { return i32 > other.i32; } /** * Operator to check for greater-than-or-equal relationship */ bool operator>=(const Addr& other) const noexcept { return (*this > other or *this == other); } /** * Operator to check for lesser-than relationship */ bool operator<(const Addr& other) const noexcept { return not (*this >= other); } /** * Operator to check for lesser-than-or-equal relationship */ bool operator<=(const Addr& other) const noexcept { return (*this < other or *this == other); } /** * Operator to perform a bitwise-and operation on the given * IPv6 addresses */ Addr operator&(const Addr& other) const noexcept { return Addr{i32[0] & other.i32[0], i32[1] & other.i32[1], i32[2] & other.i32[2], i32[3] & other.i32[3] }; } Addr operator&(uint8_t prefix) const noexcept { int i = 3; uint8_t mask; uint32_t addr[32]; addr[0] = htonl(i32[0]); addr[1] = htonl(i32[1]); addr[2] = htonl(i32[2]); addr[3] = htonl(i32[3]); if (prefix > 128) { prefix = 128; } mask = 128 - prefix; while (mask >= 32) { addr[i--] = 0; mask -= 32; } if (mask != 0) { addr[i] &= (0xFFFFFFFF << mask); } return Addr { addr[0], addr[1], addr[2], addr[3] }; } Addr operator|(const Addr& other) const noexcept { return Addr{i32[0] | other.i32[0], i32[1] | other.i32[1], i32[2] | other.i32[2], i32[3] | other.i32[3] }; } Addr operator~() const noexcept { return Addr{~i32[0], ~i32[1], ~i32[2], ~i32[3]}; } union { std::array<uint64_t, 2> i64; std::array<uint32_t ,4> i32; std::array<uint16_t, 8> i16; std::array<uint8_t, 16> i8; }; } __attribute__((packed)); //< struct Addr static_assert(sizeof(Addr) == 16); } //< namespace ip6 } //< namespace net // Allow an IPv6 address to be used as key in e.g. std::unordered_map namespace std { template<> struct hash<net::ip6::Addr> { size_t operator()(const net::ip6::Addr& addr) const { // This is temporary. Use a proper hash return std::hash<uint64_t>{}(addr.i64[0] + addr.i64[1]); } }; } //< namespace std #endif <commit_msg>ip6: Don't move array because of gcc reasons<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #pragma once #ifndef NET_IP6_ADDR_HPP #define NET_IP6_ADDR_HPP #include <common> #include <net/util.hpp> #include <cstdlib> #include <string> namespace net { namespace ip6 { /** * This type is thrown when creating an instance of Addr * with a std::string that doesn't represent a valid IPv6 * Address */ struct Invalid_Address : public std::runtime_error { using runtime_error::runtime_error; }; //< struct Invalid_Address /** * IPv6 Address representation */ struct Addr { constexpr Addr() noexcept : i32{{0, 0, 0, 0}} {} Addr(uint16_t a1, uint16_t a2, uint16_t b1, uint16_t b2, uint16_t c1, uint16_t c2, uint16_t d1, uint16_t d2) { i16[0] = htons(a1); i16[1] = htons(a2); i16[2] = htons(b1); i16[3] = htons(b2); i16[4] = htons(c1); i16[5] = htons(c2); i16[6] = htons(d1); i16[7] = htons(d2); } Addr(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { i32[0] = htonl(a); i32[1] = htonl(b); i32[2] = htonl(c); i32[3] = htonl(d); } Addr(const Addr& a) noexcept : i64{a.i64} {} Addr(Addr&& a) noexcept : i64{a.i64} {} // returns this IPv6 Address as a string std::string str() const { char ipv6_addr[40]; snprintf(ipv6_addr, sizeof(ipv6_addr), "%0x:%0x:%0x:%0x:%0x:%0x:%0x:%0x", ntohs(i16[0]), ntohs(i16[1]), ntohs(i16[2]), ntohs(i16[3]), ntohs(i16[4]), ntohs(i16[5]), ntohs(i16[6]), ntohs(i16[7])); return ipv6_addr; } /** * Get a string representation of this type * * @return A string representation of this type */ std::string to_string() const { return str(); } // multicast IPv6 Addresses static const Addr node_all_nodes; // RFC 4921 static const Addr node_all_routers; // RFC 4921 static const Addr node_mDNSv6; // RFC 6762 (multicast DNSv6) // unspecified link-local Address static const Addr link_unspecified; static const Addr addr_any; // RFC 4291 2.4.6: // Link-Local Addresses are designed to be used for Addressing on a // neighbor discovery, or when no routers are present. // single link for purposes such as automatic Address configuration, static const Addr link_all_nodes; // RFC 4921 static const Addr link_all_routers; // RFC 4921 static const Addr link_mDNSv6; // RFC 6762 static const Addr link_dhcp_servers; // RFC 3315 static const Addr site_dhcp_servers; // RFC 3315 // returns true if this Addr is a IPv6 multicast Address bool is_multicast() const { /** RFC 4291 2.7 Multicast Addresses An IPv6 multicast Address is an identifier for a group of interfaces (typically on different nodes). An interface may belong to any number of multicast groups. Multicast Addresses have the following format: | 8 | 4 | 4 | 112 bits | +------ -+----+----+---------------------------------------------+ |11111111|flgs|scop| group ID | +--------+----+----+---------------------------------------------+ **/ return ((ntohs(i16[0]) & 0xFF00) == 0xFF00); } bool is_solicit_multicast() const { return ((ntohs(i32[0]) ^ (0xff020000)) | ntohs(i32[1]) | (ntohs(i32[2]) ^ (0x00000001)) | (ntohs(i32[3]) ^ 0xff)) == 0; } uint8_t* data() { return reinterpret_cast<uint8_t*> (i16.data()); } Addr& solicit(const Addr other) noexcept { i32[0] = htonl(0xFF020000); i32[1] = 0; i32[2] = htonl(0x1); i32[3] = htonl(0xFF000000) | other.i32[3]; return *this; } /** * **/ bool is_loopback() const noexcept { return i32[0] == 0 && i32[1] == 0 && i32[2] == 0 && ntohl(i32[3]) == 1; } template <typename T> T get_part(const uint8_t n) const { static_assert(std::is_same_v<T, uint8_t> or std::is_same_v<T, uint16_t> or std::is_same_v<T, uint32_t>, "Unallowed T"); if constexpr (std::is_same_v<T, uint8_t>) { Expects(n < 16); return i8[n]; } else if constexpr (std::is_same_v<T, uint16_t>) { Expects(n < 8); return i16[n]; } else if constexpr (std::is_same_v<T, uint32_t>) { Expects(n < 4); return i32[n]; } } /** * Assignment operator */ Addr& operator=(const Addr& other) noexcept { i64 = other.i64; return *this; } Addr& operator=(Addr&& other) noexcept { i64 = other.i64; return *this; } /** * Operator to check for equality */ bool operator==(const Addr& other) const noexcept { return i32 == other.i32; } /** * Operator to check for inequality */ bool operator!=(const Addr& other) const noexcept { return not (*this == other); } /** * Operator to check for greater-than relationship */ bool operator>(const Addr& other) const noexcept { return i32 > other.i32; } /** * Operator to check for greater-than-or-equal relationship */ bool operator>=(const Addr& other) const noexcept { return (*this > other or *this == other); } /** * Operator to check for lesser-than relationship */ bool operator<(const Addr& other) const noexcept { return not (*this >= other); } /** * Operator to check for lesser-than-or-equal relationship */ bool operator<=(const Addr& other) const noexcept { return (*this < other or *this == other); } /** * Operator to perform a bitwise-and operation on the given * IPv6 addresses */ Addr operator&(const Addr& other) const noexcept { return Addr{i32[0] & other.i32[0], i32[1] & other.i32[1], i32[2] & other.i32[2], i32[3] & other.i32[3] }; } Addr operator&(uint8_t prefix) const noexcept { int i = 3; uint8_t mask; uint32_t addr[32]; addr[0] = htonl(i32[0]); addr[1] = htonl(i32[1]); addr[2] = htonl(i32[2]); addr[3] = htonl(i32[3]); if (prefix > 128) { prefix = 128; } mask = 128 - prefix; while (mask >= 32) { addr[i--] = 0; mask -= 32; } if (mask != 0) { addr[i] &= (0xFFFFFFFF << mask); } return Addr { addr[0], addr[1], addr[2], addr[3] }; } Addr operator|(const Addr& other) const noexcept { return Addr{i32[0] | other.i32[0], i32[1] | other.i32[1], i32[2] | other.i32[2], i32[3] | other.i32[3] }; } Addr operator~() const noexcept { return Addr{~i32[0], ~i32[1], ~i32[2], ~i32[3]}; } union { std::array<uint64_t, 2> i64; std::array<uint32_t ,4> i32; std::array<uint16_t, 8> i16; std::array<uint8_t, 16> i8; }; } __attribute__((packed)); //< struct Addr static_assert(sizeof(Addr) == 16); } //< namespace ip6 } //< namespace net // Allow an IPv6 address to be used as key in e.g. std::unordered_map namespace std { template<> struct hash<net::ip6::Addr> { size_t operator()(const net::ip6::Addr& addr) const { // This is temporary. Use a proper hash return std::hash<uint64_t>{}(addr.i64[0] + addr.i64[1]); } }; } //< namespace std #endif <|endoftext|>
<commit_before> #include "TMainWindow.h" #include "Application.h" #include <iostream> using namespace org::toxic; using namespace std; TMainWindow::TMainWindow(BRect frame): BWindow(frame,"Guitar Master",B_TITLED_WINDOW,B_NOT_ZOOMABLE | B_NOT_RESIZABLE) { cout<<"Main window"<<endl; timer = new BMessageRunner(this,new BMessage(T_MSG_FRAME),50000,-1); ResizeTo(640,480); gameview = new TGameView(BRect(5,5,635,400)); AddChild(gameview); Show(); } TMainWindow::~TMainWindow() { cout<<"main window destructor"<<endl; delete timer; } void TMainWindow::MessageReceived(BMessage * mesg) { switch(mesg->what) { case T_MSG_FRAME: gameview->Render(); break; } } bool TMainWindow::QuitRequested() { be_app->PostMessage(B_QUIT_REQUESTED); return true; } <commit_msg>Just included a simply menu bar<commit_after> #include "TMainWindow.h" #include <Application.h> #include <MenuItem.h> #include <MenuBar.h> #include <Menu.h> #include <iostream> using namespace org::toxic; using namespace std; TMainWindow::TMainWindow(BRect frame): BWindow(frame,"Guitar Master",B_TITLED_WINDOW,B_NOT_ZOOMABLE | B_NOT_RESIZABLE) { cout<<"Main window"<<endl; timer = new BMessageRunner(this,new BMessage(T_MSG_FRAME),50000,-1); ResizeTo(640,480); BRect bounds = Bounds(); bounds.bottom = bounds.top + 15; BMenuBar * menubar = new BMenuBar(bounds,"main menu"); BMenu * menu; BMenuItem * item; //Game menu menu = new BMenu("Game"); //----items item = new BMenuItem("Quit",new BMessage(B_QUIT_REQUESTED),'Q'); menu->AddItem(item); menubar->AddItem(menu); //Songs menu menu = new BMenu("Songs"); // fill with available song list... menubar->AddItem(menu); AddChild(menubar); //menubar->ResizeToPreferred(); //BGLView bounds.top=menubar->Bounds().bottom+1; bounds.bottom = Bounds().bottom; gameview = new TGameView(bounds); AddChild(gameview); Show(); } TMainWindow::~TMainWindow() { cout<<"main window destructor"<<endl; delete timer; } void TMainWindow::MessageReceived(BMessage * mesg) { switch(mesg->what) { case T_MSG_FRAME: gameview->Render(); break; } } bool TMainWindow::QuitRequested() { be_app->PostMessage(B_QUIT_REQUESTED); return true; } <|endoftext|>
<commit_before>#include <string.h> #include <util/atomic.h> #include "GNSS_Clock.h" #include <MicroNMEA.h> GNSS_Clock gnss_clock; void GNSS_Clock::isr(void) { gnss_clock.ppsHandler(); } bool GNSS_Clock::begin(void* buffer, uint8_t len, uint8_t ppsPin, uint8_t edge) { _nmea.setBuffer(buffer, len); pinMode(ppsPin, INPUT); attachInterrupt(digitalPinToInterrupt(ppsPin), isr, edge); return true; } bool GNSS_Clock::readClock(RTCx::time_t *t) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { *t = _secondsSinceEpoch; r = true; } } return r; } bool GNSS_Clock::readClock(RTCx::time_t& t, long& latitude, long& longitude, long& altitude, bool& altitudeValid, char& navSystem, uint8_t& numSat, uint8_t& hdop) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { t = _secondsSinceEpoch; latitude = _latitude; longitude = _longitude; altitudeValid = _altitudeValid; if (_altitudeValid) altitude = _altitude; navSystem = _navSystem; numSat = _numSat; hdop = _hdop; r = true; } } return r; } bool GNSS_Clock::readClock(struct RTCx::tm *tm) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { RTCx::gmtime_r((const RTCx::time_t*)&_secondsSinceEpoch, tm); r = true; } } return r; } void GNSS_Clock::clear(void) { _isValid = false; _navSystem = '\0'; _numSat = 0; _hdop = 255; _latitude = 999000000L; _longitude = 999000000L; _altitude = _speed = _course = LONG_MIN; _altitudeValid = false; // _tm.tm_year = _tm.tm_mon = _tm.tm_mday = 0; // _tm.tm_yday = -1; // _tm.tm_hour = _tm.tm_min = _tm.tm_sec = 99; } void GNSS_Clock::ppsHandler(void) { _isValid = _nmea.isValid(); if (_isValid) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { struct RTCx::tm tm; tm.tm_year = _nmea.getYear() - 1900; tm.tm_mon = _nmea.getMonth() - 1; tm.tm_mday = _nmea.getDay(); tm.tm_hour = _nmea.getHour(); tm.tm_min = _nmea.getMinute(); tm.tm_sec = _nmea.getSecond(); tm.tm_yday = -1; _secondsSinceEpoch = RTCx::mktime(tm); if (_secondsSinceEpoch == -1) _isValid = false; else // Increment to get current time. NB this doesn't take into // account any leap seconds which may be added. ++_secondsSinceEpoch; _navSystem = _nmea.getNavSystem(); _numSat = _nmea.getNumSatellites(); _hdop = _nmea.getHDOP(); _latitude = _nmea.getLatitude(); _longitude = _nmea.getLongitude(); long tmp = LONG_MIN; _altitudeValid = _nmea.getAltitude(tmp); if (_altitudeValid) _altitude = tmp; } } else { clear(); } _nmea.clear(); if (_1ppsCallback) (*_1ppsCallback)(*this); } <commit_msg>Set time only if pointer not NULL<commit_after>#include <string.h> #include <util/atomic.h> #include "GNSS_Clock.h" #include <MicroNMEA.h> GNSS_Clock gnss_clock; void GNSS_Clock::isr(void) { gnss_clock.ppsHandler(); } bool GNSS_Clock::begin(void* buffer, uint8_t len, uint8_t ppsPin, uint8_t edge) { _nmea.setBuffer(buffer, len); pinMode(ppsPin, INPUT); attachInterrupt(digitalPinToInterrupt(ppsPin), isr, edge); return true; } bool GNSS_Clock::readClock(RTCx::time_t *t) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { if (t != NULL) *t = _secondsSinceEpoch; r = true; } } return r; } bool GNSS_Clock::readClock(RTCx::time_t& t, long& latitude, long& longitude, long& altitude, bool& altitudeValid, char& navSystem, uint8_t& numSat, uint8_t& hdop) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { t = _secondsSinceEpoch; latitude = _latitude; longitude = _longitude; altitudeValid = _altitudeValid; if (_altitudeValid) altitude = _altitude; navSystem = _navSystem; numSat = _numSat; hdop = _hdop; r = true; } } return r; } bool GNSS_Clock::readClock(struct RTCx::tm *tm) const { bool r = false; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { if (_isValid) { RTCx::gmtime_r((const RTCx::time_t*)&_secondsSinceEpoch, tm); r = true; } } return r; } void GNSS_Clock::clear(void) { _isValid = false; _navSystem = '\0'; _numSat = 0; _hdop = 255; _latitude = 999000000L; _longitude = 999000000L; _altitude = _speed = _course = LONG_MIN; _altitudeValid = false; // _tm.tm_year = _tm.tm_mon = _tm.tm_mday = 0; // _tm.tm_yday = -1; // _tm.tm_hour = _tm.tm_min = _tm.tm_sec = 99; } void GNSS_Clock::ppsHandler(void) { _isValid = _nmea.isValid(); if (_isValid) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { struct RTCx::tm tm; tm.tm_year = _nmea.getYear() - 1900; tm.tm_mon = _nmea.getMonth() - 1; tm.tm_mday = _nmea.getDay(); tm.tm_hour = _nmea.getHour(); tm.tm_min = _nmea.getMinute(); tm.tm_sec = _nmea.getSecond(); tm.tm_yday = -1; _secondsSinceEpoch = RTCx::mktime(tm); if (_secondsSinceEpoch == -1) _isValid = false; else // Increment to get current time. NB this doesn't take into // account any leap seconds which may be added. ++_secondsSinceEpoch; _navSystem = _nmea.getNavSystem(); _numSat = _nmea.getNumSatellites(); _hdop = _nmea.getHDOP(); _latitude = _nmea.getLatitude(); _longitude = _nmea.getLongitude(); long tmp = LONG_MIN; _altitudeValid = _nmea.getAltitude(tmp); if (_altitudeValid) _altitude = tmp; } } else { clear(); } _nmea.clear(); if (_1ppsCallback) (*_1ppsCallback)(*this); } <|endoftext|>
<commit_before>//===-- Symbols.cpp ---------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Host/Symbols.h" #include "lldb/Core/ArchSpec.h" #include "lldb/Core/DataBuffer.h" #include "lldb/Core/DataExtractor.h" #include "lldb/Core/Log.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/StreamString.h" #include "lldb/Core/Timer.h" #include "lldb/Core/UUID.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/Target.h" #include "lldb/Utility/SafeMachO.h" #include "llvm/Support/FileSystem.h" // From MacOSX system header "mach/machine.h" typedef int cpu_type_t; typedef int cpu_subtype_t; using namespace lldb; using namespace lldb_private; using namespace llvm::MachO; #if defined(__APPLE__) // Forward declaration of method defined in source/Host/macosx/Symbols.cpp int LocateMacOSXFilesUsingDebugSymbols(const ModuleSpec &module_spec, ModuleSpec &return_module_spec); #else int LocateMacOSXFilesUsingDebugSymbols(const ModuleSpec &module_spec, ModuleSpec &return_module_spec) { // Cannot find MacOSX files using debug symbols on non MacOSX. return 0; } #endif static bool FileAtPathContainsArchAndUUID(const FileSpec &file_fspec, const ArchSpec *arch, const lldb_private::UUID *uuid) { ModuleSpecList module_specs; if (ObjectFile::GetModuleSpecifications(file_fspec, 0, 0, module_specs)) { ModuleSpec spec; for (size_t i = 0; i < module_specs.GetSize(); ++i) { bool got_spec = module_specs.GetModuleSpecAtIndex(i, spec); assert(got_spec); if ((uuid == NULL || (spec.GetUUIDPtr() && spec.GetUUID() == *uuid)) && (arch == NULL || (spec.GetArchitecturePtr() && spec.GetArchitecture().IsCompatibleMatch(*arch)))) { return true; } } } return false; } static bool LocateDSYMInVincinityOfExecutable(const ModuleSpec &module_spec, FileSpec &dsym_fspec) { Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); const FileSpec *exec_fspec = module_spec.GetFileSpecPtr(); if (exec_fspec) { char path[PATH_MAX]; if (exec_fspec->GetPath(path, sizeof(path))) { // Make sure the module isn't already just a dSYM file... if (strcasestr(path, ".dSYM/Contents/Resources/DWARF") == NULL) { if (log) { if (module_spec.GetUUIDPtr() && module_spec.GetUUIDPtr()->IsValid()) { log->Printf( "Searching for dSYM bundle next to executable %s, UUID %s", path, module_spec.GetUUIDPtr()->GetAsString().c_str()); } else { log->Printf("Searching for dSYM bundle next to executable %s", path); } } ::strncat(path, ".dSYM/Contents/Resources/DWARF/", sizeof(path) - strlen(path) - 1); ::strncat(path, exec_fspec->GetFilename().AsCString(), sizeof(path) - strlen(path) - 1); dsym_fspec.SetFile(path, false); ModuleSpecList module_specs; ModuleSpec matched_module_spec; if (dsym_fspec.Exists() && FileAtPathContainsArchAndUUID(dsym_fspec, module_spec.GetArchitecturePtr(), module_spec.GetUUIDPtr())) { if (log) { log->Printf("dSYM with matching UUID & arch found at %s", path); } return true; } else { // Get a clean copy of the executable path, without the final filename FileSpec path_dir_fspec (exec_fspec->GetDirectory().AsCString(), true); std::string path_dir_str = path_dir_fspec.GetPath(); // Add a ".dSYM" name to each directory component of the path, stripping // off components. e.g. we may have a binary like // /S/L/F/Foundation.framework/Versions/A/Foundation // and // /S/L/F/Foundation.framework.dSYM // // so we'll need to start with /S/L/F/Foundation.framework/Versions/A, // add the .dSYM part to the "A", and if that doesn't exist, strip off // the "A" and try it again with "Versions", etc., until we find a dSYM // bundle or we've stripped off enough path components that there's no // need to continue. for (int i = 0; i < 4; i++) { std::string path_dir_plus_dsym (path_dir_str); path_dir_plus_dsym += ".dSYM/Contents/Resources/DWARF/"; path_dir_plus_dsym += exec_fspec->GetFilename().AsCString(); dsym_fspec.SetFile (path_dir_plus_dsym, true); if (dsym_fspec.Exists() && FileAtPathContainsArchAndUUID( dsym_fspec, module_spec.GetArchitecturePtr(), module_spec.GetUUIDPtr())) { if (log) { log->Printf("dSYM with matching UUID & arch found at %s", path_dir_plus_dsym.c_str()); } return true; } auto const last_slash = path_dir_str.rfind('/'); if (last_slash == std::string::npos) break; path_dir_str.resize(last_slash); } } } } } dsym_fspec.Clear(); return false; } FileSpec LocateExecutableSymbolFileDsym(const ModuleSpec &module_spec) { const FileSpec *exec_fspec = module_spec.GetFileSpecPtr(); const ArchSpec *arch = module_spec.GetArchitecturePtr(); const UUID *uuid = module_spec.GetUUIDPtr(); Timer scoped_timer( LLVM_PRETTY_FUNCTION, "LocateExecutableSymbolFileDsym (file = %s, arch = %s, uuid = %p)", exec_fspec ? exec_fspec->GetFilename().AsCString("<NULL>") : "<NULL>", arch ? arch->GetArchitectureName() : "<NULL>", (const void *)uuid); FileSpec symbol_fspec; ModuleSpec dsym_module_spec; // First try and find the dSYM in the same directory as the executable or in // an appropriate parent directory if (LocateDSYMInVincinityOfExecutable(module_spec, symbol_fspec) == false) { // We failed to easily find the dSYM above, so use DebugSymbols LocateMacOSXFilesUsingDebugSymbols(module_spec, dsym_module_spec); } else { dsym_module_spec.GetSymbolFileSpec() = symbol_fspec; } return dsym_module_spec.GetSymbolFileSpec(); } ModuleSpec Symbols::LocateExecutableObjectFile(const ModuleSpec &module_spec) { ModuleSpec result; const FileSpec *exec_fspec = module_spec.GetFileSpecPtr(); const ArchSpec *arch = module_spec.GetArchitecturePtr(); const UUID *uuid = module_spec.GetUUIDPtr(); Timer scoped_timer( LLVM_PRETTY_FUNCTION, "LocateExecutableObjectFile (file = %s, arch = %s, uuid = %p)", exec_fspec ? exec_fspec->GetFilename().AsCString("<NULL>") : "<NULL>", arch ? arch->GetArchitectureName() : "<NULL>", (const void *)uuid); ModuleSpecList module_specs; ModuleSpec matched_module_spec; if (exec_fspec && ObjectFile::GetModuleSpecifications(*exec_fspec, 0, 0, module_specs) && module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec)) { result.GetFileSpec() = exec_fspec; } else { LocateMacOSXFilesUsingDebugSymbols(module_spec, result); } return result; } FileSpec Symbols::LocateExecutableSymbolFile(const ModuleSpec &module_spec) { FileSpec symbol_file_spec = module_spec.GetSymbolFileSpec(); if (symbol_file_spec.IsAbsolute() && symbol_file_spec.Exists()) return symbol_file_spec; const char *symbol_filename = symbol_file_spec.GetFilename().AsCString(); if (symbol_filename && symbol_filename[0]) { FileSpecList debug_file_search_paths( Target::GetDefaultDebugFileSearchPaths()); // Add module directory. const ConstString &file_dir = module_spec.GetFileSpec().GetDirectory(); debug_file_search_paths.AppendIfUnique( FileSpec(file_dir.AsCString("."), true)); // Add current working directory. debug_file_search_paths.AppendIfUnique(FileSpec(".", true)); #ifndef LLVM_ON_WIN32 // Add /usr/lib/debug directory. debug_file_search_paths.AppendIfUnique(FileSpec("/usr/lib/debug", true)); #endif // LLVM_ON_WIN32 std::string uuid_str; const UUID &module_uuid = module_spec.GetUUID(); if (module_uuid.IsValid()) { // Some debug files are stored in the .build-id directory like this: // /usr/lib/debug/.build-id/ff/e7fe727889ad82bb153de2ad065b2189693315.debug uuid_str = module_uuid.GetAsString(""); uuid_str.insert(2, 1, '/'); uuid_str = uuid_str + ".debug"; } size_t num_directories = debug_file_search_paths.GetSize(); for (size_t idx = 0; idx < num_directories; ++idx) { FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex(idx); dirspec.ResolvePath(); if (!dirspec.Exists() || !dirspec.IsDirectory()) continue; std::vector<std::string> files; std::string dirname = dirspec.GetPath(); files.push_back(dirname + "/" + symbol_filename); files.push_back(dirname + "/.debug/" + symbol_filename); files.push_back(dirname + "/.build-id/" + uuid_str); // Some debug files may stored in the module directory like this: // /usr/lib/debug/usr/lib/library.so.debug if (!file_dir.IsEmpty()) files.push_back(dirname + file_dir.AsCString() + "/" + symbol_filename); const uint32_t num_files = files.size(); for (size_t idx_file = 0; idx_file < num_files; ++idx_file) { const std::string &filename = files[idx_file]; FileSpec file_spec(filename, true); if (llvm::sys::fs::equivalent(file_spec.GetPath(), module_spec.GetFileSpec().GetPath())) continue; if (file_spec.Exists()) { lldb_private::ModuleSpecList specs; const size_t num_specs = ObjectFile::GetModuleSpecifications(file_spec, 0, 0, specs); assert(num_specs <= 1 && "Symbol Vendor supports only a single architecture"); if (num_specs == 1) { ModuleSpec mspec; if (specs.GetModuleSpecAtIndex(0, mspec)) { if (mspec.GetUUID() == module_uuid) return file_spec; } } } } } } return LocateExecutableSymbolFileDsym(module_spec); } #if !defined(__APPLE__) FileSpec Symbols::FindSymbolFileInBundle(const FileSpec &symfile_bundle, const lldb_private::UUID *uuid, const ArchSpec *arch) { // FIXME return FileSpec(); } bool Symbols::DownloadObjectAndSymbolFile(ModuleSpec &module_spec, bool force_lookup) { // Fill in the module_spec.GetFileSpec() for the object file and/or the // module_spec.GetSymbolFileSpec() for the debug symbols file. return false; } #endif <commit_msg>Change the code I added to LocateDSYMInVincinityOfExecutable to use the FileSpec methods for adding/removing file path components instead of using std::strings; feedback from Sean on the change I added in r305441. <rdar://problem/31825940><commit_after>//===-- Symbols.cpp ---------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Host/Symbols.h" #include "lldb/Core/ArchSpec.h" #include "lldb/Core/DataBuffer.h" #include "lldb/Core/DataExtractor.h" #include "lldb/Core/Log.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/StreamString.h" #include "lldb/Core/Timer.h" #include "lldb/Core/UUID.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/Target.h" #include "lldb/Utility/SafeMachO.h" #include "llvm/Support/FileSystem.h" // From MacOSX system header "mach/machine.h" typedef int cpu_type_t; typedef int cpu_subtype_t; using namespace lldb; using namespace lldb_private; using namespace llvm::MachO; #if defined(__APPLE__) // Forward declaration of method defined in source/Host/macosx/Symbols.cpp int LocateMacOSXFilesUsingDebugSymbols(const ModuleSpec &module_spec, ModuleSpec &return_module_spec); #else int LocateMacOSXFilesUsingDebugSymbols(const ModuleSpec &module_spec, ModuleSpec &return_module_spec) { // Cannot find MacOSX files using debug symbols on non MacOSX. return 0; } #endif static bool FileAtPathContainsArchAndUUID(const FileSpec &file_fspec, const ArchSpec *arch, const lldb_private::UUID *uuid) { ModuleSpecList module_specs; if (ObjectFile::GetModuleSpecifications(file_fspec, 0, 0, module_specs)) { ModuleSpec spec; for (size_t i = 0; i < module_specs.GetSize(); ++i) { bool got_spec = module_specs.GetModuleSpecAtIndex(i, spec); assert(got_spec); if ((uuid == NULL || (spec.GetUUIDPtr() && spec.GetUUID() == *uuid)) && (arch == NULL || (spec.GetArchitecturePtr() && spec.GetArchitecture().IsCompatibleMatch(*arch)))) { return true; } } } return false; } static bool LocateDSYMInVincinityOfExecutable(const ModuleSpec &module_spec, FileSpec &dsym_fspec) { Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); const FileSpec *exec_fspec = module_spec.GetFileSpecPtr(); if (exec_fspec) { char path[PATH_MAX]; if (exec_fspec->GetPath(path, sizeof(path))) { // Make sure the module isn't already just a dSYM file... if (strcasestr(path, ".dSYM/Contents/Resources/DWARF") == NULL) { if (log) { if (module_spec.GetUUIDPtr() && module_spec.GetUUIDPtr()->IsValid()) { log->Printf( "Searching for dSYM bundle next to executable %s, UUID %s", path, module_spec.GetUUIDPtr()->GetAsString().c_str()); } else { log->Printf("Searching for dSYM bundle next to executable %s", path); } } ::strncat(path, ".dSYM/Contents/Resources/DWARF/", sizeof(path) - strlen(path) - 1); ::strncat(path, exec_fspec->GetFilename().AsCString(), sizeof(path) - strlen(path) - 1); dsym_fspec.SetFile(path, false); ModuleSpecList module_specs; ModuleSpec matched_module_spec; if (dsym_fspec.Exists() && FileAtPathContainsArchAndUUID(dsym_fspec, module_spec.GetArchitecturePtr(), module_spec.GetUUIDPtr())) { if (log) { log->Printf("dSYM with matching UUID & arch found at %s", path); } return true; } else { FileSpec parent_dirs = exec_fspec; // Remove the binary name from the FileSpec parent_dirs.RemoveLastPathComponent(); // Add a ".dSYM" name to each directory component of the path, stripping // off components. e.g. we may have a binary like // /S/L/F/Foundation.framework/Versions/A/Foundation // and // /S/L/F/Foundation.framework.dSYM // // so we'll need to start with /S/L/F/Foundation.framework/Versions/A, // add the .dSYM part to the "A", and if that doesn't exist, strip off // the "A" and try it again with "Versions", etc., until we find a dSYM // bundle or we've stripped off enough path components that there's no // need to continue. for (int i = 0; i < 4; i++) { // Does this part of the path have a "." character - could it be a bundle's // top level directory? const char *fn = parent_dirs.GetFilename().AsCString(); if (fn == nullptr) break; if (::strchr (fn, '.') != nullptr) { dsym_fspec = parent_dirs; dsym_fspec.RemoveLastPathComponent(); // If the current directory name is "Foundation.framework", see if // "Foundation.framework.dSYM/Contents/Resources/DWARF/Foundation" // exists & has the right uuid. std::string dsym_fn = fn; dsym_fn += ".dSYM"; dsym_fspec.AppendPathComponent(dsym_fn.c_str()); dsym_fspec.AppendPathComponent("Contents"); dsym_fspec.AppendPathComponent("Resources"); dsym_fspec.AppendPathComponent("DWARF"); dsym_fspec.AppendPathComponent(exec_fspec->GetFilename().AsCString()); if (dsym_fspec.Exists() && FileAtPathContainsArchAndUUID( dsym_fspec, module_spec.GetArchitecturePtr(), module_spec.GetUUIDPtr())) { if (log) { log->Printf("dSYM with matching UUID & arch found at %s", dsym_fspec.GetPath().c_str()); } return true; } } parent_dirs.RemoveLastPathComponent(); } } } } } dsym_fspec.Clear(); return false; } FileSpec LocateExecutableSymbolFileDsym(const ModuleSpec &module_spec) { const FileSpec *exec_fspec = module_spec.GetFileSpecPtr(); const ArchSpec *arch = module_spec.GetArchitecturePtr(); const UUID *uuid = module_spec.GetUUIDPtr(); Timer scoped_timer( LLVM_PRETTY_FUNCTION, "LocateExecutableSymbolFileDsym (file = %s, arch = %s, uuid = %p)", exec_fspec ? exec_fspec->GetFilename().AsCString("<NULL>") : "<NULL>", arch ? arch->GetArchitectureName() : "<NULL>", (const void *)uuid); FileSpec symbol_fspec; ModuleSpec dsym_module_spec; // First try and find the dSYM in the same directory as the executable or in // an appropriate parent directory if (LocateDSYMInVincinityOfExecutable(module_spec, symbol_fspec) == false) { // We failed to easily find the dSYM above, so use DebugSymbols LocateMacOSXFilesUsingDebugSymbols(module_spec, dsym_module_spec); } else { dsym_module_spec.GetSymbolFileSpec() = symbol_fspec; } return dsym_module_spec.GetSymbolFileSpec(); } ModuleSpec Symbols::LocateExecutableObjectFile(const ModuleSpec &module_spec) { ModuleSpec result; const FileSpec *exec_fspec = module_spec.GetFileSpecPtr(); const ArchSpec *arch = module_spec.GetArchitecturePtr(); const UUID *uuid = module_spec.GetUUIDPtr(); Timer scoped_timer( LLVM_PRETTY_FUNCTION, "LocateExecutableObjectFile (file = %s, arch = %s, uuid = %p)", exec_fspec ? exec_fspec->GetFilename().AsCString("<NULL>") : "<NULL>", arch ? arch->GetArchitectureName() : "<NULL>", (const void *)uuid); ModuleSpecList module_specs; ModuleSpec matched_module_spec; if (exec_fspec && ObjectFile::GetModuleSpecifications(*exec_fspec, 0, 0, module_specs) && module_specs.FindMatchingModuleSpec(module_spec, matched_module_spec)) { result.GetFileSpec() = exec_fspec; } else { LocateMacOSXFilesUsingDebugSymbols(module_spec, result); } return result; } FileSpec Symbols::LocateExecutableSymbolFile(const ModuleSpec &module_spec) { FileSpec symbol_file_spec = module_spec.GetSymbolFileSpec(); if (symbol_file_spec.IsAbsolute() && symbol_file_spec.Exists()) return symbol_file_spec; const char *symbol_filename = symbol_file_spec.GetFilename().AsCString(); if (symbol_filename && symbol_filename[0]) { FileSpecList debug_file_search_paths( Target::GetDefaultDebugFileSearchPaths()); // Add module directory. const ConstString &file_dir = module_spec.GetFileSpec().GetDirectory(); debug_file_search_paths.AppendIfUnique( FileSpec(file_dir.AsCString("."), true)); // Add current working directory. debug_file_search_paths.AppendIfUnique(FileSpec(".", true)); #ifndef LLVM_ON_WIN32 // Add /usr/lib/debug directory. debug_file_search_paths.AppendIfUnique(FileSpec("/usr/lib/debug", true)); #endif // LLVM_ON_WIN32 std::string uuid_str; const UUID &module_uuid = module_spec.GetUUID(); if (module_uuid.IsValid()) { // Some debug files are stored in the .build-id directory like this: // /usr/lib/debug/.build-id/ff/e7fe727889ad82bb153de2ad065b2189693315.debug uuid_str = module_uuid.GetAsString(""); uuid_str.insert(2, 1, '/'); uuid_str = uuid_str + ".debug"; } size_t num_directories = debug_file_search_paths.GetSize(); for (size_t idx = 0; idx < num_directories; ++idx) { FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex(idx); dirspec.ResolvePath(); if (!dirspec.Exists() || !dirspec.IsDirectory()) continue; std::vector<std::string> files; std::string dirname = dirspec.GetPath(); files.push_back(dirname + "/" + symbol_filename); files.push_back(dirname + "/.debug/" + symbol_filename); files.push_back(dirname + "/.build-id/" + uuid_str); // Some debug files may stored in the module directory like this: // /usr/lib/debug/usr/lib/library.so.debug if (!file_dir.IsEmpty()) files.push_back(dirname + file_dir.AsCString() + "/" + symbol_filename); const uint32_t num_files = files.size(); for (size_t idx_file = 0; idx_file < num_files; ++idx_file) { const std::string &filename = files[idx_file]; FileSpec file_spec(filename, true); if (llvm::sys::fs::equivalent(file_spec.GetPath(), module_spec.GetFileSpec().GetPath())) continue; if (file_spec.Exists()) { lldb_private::ModuleSpecList specs; const size_t num_specs = ObjectFile::GetModuleSpecifications(file_spec, 0, 0, specs); assert(num_specs <= 1 && "Symbol Vendor supports only a single architecture"); if (num_specs == 1) { ModuleSpec mspec; if (specs.GetModuleSpecAtIndex(0, mspec)) { if (mspec.GetUUID() == module_uuid) return file_spec; } } } } } } return LocateExecutableSymbolFileDsym(module_spec); } #if !defined(__APPLE__) FileSpec Symbols::FindSymbolFileInBundle(const FileSpec &symfile_bundle, const lldb_private::UUID *uuid, const ArchSpec *arch) { // FIXME return FileSpec(); } bool Symbols::DownloadObjectAndSymbolFile(ModuleSpec &module_spec, bool force_lookup) { // Fill in the module_spec.GetFileSpec() for the object file and/or the // module_spec.GetSymbolFileSpec() for the debug symbols file. return false; } #endif <|endoftext|>
<commit_before>#include "Game/Clock.h" #include <map> #include <chrono> #include "Exceptions/Out_Of_Time_Exception.h" Clock::Clock(double duration_seconds, size_t moves_to_reset, double increment_seconds) : whose_turn(WHITE), use_clock(duration_seconds > 0), use_reset(moves_to_reset > 0), move_count_reset(moves_to_reset), clocks_running(false) { timers[WHITE] = fractional_seconds(duration_seconds); timers[BLACK] = fractional_seconds(duration_seconds); initial_time[WHITE] = fractional_seconds(duration_seconds); initial_time[BLACK] = fractional_seconds(duration_seconds); increment[WHITE] = fractional_seconds(increment_seconds); increment[BLACK] = fractional_seconds(increment_seconds); } bool Clock::is_running() const { return clocks_running; } void Clock::punch() { auto time_this_punch = std::chrono::steady_clock::now(); if( ! use_clock) { return; } if( ! clocks_running) { throw std::runtime_error("Clock has not been started."); } timers[whose_turn] -= (time_this_punch - time_previous_punch); if(timers[whose_turn] < std::chrono::seconds(0)) { throw Out_Of_Time_Exception(whose_turn); } if(use_reset && (++moves[whose_turn] == move_count_reset)) { timers[whose_turn] = initial_time[whose_turn]; moves[whose_turn] = 0; } whose_turn = opposite(whose_turn); time_previous_punch = time_this_punch; timers[whose_turn] += increment[whose_turn]; } void Clock::stop() { auto time_stop = std::chrono::steady_clock::now(); timers[whose_turn] -= (time_stop - time_previous_punch); clocks_running = false; } void Clock::start() { time_previous_punch = std::chrono::steady_clock::now(); clocks_running = true; } double Clock::time_left(Color color) const { if( ! use_clock) { return 0.0; } if(whose_turn != color || ! clocks_running) { return timers.at(color).count(); } else { auto now = std::chrono::steady_clock::now(); return fractional_seconds(timers.at(color) - (now - time_previous_punch)).count(); } } int Clock::moves_to_reset(Color color) const { if(use_reset) { return move_count_reset - (moves.at(color) % move_count_reset); } else { return std::numeric_limits<int>::max(); } } Color Clock::running_for() const { return whose_turn; } void Clock::set_time(Color player, double new_time_seconds) const { timers[player] = fractional_seconds(new_time_seconds); } <commit_msg>Set initial move count in clock<commit_after>#include "Game/Clock.h" #include <map> #include <chrono> #include "Exceptions/Out_Of_Time_Exception.h" Clock::Clock(double duration_seconds, size_t moves_to_reset, double increment_seconds) : whose_turn(WHITE), use_clock(duration_seconds > 0), use_reset(moves_to_reset > 0), move_count_reset(moves_to_reset), clocks_running(false) { timers[WHITE] = fractional_seconds(duration_seconds); timers[BLACK] = fractional_seconds(duration_seconds); initial_time[WHITE] = fractional_seconds(duration_seconds); initial_time[BLACK] = fractional_seconds(duration_seconds); increment[WHITE] = fractional_seconds(increment_seconds); increment[BLACK] = fractional_seconds(increment_seconds); moves[WHITE] = 0; moves[BLACK] = 0; } bool Clock::is_running() const { return clocks_running; } void Clock::punch() { auto time_this_punch = std::chrono::steady_clock::now(); if( ! use_clock) { return; } if( ! clocks_running) { throw std::runtime_error("Clock has not been started."); } timers[whose_turn] -= (time_this_punch - time_previous_punch); if(timers[whose_turn] < std::chrono::seconds(0)) { throw Out_Of_Time_Exception(whose_turn); } if(use_reset && (++moves[whose_turn] == move_count_reset)) { timers[whose_turn] = initial_time[whose_turn]; moves[whose_turn] = 0; } whose_turn = opposite(whose_turn); time_previous_punch = time_this_punch; timers[whose_turn] += increment[whose_turn]; } void Clock::stop() { auto time_stop = std::chrono::steady_clock::now(); timers[whose_turn] -= (time_stop - time_previous_punch); clocks_running = false; } void Clock::start() { time_previous_punch = std::chrono::steady_clock::now(); clocks_running = true; } double Clock::time_left(Color color) const { if( ! use_clock) { return 0.0; } if(whose_turn != color || ! clocks_running) { return timers.at(color).count(); } else { auto now = std::chrono::steady_clock::now(); return fractional_seconds(timers.at(color) - (now - time_previous_punch)).count(); } } int Clock::moves_to_reset(Color color) const { if(use_reset) { return move_count_reset - (moves.at(color) % move_count_reset); } else { return std::numeric_limits<int>::max(); } } Color Clock::running_for() const { return whose_turn; } void Clock::set_time(Color player, double new_time_seconds) const { timers[player] = fractional_seconds(new_time_seconds); } <|endoftext|>
<commit_before>/* * Copyright (c) 2009 Steven Noonan <[email protected]> * and Miah Clayton <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR 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 "universal_include.h" #include "App/app.h" #include "App/preferences.h" #include "Graphics/graphics.h" #include "Interface/interface.h" Interface::Interface() : m_dragWindow(NULL), m_fpsWidget(NULL), m_rendererWidget(NULL) { } Interface::~Interface() { while ( m_widgetList.valid(0) ) { Widget *w = m_widgetList[0]; m_widgetList.remove ( 0 ); delete w; w = NULL; } m_fpsWidget = NULL; m_rendererWidget = NULL; } void Interface::Update () { static Uint8 lastButtonState = 0; int x, y; Uint8 buttonState = SDL_GetMouseState ( &x, &y ); if ( buttonState & SDL_BUTTON(1) ) { //if (!(lastButtonState & SDL_BUTTON(1))) { MouseDown ( true, x, y ); //} } else { //if ( lastButtonState & SDL_BUTTON(1) ) { MouseDown ( false, x, y ); //} } lastButtonState = buttonState; } void Interface::SetDragWindow ( Window *_window ) { m_dragWindow = _window; } Widget *Interface::InsideWidget ( int _mouseX, int _mouseY ) { for ( int i = m_widgetList.size() - 1; i >= 0; i-- ) { if ( m_widgetList[i]->IsInsideWidget ( _mouseX, _mouseY ) ) return m_widgetList[i]; } return NULL; } void Interface::AddWidget ( Widget *_widget ) { m_widgetList.insert ( _widget ); } Widget *Interface::GetWidgetOfType ( WidgetClass _widgetType ) { for ( int i = m_widgetList.size() - 1; i >= 0; i-- ) { if ( m_widgetList[i]->ClassID() == _widgetType ) { return m_widgetList[i]; } } return NULL; } void Interface::RemoveWidget ( Widget *_widget ) { int id = m_widgetList.find ( _widget ); if ( id == -1 ) { g_console->SetColour ( IO::Console::FG_YELLOW | IO::Console::FG_INTENSITY ); g_console->WriteLine ( "WARNING: Tried to remove '%08x' from list but it wasn't found!", (void *)_widget ); g_console->SetColour (); } else m_widgetList.remove ( id ); delete _widget; } int Interface::SendEnterKey () { for ( int i = m_widgetList.size() - 1; i >= 0; i-- ) { Widget *widget = m_widgetList[i]; if ( widget->HasEnterKeyDefault() ) return widget->SendEnterKey (); } return 0; } int Interface::MouseDown ( bool _mouseDown, Sint32 x, Sint32 y ) { if ( m_dragWindow && _mouseDown) { return m_dragWindow->MouseDown ( _mouseDown, x, y ); } else { for ( int i = m_widgetList.size() - 1; i >= 0; i-- ) { Widget *widget = m_widgetList[i]; if ( x < widget->m_position.x || y < widget->m_position.y ) continue; if ( x > ( widget->m_position.x + widget->m_position.w ) || y > ( widget->m_position.y + widget->m_position.h ) ) continue; return widget->MouseDown ( _mouseDown, x, y ); } return 0; } } void Interface::UpdateRendererWidget () { char speedCaption[128]; sprintf ( speedCaption, "Renderer: %s", g_graphics->RendererName() ); if ( !m_rendererWidget ) { m_rendererWidget = new TextUI( speedCaption, MAKERGB(255,255,255), 3, g_graphics->GetScreenHeight () - 29 ); m_widgetList.insert ( m_rendererWidget ); } m_rendererWidget->SetText ( speedCaption ); } void Interface::UpdateFPS ( unsigned int _fps ) { char fpsCaption[32]; Uint32 color = 0; if ( _fps >= 50 ) color = MAKERGB(0,255,0); // GREEN else if ( _fps < 50 && _fps >= 30 ) color = MAKERGB(255,255,0); // YELLOW else if ( _fps < 30 ) color = MAKERGB(255,0,0); // RED sprintf ( fpsCaption, "FPS: %d", _fps ); if ( !m_fpsWidget ) { m_fpsWidget = new TextUI( fpsCaption, color, 3, g_graphics->GetScreenHeight () - 40 ); m_widgetList.insert ( m_fpsWidget ); } m_fpsWidget->SetColor ( color ); m_fpsWidget->SetText ( fpsCaption ); } void Interface::RenderWidgets() { for ( size_t i = 0; i < m_widgetList.size(); i++ ) { Widget *widget = m_widgetList[i]; if ( widget->Expired() ) { m_widgetList.remove ( i ); delete widget; i--; continue; } widget->Update(); widget->Render(); } } void Interface::InitWidgets () { for ( size_t i = 0; i < m_widgetList.size(); i++ ) { m_widgetList[i]->Initialise(); } } Interface *g_interface; <commit_msg>Interface: implement window focusing<commit_after>/* * Copyright (c) 2009 Steven Noonan <[email protected]> * and Miah Clayton <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR 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 "universal_include.h" #include "App/app.h" #include "App/preferences.h" #include "Graphics/graphics.h" #include "Interface/interface.h" Interface::Interface() : m_dragWindow(NULL), m_fpsWidget(NULL), m_rendererWidget(NULL) { } Interface::~Interface() { while ( m_widgetList.valid(0) ) { Widget *w = m_widgetList[0]; m_widgetList.remove ( 0 ); delete w; w = NULL; } m_fpsWidget = NULL; m_rendererWidget = NULL; } void Interface::Update () { static Uint8 lastButtonState = 0; int x, y; Uint8 buttonState = SDL_GetMouseState ( &x, &y ); if ( buttonState & SDL_BUTTON(1) ) { //if (!(lastButtonState & SDL_BUTTON(1))) { MouseDown ( true, x, y ); //} } else { //if ( lastButtonState & SDL_BUTTON(1) ) { MouseDown ( false, x, y ); //} } lastButtonState = buttonState; } void Interface::SetDragWindow ( Window *_window ) { m_dragWindow = _window; if (_window) { int id = m_widgetList.find(_window); m_widgetList.remove(id); m_widgetList.insert(_window); } } Widget *Interface::InsideWidget ( int _mouseX, int _mouseY ) { for ( int i = m_widgetList.size() - 1; i >= 0; i-- ) { if ( m_widgetList[i]->IsInsideWidget ( _mouseX, _mouseY ) ) return m_widgetList[i]; } return NULL; } void Interface::AddWidget ( Widget *_widget ) { m_widgetList.insert ( _widget ); } Widget *Interface::GetWidgetOfType ( WidgetClass _widgetType ) { for ( int i = m_widgetList.size() - 1; i >= 0; i-- ) { if ( m_widgetList[i]->ClassID() == _widgetType ) { return m_widgetList[i]; } } return NULL; } void Interface::RemoveWidget ( Widget *_widget ) { int id = m_widgetList.find ( _widget ); if ( id == -1 ) { g_console->SetColour ( IO::Console::FG_YELLOW | IO::Console::FG_INTENSITY ); g_console->WriteLine ( "WARNING: Tried to remove '%08x' from list but it wasn't found!", (void *)_widget ); g_console->SetColour (); } else m_widgetList.remove ( id ); delete _widget; } int Interface::SendEnterKey () { for ( int i = m_widgetList.size() - 1; i >= 0; i-- ) { Widget *widget = m_widgetList[i]; if ( widget->HasEnterKeyDefault() ) return widget->SendEnterKey (); } return 0; } int Interface::MouseDown ( bool _mouseDown, Sint32 x, Sint32 y ) { if ( m_dragWindow && _mouseDown) { return m_dragWindow->MouseDown ( _mouseDown, x, y ); } else { for ( int i = m_widgetList.size() - 1; i >= 0; i-- ) { Widget *widget = m_widgetList[i]; if ( x < widget->m_position.x || y < widget->m_position.y ) continue; if ( x > ( widget->m_position.x + widget->m_position.w ) || y > ( widget->m_position.y + widget->m_position.h ) ) continue; return widget->MouseDown ( _mouseDown, x, y ); } return 0; } } void Interface::UpdateRendererWidget () { char speedCaption[128]; sprintf ( speedCaption, "Renderer: %s", g_graphics->RendererName() ); if ( !m_rendererWidget ) { m_rendererWidget = new TextUI( speedCaption, MAKERGB(255,255,255), 3, g_graphics->GetScreenHeight () - 29 ); m_widgetList.insert ( m_rendererWidget ); } m_rendererWidget->SetText ( speedCaption ); } void Interface::UpdateFPS ( unsigned int _fps ) { char fpsCaption[32]; Uint32 color = 0; if ( _fps >= 50 ) color = MAKERGB(0,255,0); // GREEN else if ( _fps < 50 && _fps >= 30 ) color = MAKERGB(255,255,0); // YELLOW else if ( _fps < 30 ) color = MAKERGB(255,0,0); // RED sprintf ( fpsCaption, "FPS: %d", _fps ); if ( !m_fpsWidget ) { m_fpsWidget = new TextUI( fpsCaption, color, 3, g_graphics->GetScreenHeight () - 40 ); m_widgetList.insert ( m_fpsWidget ); } m_fpsWidget->SetColor ( color ); m_fpsWidget->SetText ( fpsCaption ); } void Interface::RenderWidgets() { for ( size_t i = 0; i < m_widgetList.size(); i++ ) { Widget *widget = m_widgetList[i]; if ( widget->Expired() ) { m_widgetList.remove ( i ); delete widget; i--; continue; } widget->Update(); widget->Render(); } } void Interface::InitWidgets () { for ( size_t i = 0; i < m_widgetList.size(); i++ ) { m_widgetList[i]->Initialise(); } } Interface *g_interface; <|endoftext|>
<commit_before>// Scintilla source code edit control // Copyright 1998-2002 by Neil Hodgson <[email protected]> /* This is the Lexer for Gui4Cli, included in SciLexer.dll - by d. Keletsekis, 2/10/2003 To add to SciLexer.dll: 1. Add the values below to INCLUDE\Scintilla.iface 2. Run the include/HFacer.py script 3. Run the src/lexGen.py script val SCE_GC_DEFAULT=0 val SCE_GC_COMMENTLINE=1 val SCE_GC_COMMENTBLOCK=2 val SCE_GC_GLOBAL=3 val SCE_GC_EVENT=4 val SCE_GC_ATTRIBUTE=5 val SCE_GC_CONTROL=6 val SCE_GC_COMMAND=7 val SCE_GC_STRING=8 val SCE_GC_OPERATOR=9 */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #define debug Platform::DebugPrintf static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch =='\\'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.'); } inline bool isGCOperator(int ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '%' || ch == '[' || ch == ']' || ch == '<' || ch == '>' || ch == ',' || ch == ';' || ch == ':') return true; return false; } #define isSpace(x) ((x)==' ' || (x)=='\t') #define isNL(x) ((x)=='\n' || (x)=='\r') #define isSpaceOrNL(x) (isSpace(x) || isNL(x)) #define BUFFSIZE 500 #define isFoldPoint(x) ((styler.LevelAt(x) & SC_FOLDLEVELNUMBERMASK) == 1024) static void colorFirstWord(WordList *keywordlists[], Accessor &styler, StyleContext *sc, char *buff, int length, int) { int c = 0; while (sc->More() && isSpaceOrNL(sc->ch)) { sc->Forward(); } styler.ColourTo(sc->currentPos - 1, sc->state); if (!IsAWordChar(sc->ch)) // comment, marker, etc.. return; while (sc->More() && !isSpaceOrNL(sc->ch) && (c < length-1) && !isGCOperator(sc->ch)) { buff[c] = static_cast<char>(sc->ch); ++c; sc->Forward(); } buff[c] = '\0'; char *p = buff; while (*p) // capitalize.. { if (islower(*p)) *p = static_cast<char>(toupper(*p)); ++p; } WordList &kGlobal = *keywordlists[0]; // keyword lists set by the user WordList &kEvent = *keywordlists[1]; WordList &kAttribute = *keywordlists[2]; WordList &kControl = *keywordlists[3]; WordList &kCommand = *keywordlists[4]; int state = 0; // int level = styler.LevelAt(line) & SC_FOLDLEVELNUMBERMASK; // debug ("line = %d, level = %d", line, level); if (kGlobal.InList(buff)) state = SCE_GC_GLOBAL; else if (kAttribute.InList(buff)) state = SCE_GC_ATTRIBUTE; else if (kControl.InList(buff)) state = SCE_GC_CONTROL; else if (kCommand.InList(buff)) state = SCE_GC_COMMAND; else if (kEvent.InList(buff)) state = SCE_GC_EVENT; if (state) { sc->ChangeState(state); styler.ColourTo(sc->currentPos - 1, sc->state); sc->ChangeState(SCE_GC_DEFAULT); } else { sc->ChangeState(SCE_GC_DEFAULT); styler.ColourTo(sc->currentPos - 1, sc->state); } } // Main colorizing function called by Scintilla static void ColouriseGui4CliDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { styler.StartAt(startPos); int quotestart = 0, oldstate, currentline = styler.GetLine(startPos); styler.StartSegment(startPos); bool noforward; char buff[BUFFSIZE+1]; // buffer for command name StyleContext sc(startPos, length, initStyle, styler); buff[0] = '\0'; // cbuff = 0; if (sc.state != SCE_GC_COMMENTBLOCK) // colorize 1st word.. colorFirstWord(keywordlists, styler, &sc, buff, BUFFSIZE, currentline); while (sc.More()) { noforward = 0; switch (sc.ch) { case '/': if (sc.state == SCE_GC_COMMENTBLOCK || sc.state == SCE_GC_STRING) break; if (sc.chNext == '/') // line comment { sc.SetState (SCE_GC_COMMENTLINE); sc.Forward(); styler.ColourTo(sc.currentPos, sc.state); } else if (sc.chNext == '*') // block comment { sc.SetState(SCE_GC_COMMENTBLOCK); sc.Forward(); styler.ColourTo(sc.currentPos, sc.state); } else styler.ColourTo(sc.currentPos, sc.state); break; case '*': // end of comment block, or operator.. if (sc.state == SCE_GC_STRING) break; if (sc.state == SCE_GC_COMMENTBLOCK && sc.chNext == '/') { sc.Forward(); styler.ColourTo(sc.currentPos, sc.state); sc.ChangeState (SCE_GC_DEFAULT); } else styler.ColourTo(sc.currentPos, sc.state); break; case '\'': case '\"': // strings.. if (sc.state == SCE_GC_COMMENTBLOCK || sc.state == SCE_GC_COMMENTLINE) break; if (sc.state == SCE_GC_STRING) { if (sc.ch == quotestart) // match same quote char.. { styler.ColourTo(sc.currentPos, sc.state); sc.ChangeState(SCE_GC_DEFAULT); quotestart = 0; } } else { styler.ColourTo(sc.currentPos - 1, sc.state); sc.ChangeState(SCE_GC_STRING); quotestart = sc.ch; } break; case ';': // end of commandline character if (sc.state != SCE_GC_COMMENTBLOCK && sc.state != SCE_GC_COMMENTLINE && sc.state != SCE_GC_STRING) { styler.ColourTo(sc.currentPos - 1, sc.state); styler.ColourTo(sc.currentPos, SCE_GC_OPERATOR); sc.ChangeState(SCE_GC_DEFAULT); sc.Forward(); colorFirstWord(keywordlists, styler, &sc, buff, BUFFSIZE, currentline); noforward = 1; // don't move forward - already positioned at next char.. } break; case '+': case '-': case '=': case '!': // operators.. case '<': case '>': case '&': case '|': case '$': if (sc.state != SCE_GC_COMMENTBLOCK && sc.state != SCE_GC_COMMENTLINE && sc.state != SCE_GC_STRING) { styler.ColourTo(sc.currentPos - 1, sc.state); styler.ColourTo(sc.currentPos, SCE_GC_OPERATOR); sc.ChangeState(SCE_GC_DEFAULT); } break; case '\\': // escape - same as operator, but also mark in strings.. if (sc.state != SCE_GC_COMMENTBLOCK && sc.state != SCE_GC_COMMENTLINE) { oldstate = sc.state; styler.ColourTo(sc.currentPos - 1, sc.state); sc.Forward(); // mark also the next char.. styler.ColourTo(sc.currentPos, SCE_GC_OPERATOR); sc.ChangeState(oldstate); } break; case '\n': case '\r': ++currentline; if (sc.state == SCE_GC_COMMENTLINE) { styler.ColourTo(sc.currentPos, sc.state); sc.ChangeState (SCE_GC_DEFAULT); } else if (sc.state != SCE_GC_COMMENTBLOCK) { colorFirstWord(keywordlists, styler, &sc, buff, BUFFSIZE, currentline); noforward = 1; // don't move forward - already positioned at next char.. } break; // case ' ': case '\t': // default : } if (!noforward) sc.Forward(); } styler.ColourTo(sc.currentPos, sc.state); } // Main folding function called by Scintilla - (based on props (.ini) files function) static void FoldGui4Cli(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); bool headerPoint = false; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler[i+1]; int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_GC_EVENT || style == SCE_GC_GLOBAL) { headerPoint = true; // fold at events and globals } if (atEOL) { int lev = SC_FOLDLEVELBASE+1; if (headerPoint) lev = SC_FOLDLEVELBASE; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (headerPoint) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) // set level, if not already correct { styler.SetLevel(lineCurrent, lev); } lineCurrent++; // re-initialize our flags visibleChars = 0; headerPoint = false; } if (!(isspacechar(ch))) // || (style == SCE_GC_COMMENTLINE) || (style != SCE_GC_COMMENTBLOCK))) visibleChars++; } int lev = headerPoint ? SC_FOLDLEVELBASE : SC_FOLDLEVELBASE+1; int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, lev | flagsNext); } // I have no idea what these are for.. probably accessible by some message. static const char * const gui4cliWordListDesc[] = { "Globals", "Events", "Attributes", "Control", "Commands", 0 }; // Declare language & pass our function pointers to Scintilla LexerModule lmGui4Cli(SCLEX_GUI4CLI, ColouriseGui4CliDoc, "gui4cli", FoldGui4Cli, gui4cliWordListDesc); #undef debug <commit_msg>Changed final code in lexer to perform sc.Complete() and avoid asserting.<commit_after>// Scintilla source code edit control // Copyright 1998-2002 by Neil Hodgson <[email protected]> /* This is the Lexer for Gui4Cli, included in SciLexer.dll - by d. Keletsekis, 2/10/2003 To add to SciLexer.dll: 1. Add the values below to INCLUDE\Scintilla.iface 2. Run the include/HFacer.py script 3. Run the src/lexGen.py script val SCE_GC_DEFAULT=0 val SCE_GC_COMMENTLINE=1 val SCE_GC_COMMENTBLOCK=2 val SCE_GC_GLOBAL=3 val SCE_GC_EVENT=4 val SCE_GC_ATTRIBUTE=5 val SCE_GC_CONTROL=6 val SCE_GC_COMMAND=7 val SCE_GC_STRING=8 val SCE_GC_OPERATOR=9 */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #define debug Platform::DebugPrintf static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch =='\\'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.'); } inline bool isGCOperator(int ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '%' || ch == '[' || ch == ']' || ch == '<' || ch == '>' || ch == ',' || ch == ';' || ch == ':') return true; return false; } #define isSpace(x) ((x)==' ' || (x)=='\t') #define isNL(x) ((x)=='\n' || (x)=='\r') #define isSpaceOrNL(x) (isSpace(x) || isNL(x)) #define BUFFSIZE 500 #define isFoldPoint(x) ((styler.LevelAt(x) & SC_FOLDLEVELNUMBERMASK) == 1024) static void colorFirstWord(WordList *keywordlists[], Accessor &styler, StyleContext *sc, char *buff, int length, int) { int c = 0; while (sc->More() && isSpaceOrNL(sc->ch)) { sc->Forward(); } styler.ColourTo(sc->currentPos - 1, sc->state); if (!IsAWordChar(sc->ch)) // comment, marker, etc.. return; while (sc->More() && !isSpaceOrNL(sc->ch) && (c < length-1) && !isGCOperator(sc->ch)) { buff[c] = static_cast<char>(sc->ch); ++c; sc->Forward(); } buff[c] = '\0'; char *p = buff; while (*p) // capitalize.. { if (islower(*p)) *p = static_cast<char>(toupper(*p)); ++p; } WordList &kGlobal = *keywordlists[0]; // keyword lists set by the user WordList &kEvent = *keywordlists[1]; WordList &kAttribute = *keywordlists[2]; WordList &kControl = *keywordlists[3]; WordList &kCommand = *keywordlists[4]; int state = 0; // int level = styler.LevelAt(line) & SC_FOLDLEVELNUMBERMASK; // debug ("line = %d, level = %d", line, level); if (kGlobal.InList(buff)) state = SCE_GC_GLOBAL; else if (kAttribute.InList(buff)) state = SCE_GC_ATTRIBUTE; else if (kControl.InList(buff)) state = SCE_GC_CONTROL; else if (kCommand.InList(buff)) state = SCE_GC_COMMAND; else if (kEvent.InList(buff)) state = SCE_GC_EVENT; if (state) { sc->ChangeState(state); styler.ColourTo(sc->currentPos - 1, sc->state); sc->ChangeState(SCE_GC_DEFAULT); } else { sc->ChangeState(SCE_GC_DEFAULT); styler.ColourTo(sc->currentPos - 1, sc->state); } } // Main colorizing function called by Scintilla static void ColouriseGui4CliDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { styler.StartAt(startPos); int quotestart = 0, oldstate, currentline = styler.GetLine(startPos); styler.StartSegment(startPos); bool noforward; char buff[BUFFSIZE+1]; // buffer for command name StyleContext sc(startPos, length, initStyle, styler); buff[0] = '\0'; // cbuff = 0; if (sc.state != SCE_GC_COMMENTBLOCK) // colorize 1st word.. colorFirstWord(keywordlists, styler, &sc, buff, BUFFSIZE, currentline); while (sc.More()) { noforward = 0; switch (sc.ch) { case '/': if (sc.state == SCE_GC_COMMENTBLOCK || sc.state == SCE_GC_STRING) break; if (sc.chNext == '/') // line comment { sc.SetState (SCE_GC_COMMENTLINE); sc.Forward(); styler.ColourTo(sc.currentPos, sc.state); } else if (sc.chNext == '*') // block comment { sc.SetState(SCE_GC_COMMENTBLOCK); sc.Forward(); styler.ColourTo(sc.currentPos, sc.state); } else styler.ColourTo(sc.currentPos, sc.state); break; case '*': // end of comment block, or operator.. if (sc.state == SCE_GC_STRING) break; if (sc.state == SCE_GC_COMMENTBLOCK && sc.chNext == '/') { sc.Forward(); styler.ColourTo(sc.currentPos, sc.state); sc.ChangeState (SCE_GC_DEFAULT); } else styler.ColourTo(sc.currentPos, sc.state); break; case '\'': case '\"': // strings.. if (sc.state == SCE_GC_COMMENTBLOCK || sc.state == SCE_GC_COMMENTLINE) break; if (sc.state == SCE_GC_STRING) { if (sc.ch == quotestart) // match same quote char.. { styler.ColourTo(sc.currentPos, sc.state); sc.ChangeState(SCE_GC_DEFAULT); quotestart = 0; } } else { styler.ColourTo(sc.currentPos - 1, sc.state); sc.ChangeState(SCE_GC_STRING); quotestart = sc.ch; } break; case ';': // end of commandline character if (sc.state != SCE_GC_COMMENTBLOCK && sc.state != SCE_GC_COMMENTLINE && sc.state != SCE_GC_STRING) { styler.ColourTo(sc.currentPos - 1, sc.state); styler.ColourTo(sc.currentPos, SCE_GC_OPERATOR); sc.ChangeState(SCE_GC_DEFAULT); sc.Forward(); colorFirstWord(keywordlists, styler, &sc, buff, BUFFSIZE, currentline); noforward = 1; // don't move forward - already positioned at next char.. } break; case '+': case '-': case '=': case '!': // operators.. case '<': case '>': case '&': case '|': case '$': if (sc.state != SCE_GC_COMMENTBLOCK && sc.state != SCE_GC_COMMENTLINE && sc.state != SCE_GC_STRING) { styler.ColourTo(sc.currentPos - 1, sc.state); styler.ColourTo(sc.currentPos, SCE_GC_OPERATOR); sc.ChangeState(SCE_GC_DEFAULT); } break; case '\\': // escape - same as operator, but also mark in strings.. if (sc.state != SCE_GC_COMMENTBLOCK && sc.state != SCE_GC_COMMENTLINE) { oldstate = sc.state; styler.ColourTo(sc.currentPos - 1, sc.state); sc.Forward(); // mark also the next char.. styler.ColourTo(sc.currentPos, SCE_GC_OPERATOR); sc.ChangeState(oldstate); } break; case '\n': case '\r': ++currentline; if (sc.state == SCE_GC_COMMENTLINE) { styler.ColourTo(sc.currentPos, sc.state); sc.ChangeState (SCE_GC_DEFAULT); } else if (sc.state != SCE_GC_COMMENTBLOCK) { colorFirstWord(keywordlists, styler, &sc, buff, BUFFSIZE, currentline); noforward = 1; // don't move forward - already positioned at next char.. } break; // case ' ': case '\t': // default : } if (!noforward) sc.Forward(); } sc.Complete(); } // Main folding function called by Scintilla - (based on props (.ini) files function) static void FoldGui4Cli(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); bool headerPoint = false; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler[i+1]; int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_GC_EVENT || style == SCE_GC_GLOBAL) { headerPoint = true; // fold at events and globals } if (atEOL) { int lev = SC_FOLDLEVELBASE+1; if (headerPoint) lev = SC_FOLDLEVELBASE; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (headerPoint) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) // set level, if not already correct { styler.SetLevel(lineCurrent, lev); } lineCurrent++; // re-initialize our flags visibleChars = 0; headerPoint = false; } if (!(isspacechar(ch))) // || (style == SCE_GC_COMMENTLINE) || (style != SCE_GC_COMMENTBLOCK))) visibleChars++; } int lev = headerPoint ? SC_FOLDLEVELBASE : SC_FOLDLEVELBASE+1; int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, lev | flagsNext); } // I have no idea what these are for.. probably accessible by some message. static const char * const gui4cliWordListDesc[] = { "Globals", "Events", "Attributes", "Control", "Commands", 0 }; // Declare language & pass our function pointers to Scintilla LexerModule lmGui4Cli(SCLEX_GUI4CLI, ColouriseGui4CliDoc, "gui4cli", FoldGui4Cli, gui4cliWordListDesc); #undef debug <|endoftext|>
<commit_before>#include <nan.h> #include <iostream> #include <string> #include <sstream> #include <map> #include <stdlib.h> #include <stdio.h> #include <poppler/qt4/poppler-form.h> #include <poppler/qt4/poppler-qt4.h> #include <cairo/cairo.h> #include <cairo/cairo-pdf.h> #include <QtCore/QBuffer> #include <QtCore/QFile> #include <QtGui/QImage> #include "NodePoppler.h" // NOLINT(build/include) using namespace std; using v8::Number; using v8::String; using v8::Object; using v8::Local; using v8::Array; using v8::Value; using v8::Boolean; inline bool fileExists (const std::string& name) { if (FILE *file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } // Cairo write and read functions (to QBuffer) static cairo_status_t readPngFromBuffer(void *closure, unsigned char *data, unsigned int length) { QBuffer *myBuffer = (QBuffer *)closure; size_t bytes_read; bytes_read = myBuffer->read((char *)data, length); if (bytes_read != length) return CAIRO_STATUS_READ_ERROR; return CAIRO_STATUS_SUCCESS; } static cairo_status_t writePngToBuffer(void *closure, const unsigned char *data, unsigned int length) { QBuffer *myBuffer = (QBuffer *)closure; size_t bytes_wrote; bytes_wrote = myBuffer->write((char *)data, length); if (bytes_wrote != length) return CAIRO_STATUS_READ_ERROR; return CAIRO_STATUS_SUCCESS; } void createPdf(QBuffer *buffer, Poppler::Document *document) { ostringstream ss; Poppler::PDFConverter *converter = document->pdfConverter(); converter->setPDFOptions(converter->pdfOptions() | Poppler::PDFConverter::WithChanges); converter->setOutputDevice(buffer); if (!converter->convert()) { // enum Error // { // NoError, // FileLockedError, // OpenOutputError, // NotSupportedInputFileError // }; ss << "Error occurred when converting PDF: " << converter->lastError(); throw ss.str(); } } void createImgPdf(QBuffer *buffer, Poppler::Document *document) { // Initialize Cairo writing surface, and since we have images at 360 DPI, we'll set scaling. Width and Height are set for A4 dimensions. cairo_surface_t *surface = cairo_pdf_surface_create_for_stream(writePngToBuffer, buffer, 595.00, 842.00); cairo_t *cr = cairo_create(surface); cairo_scale(cr, 0.2, 0.2); int n = document->numPages(); for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); // Save the page as PNG image to buffer. (We could use QFile if we want to save images to files) QBuffer *pageImage = new QBuffer(); pageImage->open(QIODevice::ReadWrite); QImage img = page->renderToImage(360, 360); img.save(pageImage, "png"); pageImage->seek(0); // Reading does not work if we don't reset the pointer // Ookay, let's try to make new page out of the image cairo_surface_t *drawImageSurface = cairo_image_surface_create_from_png_stream(readPngFromBuffer, pageImage); cairo_set_source_surface(cr, drawImageSurface, 0, 0); cairo_paint(cr); // Create new page if multipage document if (n > 0) { cairo_surface_show_page(surface); cr = cairo_create(surface); cairo_scale(cr, 0.2, 0.2); } pageImage->close(); } // Close Cairo cairo_destroy(cr); cairo_surface_finish(surface); cairo_surface_destroy (surface); } WriteFieldsParams v8ParamsToCpp(const v8::FunctionCallbackInfo<Value>& args) { Local<Object> parameters; string saveFormat = "imgpdf"; map<string, string> fields; string sourcePdfFileName = *NanAsciiString(args[0]); Local<Object> changeFields = args[1]->ToObject(); // Check if any configuration parameters if (args.Length() > 2) { parameters = args[2]->ToObject(); Local<Value> saveParam = parameters->Get(NanNew<String>("save")); if (!saveParam->IsUndefined()) { saveFormat = *NanAsciiString(parameters->Get(NanNew<String>("save"))); } } // Convert form fields to c++ map Local<Array> fieldArray = changeFields->GetPropertyNames(); for (uint32_t i = 0; i < fieldArray->Length(); i += 1) { Local<Value> name = fieldArray->Get(i); Local<Value> value = changeFields->Get(name); fields[std::string(*v8::String::Utf8Value(name))] = std::string(*v8::String::Utf8Value(value)); } // Create and return PDF struct WriteFieldsParams params(sourcePdfFileName, saveFormat, fields); return params; } // Pdf creator that is not dependent on V8 internals (safe at async?) QBuffer *writePdfFields(struct WriteFieldsParams params) { ostringstream ss; // If source file does not exist, throw error and return false if (!fileExists(params.sourcePdfFileName)) { ss << "File \"" << params.sourcePdfFileName << "\" does not exist"; throw ss.str(); } // Open document and return false and throw error if something goes wrong Poppler::Document *document = Poppler::Document::load(QString::fromStdString(params.sourcePdfFileName)); if (document == NULL) { ss << "Error occurred when reading \"" << params.sourcePdfFileName << "\""; throw ss.str(); } // Fill form int n = document->numPages(); stringstream idSS; for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); foreach (Poppler::FormField *field, page->formFields()) { string fieldName = field->fullyQualifiedName().toStdString(); // Support writing fields by both fieldName and id. // If fieldName is not present in params, try id. if (params.fields.count(fieldName) == 0) { idSS << field->id(); fieldName = idSS.str(); idSS.str(""); idSS.clear(); } if (!field->isReadOnly() && field->isVisible() && params.fields.count(fieldName) ) { // Text if (field->type() == Poppler::FormField::FormText) { Poppler::FormFieldText *textField = (Poppler::FormFieldText *) field; textField->setText(QString::fromUtf8(params.fields[fieldName].c_str())); } // Choice if (field->type() == Poppler::FormField::FormChoice) { Poppler::FormFieldChoice *choiceField = (Poppler::FormFieldChoice *) field; if (choiceField->isEditable()) { choiceField->setEditChoice(QString::fromUtf8(params.fields[fieldName].c_str())); } else { QStringList possibleChoices = choiceField->choices(); QString proposedChoice = QString::fromUtf8(params.fields[fieldName].c_str()); int index = possibleChoices.indexOf(proposedChoice); if (index >= 0) { QList<int> choiceList; choiceList << index; choiceField->setCurrentChoices(choiceList); } } } // Button // ! TODO ! Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue). if (field->type() == Poppler::FormField::FormButton) { Poppler::FormFieldButton *buttonField = (Poppler::FormFieldButton *) field; if (params.fields[fieldName].compare("true") == 0) { buttonField->setState(true); } else { buttonField->setState(false); } } } } } // Now save and return the document QBuffer *bufferDevice = new QBuffer(); bufferDevice->open(QIODevice::ReadWrite); // Get save parameters if (params.saveFormat == "imgpdf") { createImgPdf(bufferDevice, document); } else { createPdf(bufferDevice, document); } return bufferDevice; } //*********************************** // // Node.js methods // //*********************************** // Read PDF form fields NAN_METHOD(ReadSync) { NanScope(); // expect a number as the first argument NanUtf8String *fileName = new NanUtf8String(args[0]); ostringstream ss; int n = 0; // If file does not exist, throw error and return false if (!fileExists(**fileName)) { ss << "File \"" << **fileName << "\" does not exist"; NanThrowError(NanNew<String>(ss.str())); NanReturnValue(NanFalse()); } // Open document and return false and throw error if something goes wrong Poppler::Document *document = Poppler::Document::load(**fileName); if (document != NULL) { // Get field list n = document->numPages(); } else { ss << "Error occurred when reading \"" << **fileName << "\""; NanThrowError(NanNew<String>(ss.str())); NanReturnValue(NanFalse()); } // Store field value objects to v8 array Local<Array> fieldArray = NanNew<Array>(); int fieldNum = 0; for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); foreach (Poppler::FormField *field, page->formFields()) { if (!field->isReadOnly() && field->isVisible()) { // Make JavaScript object out of the fieldnames Local<Object> obj = NanNew<Object>(); obj->Set(NanNew<String>("name"), NanNew<String>(field->fullyQualifiedName().toStdString())); obj->Set(NanNew<String>("page"), NanNew<Number>(i)); // ! TODO ! Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue). string fieldType; // Set default value undefined obj->Set(NanNew<String>("value"), NanUndefined()); Poppler::FormFieldButton *myButton; Poppler::FormFieldChoice *myChoice; obj->Set(NanNew<String>("id"), NanNew<Number>(field->id())); switch (field->type()) { // FormButton case Poppler::FormField::FormButton: myButton = (Poppler::FormFieldButton *)field; switch (myButton->buttonType()) { // Push case Poppler::FormFieldButton::Push: fieldType = "push_button"; break; case Poppler::FormFieldButton::CheckBox: fieldType = "checkbox"; obj->Set(NanNew<String>("value"), NanNew<Boolean>(myButton->state())); break; case Poppler::FormFieldButton::Radio: fieldType = "radio"; break; } break; // FormText case Poppler::FormField::FormText: obj->Set(NanNew<String>("value"), NanNew<String>(((Poppler::FormFieldText *)field)->text().toStdString())); fieldType = "text"; break; // FormChoice case Poppler::FormField::FormChoice: { Local<Array> choiceArray = NanNew<Array>(); myChoice = (Poppler::FormFieldChoice *)field; QStringList possibleChoices = myChoice->choices(); for (int i = 0; i < possibleChoices.size(); i++) { choiceArray->Set(i, NanNew<String>(possibleChoices.at(i).toStdString())); } obj->Set(NanNew<String>("choices"), choiceArray); switch (myChoice->choiceType()) { case Poppler::FormFieldChoice::ComboBox: fieldType = "combobox"; break; case Poppler::FormFieldChoice::ListBox: fieldType = "listbox"; break; } break; } // FormSignature case Poppler::FormField::FormSignature: fieldType = "formsignature"; break; default: fieldType = "undefined"; break; } obj->Set(NanNew<String>("type"), NanNew<String>(fieldType.c_str())); fieldArray->Set(fieldNum, obj); fieldNum++; } } } NanReturnValue(fieldArray); } // Write PDF form fields NAN_METHOD(WriteSync) { NanScope(); // Check and return parameters given at JavaScript function call WriteFieldsParams params = v8ParamsToCpp(args); // Create and return pdf try { QBuffer *buffer = writePdfFields(params); Local<Object> returnPdf = NanNewBufferHandle(buffer->data().data(), buffer->size()); buffer->close(); delete buffer; NanReturnValue(returnPdf); } catch (string error) { NanThrowError(NanNew<String>(error)); NanReturnValue(NanNull()); } } <commit_msg>Convert field names to Utf8.<commit_after>#include <nan.h> #include <iostream> #include <string> #include <sstream> #include <map> #include <stdlib.h> #include <stdio.h> #include <poppler/qt4/poppler-form.h> #include <poppler/qt4/poppler-qt4.h> #include <cairo/cairo.h> #include <cairo/cairo-pdf.h> #include <QtCore/QBuffer> #include <QtCore/QFile> #include <QtGui/QImage> #include "NodePoppler.h" // NOLINT(build/include) using namespace std; using v8::Number; using v8::String; using v8::Object; using v8::Local; using v8::Array; using v8::Value; using v8::Boolean; inline bool fileExists (const std::string& name) { if (FILE *file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } // Cairo write and read functions (to QBuffer) static cairo_status_t readPngFromBuffer(void *closure, unsigned char *data, unsigned int length) { QBuffer *myBuffer = (QBuffer *)closure; size_t bytes_read; bytes_read = myBuffer->read((char *)data, length); if (bytes_read != length) return CAIRO_STATUS_READ_ERROR; return CAIRO_STATUS_SUCCESS; } static cairo_status_t writePngToBuffer(void *closure, const unsigned char *data, unsigned int length) { QBuffer *myBuffer = (QBuffer *)closure; size_t bytes_wrote; bytes_wrote = myBuffer->write((char *)data, length); if (bytes_wrote != length) return CAIRO_STATUS_READ_ERROR; return CAIRO_STATUS_SUCCESS; } void createPdf(QBuffer *buffer, Poppler::Document *document) { ostringstream ss; Poppler::PDFConverter *converter = document->pdfConverter(); converter->setPDFOptions(converter->pdfOptions() | Poppler::PDFConverter::WithChanges); converter->setOutputDevice(buffer); if (!converter->convert()) { // enum Error // { // NoError, // FileLockedError, // OpenOutputError, // NotSupportedInputFileError // }; ss << "Error occurred when converting PDF: " << converter->lastError(); throw ss.str(); } } void createImgPdf(QBuffer *buffer, Poppler::Document *document) { // Initialize Cairo writing surface, and since we have images at 360 DPI, we'll set scaling. Width and Height are set for A4 dimensions. cairo_surface_t *surface = cairo_pdf_surface_create_for_stream(writePngToBuffer, buffer, 595.00, 842.00); cairo_t *cr = cairo_create(surface); cairo_scale(cr, 0.2, 0.2); int n = document->numPages(); for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); // Save the page as PNG image to buffer. (We could use QFile if we want to save images to files) QBuffer *pageImage = new QBuffer(); pageImage->open(QIODevice::ReadWrite); QImage img = page->renderToImage(360, 360); img.save(pageImage, "png"); pageImage->seek(0); // Reading does not work if we don't reset the pointer // Ookay, let's try to make new page out of the image cairo_surface_t *drawImageSurface = cairo_image_surface_create_from_png_stream(readPngFromBuffer, pageImage); cairo_set_source_surface(cr, drawImageSurface, 0, 0); cairo_paint(cr); // Create new page if multipage document if (n > 0) { cairo_surface_show_page(surface); cr = cairo_create(surface); cairo_scale(cr, 0.2, 0.2); } pageImage->close(); } // Close Cairo cairo_destroy(cr); cairo_surface_finish(surface); cairo_surface_destroy (surface); } WriteFieldsParams v8ParamsToCpp(const v8::FunctionCallbackInfo<Value>& args) { Local<Object> parameters; string saveFormat = "imgpdf"; map<string, string> fields; string sourcePdfFileName = *NanAsciiString(args[0]); Local<Object> changeFields = args[1]->ToObject(); // Check if any configuration parameters if (args.Length() > 2) { parameters = args[2]->ToObject(); Local<Value> saveParam = parameters->Get(NanNew<String>("save")); if (!saveParam->IsUndefined()) { saveFormat = *NanAsciiString(parameters->Get(NanNew<String>("save"))); } } // Convert form fields to c++ map Local<Array> fieldArray = changeFields->GetPropertyNames(); for (uint32_t i = 0; i < fieldArray->Length(); i += 1) { Local<Value> name = fieldArray->Get(i); Local<Value> value = changeFields->Get(name); fields[std::string(*v8::String::Utf8Value(name))] = std::string(*v8::String::Utf8Value(value)); } // Create and return PDF struct WriteFieldsParams params(sourcePdfFileName, saveFormat, fields); return params; } // Pdf creator that is not dependent on V8 internals (safe at async?) QBuffer *writePdfFields(struct WriteFieldsParams params) { ostringstream ss; // If source file does not exist, throw error and return false if (!fileExists(params.sourcePdfFileName)) { ss << "File \"" << params.sourcePdfFileName << "\" does not exist"; throw ss.str(); } // Open document and return false and throw error if something goes wrong Poppler::Document *document = Poppler::Document::load(QString::fromStdString(params.sourcePdfFileName)); if (document == NULL) { ss << "Error occurred when reading \"" << params.sourcePdfFileName << "\""; throw ss.str(); } // Fill form int n = document->numPages(); stringstream idSS; for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); foreach (Poppler::FormField *field, page->formFields()) { string fieldName = field->fullyQualifiedName().toStdString(); // Support writing fields by both fieldName and id. // If fieldName is not present in params, try id. if (params.fields.count(fieldName) == 0) { idSS << field->id(); fieldName = idSS.str(); idSS.str(""); idSS.clear(); } if (!field->isReadOnly() && field->isVisible() && params.fields.count(fieldName) ) { // Text if (field->type() == Poppler::FormField::FormText) { Poppler::FormFieldText *textField = (Poppler::FormFieldText *) field; textField->setText(QString::fromUtf8(params.fields[fieldName].c_str())); } // Choice if (field->type() == Poppler::FormField::FormChoice) { Poppler::FormFieldChoice *choiceField = (Poppler::FormFieldChoice *) field; if (choiceField->isEditable()) { choiceField->setEditChoice(QString::fromUtf8(params.fields[fieldName].c_str())); } else { QStringList possibleChoices = choiceField->choices(); QString proposedChoice = QString::fromUtf8(params.fields[fieldName].c_str()); int index = possibleChoices.indexOf(proposedChoice); if (index >= 0) { QList<int> choiceList; choiceList << index; choiceField->setCurrentChoices(choiceList); } } } // Button // ! TODO ! Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue). if (field->type() == Poppler::FormField::FormButton) { Poppler::FormFieldButton *buttonField = (Poppler::FormFieldButton *) field; if (params.fields[fieldName].compare("true") == 0) { buttonField->setState(true); } else { buttonField->setState(false); } } } } } // Now save and return the document QBuffer *bufferDevice = new QBuffer(); bufferDevice->open(QIODevice::ReadWrite); // Get save parameters if (params.saveFormat == "imgpdf") { createImgPdf(bufferDevice, document); } else { createPdf(bufferDevice, document); } return bufferDevice; } //*********************************** // // Node.js methods // //*********************************** // Read PDF form fields NAN_METHOD(ReadSync) { NanScope(); // expect a number as the first argument NanUtf8String *fileName = new NanUtf8String(args[0]); ostringstream ss; int n = 0; // If file does not exist, throw error and return false if (!fileExists(**fileName)) { ss << "File \"" << **fileName << "\" does not exist"; NanThrowError(NanNew<String>(ss.str())); NanReturnValue(NanFalse()); } // Open document and return false and throw error if something goes wrong Poppler::Document *document = Poppler::Document::load(**fileName); if (document != NULL) { // Get field list n = document->numPages(); } else { ss << "Error occurred when reading \"" << **fileName << "\""; NanThrowError(NanNew<String>(ss.str())); NanReturnValue(NanFalse()); } // Store field value objects to v8 array Local<Array> fieldArray = NanNew<Array>(); int fieldNum = 0; for (int i = 0; i < n; i += 1) { Poppler::Page *page = document->page(i); foreach (Poppler::FormField *field, page->formFields()) { if (!field->isReadOnly() && field->isVisible()) { //QString::fromUtf8(field->fullyQualifiedName().toLatin1()).toStdString() // Make JavaScript object out of the fieldnames Local<Object> obj = NanNew<Object>(); obj->Set(NanNew<String>("name"), NanNew<String>(QString(field->fullyQualifiedName().toUtf8()).toStdString())); obj->Set(NanNew<String>("page"), NanNew<Number>(i)); // ! TODO ! Note. Poppler doesn't support checkboxes with hashtag names (aka using exportValue). string fieldType; // Set default value undefined obj->Set(NanNew<String>("value"), NanUndefined()); Poppler::FormFieldButton *myButton; Poppler::FormFieldChoice *myChoice; obj->Set(NanNew<String>("id"), NanNew<Number>(field->id())); switch (field->type()) { // FormButton case Poppler::FormField::FormButton: myButton = (Poppler::FormFieldButton *)field; switch (myButton->buttonType()) { // Push case Poppler::FormFieldButton::Push: fieldType = "push_button"; break; case Poppler::FormFieldButton::CheckBox: fieldType = "checkbox"; obj->Set(NanNew<String>("value"), NanNew<Boolean>(myButton->state())); break; case Poppler::FormFieldButton::Radio: fieldType = "radio"; break; } break; // FormText case Poppler::FormField::FormText: obj->Set(NanNew<String>("value"), NanNew<String>(((Poppler::FormFieldText *)field)->text().toStdString())); fieldType = "text"; break; // FormChoice case Poppler::FormField::FormChoice: { Local<Array> choiceArray = NanNew<Array>(); myChoice = (Poppler::FormFieldChoice *)field; QStringList possibleChoices = myChoice->choices(); for (int i = 0; i < possibleChoices.size(); i++) { choiceArray->Set(i, NanNew<String>(possibleChoices.at(i).toStdString())); } obj->Set(NanNew<String>("choices"), choiceArray); switch (myChoice->choiceType()) { case Poppler::FormFieldChoice::ComboBox: fieldType = "combobox"; break; case Poppler::FormFieldChoice::ListBox: fieldType = "listbox"; break; } break; } // FormSignature case Poppler::FormField::FormSignature: fieldType = "formsignature"; break; default: fieldType = "undefined"; break; } obj->Set(NanNew<String>("type"), NanNew<String>(fieldType.c_str())); fieldArray->Set(fieldNum, obj); fieldNum++; } } } NanReturnValue(fieldArray); } // Write PDF form fields NAN_METHOD(WriteSync) { NanScope(); // Check and return parameters given at JavaScript function call WriteFieldsParams params = v8ParamsToCpp(args); // Create and return pdf try { QBuffer *buffer = writePdfFields(params); Local<Object> returnPdf = NanNewBufferHandle(buffer->data().data(), buffer->size()); buffer->close(); delete buffer; NanReturnValue(returnPdf); } catch (string error) { NanThrowError(NanNew<String>(error)); NanReturnValue(NanNull()); } } <|endoftext|>
<commit_before>//===-- tsan_rtl_mutex.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 part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "tsan_rtl.h" #include "tsan_flags.h" #include "tsan_sync.h" #include "tsan_report.h" #include "tsan_symbolize.h" #include "tsan_platform.h" namespace __tsan { void MutexCreate(ThreadState *thr, uptr pc, uptr addr, bool rw, bool recursive, bool linker_init) { Context *ctx = CTX(); CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexCreate %zx\n", thr->tid, addr); StatInc(thr, StatMutexCreate); if (!linker_init && IsAppMem(addr)) { CHECK(!thr->is_freeing); thr->is_freeing = true; MemoryWrite(thr, pc, addr, kSizeLog1); thr->is_freeing = false; } SyncVar *s = ctx->synctab.GetOrCreateAndLock(thr, pc, addr, true); s->is_rw = rw; s->is_recursive = recursive; s->is_linker_init = linker_init; s->mtx.Unlock(); } void MutexDestroy(ThreadState *thr, uptr pc, uptr addr) { Context *ctx = CTX(); CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexDestroy %zx\n", thr->tid, addr); StatInc(thr, StatMutexDestroy); #ifndef TSAN_GO // Global mutexes not marked as LINKER_INITIALIZED // cause tons of not interesting reports, so just ignore it. if (IsGlobalVar(addr)) return; #endif SyncVar *s = ctx->synctab.GetAndRemove(thr, pc, addr); if (s == 0) return; if (IsAppMem(addr)) { CHECK(!thr->is_freeing); thr->is_freeing = true; MemoryWrite(thr, pc, addr, kSizeLog1); thr->is_freeing = false; } if (flags()->report_destroy_locked && s->owner_tid != SyncVar::kInvalidTid && !s->is_broken) { s->is_broken = true; ThreadRegistryLock l(ctx->thread_registry); ScopedReport rep(ReportTypeMutexDestroyLocked); rep.AddMutex(s); StackTrace trace; trace.ObtainCurrent(thr, pc); rep.AddStack(&trace); FastState last(s->last_lock); RestoreStack(last.tid(), last.epoch(), &trace, 0); rep.AddStack(&trace); rep.AddLocation(s->addr, 1); OutputReport(ctx, rep); } thr->mset.Remove(s->GetId()); DestroyAndFree(s); } void MutexLock(ThreadState *thr, uptr pc, uptr addr, int rec) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexLock %zx rec=%d\n", thr->tid, addr, rec); CHECK_GT(rec, 0); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeLock, s->GetId()); if (s->owner_tid == SyncVar::kInvalidTid) { CHECK_EQ(s->recursion, 0); s->owner_tid = thr->tid; s->last_lock = thr->fast_state.raw(); } else if (s->owner_tid == thr->tid) { CHECK_GT(s->recursion, 0); } else { Printf("ThreadSanitizer WARNING: double lock of mutex %p\n", addr); PrintCurrentStack(thr, pc); } if (s->recursion == 0) { StatInc(thr, StatMutexLock); AcquireImpl(thr, pc, &s->clock); AcquireImpl(thr, pc, &s->read_clock); } else if (!s->is_recursive) { StatInc(thr, StatMutexRecLock); } s->recursion += rec; thr->mset.Add(s->GetId(), true, thr->fast_state.epoch()); s->mtx.Unlock(); } int MutexUnlock(ThreadState *thr, uptr pc, uptr addr, bool all) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexUnlock %zx all=%d\n", thr->tid, addr, all); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeUnlock, s->GetId()); int rec = 0; if (s->recursion == 0) { if (!s->is_broken) { s->is_broken = true; Printf("ThreadSanitizer WARNING: unlock of unlocked mutex %p\n", addr); PrintCurrentStack(thr, pc); } } else if (s->owner_tid != thr->tid) { if (!s->is_broken) { s->is_broken = true; Printf("ThreadSanitizer WARNING: mutex %p is unlocked by wrong thread\n", addr); PrintCurrentStack(thr, pc); } } else { rec = all ? s->recursion : 1; s->recursion -= rec; if (s->recursion == 0) { StatInc(thr, StatMutexUnlock); s->owner_tid = SyncVar::kInvalidTid; if (thr->ignore_sync == 0) { thr->clock.set(thr->tid, thr->fast_state.epoch()); thr->fast_synch_epoch = thr->fast_state.epoch(); thr->clock.ReleaseStore(&s->clock); StatInc(thr, StatSyncRelease); } } else { StatInc(thr, StatMutexRecUnlock); } } thr->mset.Del(s->GetId(), true); s->mtx.Unlock(); return rec; } void MutexReadLock(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexReadLock %zx\n", thr->tid, addr); StatInc(thr, StatMutexReadLock); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, false); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeRLock, s->GetId()); if (s->owner_tid != SyncVar::kInvalidTid) { Printf("ThreadSanitizer WARNING: read lock of a write locked mutex %p\n", addr); PrintCurrentStack(thr, pc); } AcquireImpl(thr, pc, &s->clock); s->last_lock = thr->fast_state.raw(); thr->mset.Add(s->GetId(), false, thr->fast_state.epoch()); s->mtx.ReadUnlock(); } void MutexReadUnlock(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexReadUnlock %zx\n", thr->tid, addr); StatInc(thr, StatMutexReadUnlock); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeRUnlock, s->GetId()); if (s->owner_tid != SyncVar::kInvalidTid) { Printf("ThreadSanitizer WARNING: read unlock of a write locked mutex %p\n", addr); PrintCurrentStack(thr, pc); } ReleaseImpl(thr, pc, &s->read_clock); s->mtx.Unlock(); thr->mset.Del(s->GetId(), false); } void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexReadOrWriteUnlock %zx\n", thr->tid, addr); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); bool write = true; if (s->owner_tid == SyncVar::kInvalidTid) { // Seems to be read unlock. write = false; StatInc(thr, StatMutexReadUnlock); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeRUnlock, s->GetId()); ReleaseImpl(thr, pc, &s->read_clock); } else if (s->owner_tid == thr->tid) { // Seems to be write unlock. thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeUnlock, s->GetId()); CHECK_GT(s->recursion, 0); s->recursion--; if (s->recursion == 0) { StatInc(thr, StatMutexUnlock); s->owner_tid = SyncVar::kInvalidTid; ReleaseImpl(thr, pc, &s->clock); } else { StatInc(thr, StatMutexRecUnlock); } } else if (!s->is_broken) { s->is_broken = true; Printf("ThreadSanitizer WARNING: mutex %p is unlock by wrong thread\n", addr); PrintCurrentStack(thr, pc); } thr->mset.Del(s->GetId(), write); s->mtx.Unlock(); } void Acquire(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: Acquire %zx\n", thr->tid, addr); if (thr->ignore_sync) return; SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, false); AcquireImpl(thr, pc, &s->clock); s->mtx.ReadUnlock(); } static void UpdateClockCallback(ThreadContextBase *tctx_base, void *arg) { ThreadState *thr = reinterpret_cast<ThreadState*>(arg); ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base); if (tctx->status == ThreadStatusRunning) thr->clock.set(tctx->tid, tctx->thr->fast_state.epoch()); else thr->clock.set(tctx->tid, tctx->epoch1); } void AcquireGlobal(ThreadState *thr, uptr pc) { DPrintf("#%d: AcquireGlobal\n", thr->tid); if (thr->ignore_sync) return; ThreadRegistryLock l(CTX()->thread_registry); CTX()->thread_registry->RunCallbackForEachThreadLocked( UpdateClockCallback, thr); } void Release(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: Release %zx\n", thr->tid, addr); if (thr->ignore_sync) return; SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); // Can't increment epoch w/o writing to the trace as well. TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0); ReleaseImpl(thr, pc, &s->clock); s->mtx.Unlock(); } void ReleaseStore(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: ReleaseStore %zx\n", thr->tid, addr); if (thr->ignore_sync) return; SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); // Can't increment epoch w/o writing to the trace as well. TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0); ReleaseStoreImpl(thr, pc, &s->clock); s->mtx.Unlock(); } #ifndef TSAN_GO static void UpdateSleepClockCallback(ThreadContextBase *tctx_base, void *arg) { ThreadState *thr = reinterpret_cast<ThreadState*>(arg); ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base); if (tctx->status == ThreadStatusRunning) thr->last_sleep_clock.set(tctx->tid, tctx->thr->fast_state.epoch()); else thr->last_sleep_clock.set(tctx->tid, tctx->epoch1); } void AfterSleep(ThreadState *thr, uptr pc) { DPrintf("#%d: AfterSleep %zx\n", thr->tid); if (thr->ignore_sync) return; thr->last_sleep_stack_id = CurrentStackId(thr, pc); ThreadRegistryLock l(CTX()->thread_registry); CTX()->thread_registry->RunCallbackForEachThreadLocked( UpdateSleepClockCallback, thr); } #endif void AcquireImpl(ThreadState *thr, uptr pc, SyncClock *c) { if (thr->ignore_sync) return; thr->clock.set(thr->tid, thr->fast_state.epoch()); thr->clock.acquire(c); StatInc(thr, StatSyncAcquire); } void ReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c) { if (thr->ignore_sync) return; thr->clock.set(thr->tid, thr->fast_state.epoch()); thr->fast_synch_epoch = thr->fast_state.epoch(); thr->clock.release(c); StatInc(thr, StatSyncRelease); } void ReleaseStoreImpl(ThreadState *thr, uptr pc, SyncClock *c) { if (thr->ignore_sync) return; thr->clock.set(thr->tid, thr->fast_state.epoch()); thr->fast_synch_epoch = thr->fast_state.epoch(); thr->clock.ReleaseStore(c); StatInc(thr, StatSyncRelease); } void AcquireReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c) { if (thr->ignore_sync) return; thr->clock.set(thr->tid, thr->fast_state.epoch()); thr->fast_synch_epoch = thr->fast_state.epoch(); thr->clock.acq_rel(c); StatInc(thr, StatSyncAcquire); StatInc(thr, StatSyncRelease); } } // namespace __tsan <commit_msg>tsan: minor refactoring<commit_after>//===-- tsan_rtl_mutex.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 part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "tsan_rtl.h" #include "tsan_flags.h" #include "tsan_sync.h" #include "tsan_report.h" #include "tsan_symbolize.h" #include "tsan_platform.h" namespace __tsan { void MutexCreate(ThreadState *thr, uptr pc, uptr addr, bool rw, bool recursive, bool linker_init) { Context *ctx = CTX(); CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexCreate %zx\n", thr->tid, addr); StatInc(thr, StatMutexCreate); if (!linker_init && IsAppMem(addr)) { CHECK(!thr->is_freeing); thr->is_freeing = true; MemoryWrite(thr, pc, addr, kSizeLog1); thr->is_freeing = false; } SyncVar *s = ctx->synctab.GetOrCreateAndLock(thr, pc, addr, true); s->is_rw = rw; s->is_recursive = recursive; s->is_linker_init = linker_init; s->mtx.Unlock(); } void MutexDestroy(ThreadState *thr, uptr pc, uptr addr) { Context *ctx = CTX(); CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexDestroy %zx\n", thr->tid, addr); StatInc(thr, StatMutexDestroy); #ifndef TSAN_GO // Global mutexes not marked as LINKER_INITIALIZED // cause tons of not interesting reports, so just ignore it. if (IsGlobalVar(addr)) return; #endif SyncVar *s = ctx->synctab.GetAndRemove(thr, pc, addr); if (s == 0) return; if (IsAppMem(addr)) { CHECK(!thr->is_freeing); thr->is_freeing = true; MemoryWrite(thr, pc, addr, kSizeLog1); thr->is_freeing = false; } if (flags()->report_destroy_locked && s->owner_tid != SyncVar::kInvalidTid && !s->is_broken) { s->is_broken = true; ThreadRegistryLock l(ctx->thread_registry); ScopedReport rep(ReportTypeMutexDestroyLocked); rep.AddMutex(s); StackTrace trace; trace.ObtainCurrent(thr, pc); rep.AddStack(&trace); FastState last(s->last_lock); RestoreStack(last.tid(), last.epoch(), &trace, 0); rep.AddStack(&trace); rep.AddLocation(s->addr, 1); OutputReport(ctx, rep); } thr->mset.Remove(s->GetId()); DestroyAndFree(s); } void MutexLock(ThreadState *thr, uptr pc, uptr addr, int rec) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexLock %zx rec=%d\n", thr->tid, addr, rec); CHECK_GT(rec, 0); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeLock, s->GetId()); if (s->owner_tid == SyncVar::kInvalidTid) { CHECK_EQ(s->recursion, 0); s->owner_tid = thr->tid; s->last_lock = thr->fast_state.raw(); } else if (s->owner_tid == thr->tid) { CHECK_GT(s->recursion, 0); } else { Printf("ThreadSanitizer WARNING: double lock of mutex %p\n", addr); PrintCurrentStack(thr, pc); } if (s->recursion == 0) { StatInc(thr, StatMutexLock); AcquireImpl(thr, pc, &s->clock); AcquireImpl(thr, pc, &s->read_clock); } else if (!s->is_recursive) { StatInc(thr, StatMutexRecLock); } s->recursion += rec; thr->mset.Add(s->GetId(), true, thr->fast_state.epoch()); s->mtx.Unlock(); } int MutexUnlock(ThreadState *thr, uptr pc, uptr addr, bool all) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexUnlock %zx all=%d\n", thr->tid, addr, all); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeUnlock, s->GetId()); int rec = 0; if (s->recursion == 0) { if (!s->is_broken) { s->is_broken = true; Printf("ThreadSanitizer WARNING: unlock of unlocked mutex %p\n", addr); PrintCurrentStack(thr, pc); } } else if (s->owner_tid != thr->tid) { if (!s->is_broken) { s->is_broken = true; Printf("ThreadSanitizer WARNING: mutex %p is unlocked by wrong thread\n", addr); PrintCurrentStack(thr, pc); } } else { rec = all ? s->recursion : 1; s->recursion -= rec; if (s->recursion == 0) { StatInc(thr, StatMutexUnlock); s->owner_tid = SyncVar::kInvalidTid; ReleaseStoreImpl(thr, pc, &s->clock); } else { StatInc(thr, StatMutexRecUnlock); } } thr->mset.Del(s->GetId(), true); s->mtx.Unlock(); return rec; } void MutexReadLock(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexReadLock %zx\n", thr->tid, addr); StatInc(thr, StatMutexReadLock); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, false); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeRLock, s->GetId()); if (s->owner_tid != SyncVar::kInvalidTid) { Printf("ThreadSanitizer WARNING: read lock of a write locked mutex %p\n", addr); PrintCurrentStack(thr, pc); } AcquireImpl(thr, pc, &s->clock); s->last_lock = thr->fast_state.raw(); thr->mset.Add(s->GetId(), false, thr->fast_state.epoch()); s->mtx.ReadUnlock(); } void MutexReadUnlock(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexReadUnlock %zx\n", thr->tid, addr); StatInc(thr, StatMutexReadUnlock); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeRUnlock, s->GetId()); if (s->owner_tid != SyncVar::kInvalidTid) { Printf("ThreadSanitizer WARNING: read unlock of a write locked mutex %p\n", addr); PrintCurrentStack(thr, pc); } ReleaseImpl(thr, pc, &s->read_clock); s->mtx.Unlock(); thr->mset.Del(s->GetId(), false); } void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: MutexReadOrWriteUnlock %zx\n", thr->tid, addr); if (IsAppMem(addr)) MemoryReadAtomic(thr, pc, addr, kSizeLog1); SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); bool write = true; if (s->owner_tid == SyncVar::kInvalidTid) { // Seems to be read unlock. write = false; StatInc(thr, StatMutexReadUnlock); thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeRUnlock, s->GetId()); ReleaseImpl(thr, pc, &s->read_clock); } else if (s->owner_tid == thr->tid) { // Seems to be write unlock. thr->fast_state.IncrementEpoch(); TraceAddEvent(thr, thr->fast_state, EventTypeUnlock, s->GetId()); CHECK_GT(s->recursion, 0); s->recursion--; if (s->recursion == 0) { StatInc(thr, StatMutexUnlock); s->owner_tid = SyncVar::kInvalidTid; ReleaseImpl(thr, pc, &s->clock); } else { StatInc(thr, StatMutexRecUnlock); } } else if (!s->is_broken) { s->is_broken = true; Printf("ThreadSanitizer WARNING: mutex %p is unlock by wrong thread\n", addr); PrintCurrentStack(thr, pc); } thr->mset.Del(s->GetId(), write); s->mtx.Unlock(); } void Acquire(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: Acquire %zx\n", thr->tid, addr); if (thr->ignore_sync) return; SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, false); AcquireImpl(thr, pc, &s->clock); s->mtx.ReadUnlock(); } static void UpdateClockCallback(ThreadContextBase *tctx_base, void *arg) { ThreadState *thr = reinterpret_cast<ThreadState*>(arg); ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base); if (tctx->status == ThreadStatusRunning) thr->clock.set(tctx->tid, tctx->thr->fast_state.epoch()); else thr->clock.set(tctx->tid, tctx->epoch1); } void AcquireGlobal(ThreadState *thr, uptr pc) { DPrintf("#%d: AcquireGlobal\n", thr->tid); if (thr->ignore_sync) return; ThreadRegistryLock l(CTX()->thread_registry); CTX()->thread_registry->RunCallbackForEachThreadLocked( UpdateClockCallback, thr); } void Release(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: Release %zx\n", thr->tid, addr); if (thr->ignore_sync) return; SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); // Can't increment epoch w/o writing to the trace as well. TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0); ReleaseImpl(thr, pc, &s->clock); s->mtx.Unlock(); } void ReleaseStore(ThreadState *thr, uptr pc, uptr addr) { CHECK_GT(thr->in_rtl, 0); DPrintf("#%d: ReleaseStore %zx\n", thr->tid, addr); if (thr->ignore_sync) return; SyncVar *s = CTX()->synctab.GetOrCreateAndLock(thr, pc, addr, true); thr->fast_state.IncrementEpoch(); // Can't increment epoch w/o writing to the trace as well. TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0); ReleaseStoreImpl(thr, pc, &s->clock); s->mtx.Unlock(); } #ifndef TSAN_GO static void UpdateSleepClockCallback(ThreadContextBase *tctx_base, void *arg) { ThreadState *thr = reinterpret_cast<ThreadState*>(arg); ThreadContext *tctx = static_cast<ThreadContext*>(tctx_base); if (tctx->status == ThreadStatusRunning) thr->last_sleep_clock.set(tctx->tid, tctx->thr->fast_state.epoch()); else thr->last_sleep_clock.set(tctx->tid, tctx->epoch1); } void AfterSleep(ThreadState *thr, uptr pc) { DPrintf("#%d: AfterSleep %zx\n", thr->tid); if (thr->ignore_sync) return; thr->last_sleep_stack_id = CurrentStackId(thr, pc); ThreadRegistryLock l(CTX()->thread_registry); CTX()->thread_registry->RunCallbackForEachThreadLocked( UpdateSleepClockCallback, thr); } #endif void AcquireImpl(ThreadState *thr, uptr pc, SyncClock *c) { if (thr->ignore_sync) return; thr->clock.set(thr->tid, thr->fast_state.epoch()); thr->clock.acquire(c); StatInc(thr, StatSyncAcquire); } void ReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c) { if (thr->ignore_sync) return; thr->clock.set(thr->tid, thr->fast_state.epoch()); thr->fast_synch_epoch = thr->fast_state.epoch(); thr->clock.release(c); StatInc(thr, StatSyncRelease); } void ReleaseStoreImpl(ThreadState *thr, uptr pc, SyncClock *c) { if (thr->ignore_sync) return; thr->clock.set(thr->tid, thr->fast_state.epoch()); thr->fast_synch_epoch = thr->fast_state.epoch(); thr->clock.ReleaseStore(c); StatInc(thr, StatSyncRelease); } void AcquireReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c) { if (thr->ignore_sync) return; thr->clock.set(thr->tid, thr->fast_state.epoch()); thr->fast_synch_epoch = thr->fast_state.epoch(); thr->clock.acq_rel(c); StatInc(thr, StatSyncAcquire); StatInc(thr, StatSyncRelease); } } // namespace __tsan <|endoftext|>
<commit_before>/** * @file * @author lpraz * * @section DESCRIPTION * Defines tiger's operations functions, which are the top-level functions * for each of tiger's commands. * Any operations functions will be placed in the Tiger::Operations * namespace. */ // Stdlib includes #include <algorithm> #include <iostream> // Include own header #include "Operations.hpp" namespace Tiger { /** * Adds a tag to a file. * In terms of the internal operations of the class, it more so * adds a file to a tag, but the end-user should see no difference. * If the tag doesn't exist, it will be added first, then the file * added to its list. * * @param tagDict The hash table of tags to modify. * @param tag The tag to be added. * @param file The file to add the tag to. */ void Operations::addTagToFile(std::unordered_map<std::string, std::vector<std::string>>& tagDict, std::string tag, std::string file) { if (tagDict.find(tag) == tagDict.end()) { tagDict.insert({tag, std::vector<std::string> {file}}); } else { auto filePosition = std::find(tagDict[tag].begin(), tagDict[tag].end(), file); if (filePosition == tagDict[tag].end()) tagDict[tag].push_back(file); } } /** * Removes a tag from a file. * In terms of the internal operations of the class, it more so * removes a file from a tag, but the end-user should see no * difference. If the tag would have no more files after having * the file removed, it will be deleted. * * @param tagDict The hash table of tags to modify. * @param tag The tag to be removed. * @param file The file to remove the tag from. */ void Operations::removeTagFromFile(std::unordered_map<std::string, std::vector<std::string>>& tagDict, std::string tag, std::string file) { if (tagDict.find(tag) == tagDict.end()) { auto index = std::remove(tagDict[tag].begin(), tagDict[tag].end(), file); if (index != tagDict[tag].end()) tagDict[tag].erase(index); } } /** * Adds the specified tags to the specified files. * Called by the user with the "add" command. * * @param tagDict The hash table of tags to modify. * @param command The command object containing the tags to be * added, and the files to be tagged. */ void Operations::addTags(std::unordered_map<std::string, std::vector<std::string>>& tagDict, std::vector<std::string> tags, std::vector<std::string> files) { for (auto file : files) { for (auto tag : tags) { addTagToFile(tagDict, tag, file); } } } /** * Removes the specified tags from the specified files. * Called by the user with the "remove" command. * * @param tagDict The hash table of tags to modify. * @param command The command object containing the tags to be * added, and the files to be tagged. */ void Operations::removeTags(std::unordered_map<std::string, std::vector<std::string>>& tagDict, std::vector<std::string> tags, std::vector<std::string> files) { // TODO: just plain-ol' doesn't work for (auto file : files) { for (auto tag : tags) { if (tagDict.find(tag) != tagDict.end()) { removeTagFromFile(tagDict, tag, file); } } } } /** * Displays a list of all files with given tags, and all tags * attached to given files. * Called by the user with the "search" command. * * @param tagDict The hash table of tags to search through. * @param command The command object containing the arguments * to base the search on. */ void Operations::search(std::unordered_map<std::string, std::vector<std::string>> tagDict, std::vector<std::string> tags, std::vector<std::string> files) { std::cout << "=== Tags ===\n"; for (auto tag : tags) { std::cout << tag << ":\n\t"; auto tagFiles = tagDict.find(tag); if (tagFiles != tagDict.end()) { for (auto tagFile = tagFiles->second.begin(); tagFile != tagFiles->second.end(); tagFile++) { if (tagFile != tagFiles->second.begin()) std::cout << ",\n\t"; std::cout << *tagFile; } } } std::cout << "=== Files ===\n"; for (auto file : files) { std::cout << file << ":\n\t"; bool first = true; for (auto tag : tagDict) { if (std::find(tag.second.begin(), tag.second.end(), file) != tag.second.end()) { if (first) first = false; else std::cout << ",\n\t"; std::cout << tag.first; } } } std::cout << "\n"; } /** * Displays a list of all tags, and all files that have those * tags. * Called by the user with the "list" command. * * @param tagDict The hash table of tags to output. */ void Operations::displayListOfTags(std::unordered_map<std::string, std::vector<std::string>> tagDict) { for (auto tag : tagDict) { std::cout << tag.first << ":\n\t"; for (auto file = tag.second.begin(); file != tag.second.end(); file++) { if (file != tag.second.begin()) std::cout << ",\n\t"; std::cout << *file; } std::cout << std::endl; } } /** * Displays the help for the application and its commands. * Called by the user with the "help" command, or by specifying * no command at all. */ void Operations::displayHelp(void) { std::string helpText = "tiger is a program for tagging and organizing files.\n" "Alternate between specifying tags and files in your\n" "arguments by using -t and -f, respectively.\n" "Commands:\n" "\thelp: Display this screen.\n" "\tadd: Add tag(s) to file(s).\n" "\tremove: Remove tag(s) from file(s).\n" "\tsearch: Look up files with a certain tag.\n" "\tlist: Display all tags on your system, and all\n" "\t\tof the files they are attached to.\n"; std::cout << helpText; } } <commit_msg>Fixed tag deletion<commit_after>/** * @file * @author lpraz * * @section DESCRIPTION * Defines tiger's operations functions, which are the top-level functions * for each of tiger's commands. * Any operations functions will be placed in the Tiger::Operations * namespace. */ // Stdlib includes #include <algorithm> #include <iostream> // Include own header #include "Operations.hpp" namespace Tiger { /** * Adds a tag to a file. * In terms of the internal operations of the class, it more so * adds a file to a tag, but the end-user should see no difference. * If the tag doesn't exist, it will be added first, then the file * added to its list. * * @param tagDict The hash table of tags to modify. * @param tag The tag to be added. * @param file The file to add the tag to. */ void Operations::addTagToFile(std::unordered_map<std::string, std::vector<std::string>>& tagDict, std::string tag, std::string file) { if (tagDict.find(tag) == tagDict.end()) { tagDict.insert({tag, std::vector<std::string> {file}}); } else { auto filePosition = std::find(tagDict[tag].begin(), tagDict[tag].end(), file); if (filePosition == tagDict[tag].end()) tagDict[tag].push_back(file); } } /** * Removes a tag from a file. * In terms of the internal operations of the class, it more so * removes a file from a tag, but the end-user should see no * difference. If the tag would have no more files after having * the file removed, it will be deleted. * * @param tagDict The hash table of tags to modify. * @param tag The tag to be removed. * @param file The file to remove the tag from. */ void Operations::removeTagFromFile(std::unordered_map<std::string, std::vector<std::string>>& tagDict, std::string tag, std::string file) { if (tagDict.find(tag) != tagDict.end()) { auto index = std::remove(tagDict[tag].begin(), tagDict[tag].end(), file); if (index != tagDict[tag].end()) { tagDict[tag].erase(index); if (tagDict[tag].size() == 0) tagDict.erase(tag); } } } /** * Adds the specified tags to the specified files. * Called by the user with the "add" command. * * @param tagDict The hash table of tags to modify. * @param command The command object containing the tags to be * added, and the files to be tagged. */ void Operations::addTags(std::unordered_map<std::string, std::vector<std::string>>& tagDict, std::vector<std::string> tags, std::vector<std::string> files) { for (auto file : files) { for (auto tag : tags) { addTagToFile(tagDict, tag, file); } } } /** * Removes the specified tags from the specified files. * Called by the user with the "remove" command. * * @param tagDict The hash table of tags to modify. * @param command The command object containing the tags to be * added, and the files to be tagged. */ void Operations::removeTags(std::unordered_map<std::string, std::vector<std::string>>& tagDict, std::vector<std::string> tags, std::vector<std::string> files) { for (auto file : files) { for (auto tag : tags) { removeTagFromFile(tagDict, tag, file); } } } /** * Displays a list of all files with given tags, and all tags * attached to given files. * Called by the user with the "search" command. * * @param tagDict The hash table of tags to search through. * @param command The command object containing the arguments * to base the search on. */ void Operations::search(std::unordered_map<std::string, std::vector<std::string>> tagDict, std::vector<std::string> tags, std::vector<std::string> files) { std::cout << "=== Tags ===\n"; for (auto tag : tags) { std::cout << tag << ":\n\t"; auto tagFiles = tagDict.find(tag); if (tagFiles != tagDict.end()) { for (auto tagFile = tagFiles->second.begin(); tagFile != tagFiles->second.end(); tagFile++) { if (tagFile != tagFiles->second.begin()) std::cout << ",\n\t"; std::cout << *tagFile; } } } std::cout << "=== Files ===\n"; for (auto file : files) { std::cout << file << ":\n\t"; bool first = true; for (auto tag : tagDict) { if (std::find(tag.second.begin(), tag.second.end(), file) != tag.second.end()) { if (first) first = false; else std::cout << ",\n\t"; std::cout << tag.first; } } } std::cout << "\n"; } /** * Displays a list of all tags, and all files that have those * tags. * Called by the user with the "list" command. * * @param tagDict The hash table of tags to output. */ void Operations::displayListOfTags(std::unordered_map<std::string, std::vector<std::string>> tagDict) { for (auto tag : tagDict) { std::cout << tag.first << ":\n\t"; for (auto file = tag.second.begin(); file != tag.second.end(); file++) { if (file != tag.second.begin()) std::cout << ",\n\t"; std::cout << *file; } std::cout << std::endl; } } /** * Displays the help for the application and its commands. * Called by the user with the "help" command, or by specifying * no command at all. */ void Operations::displayHelp(void) { std::string helpText = "tiger is a program for tagging and organizing files.\n" "Alternate between specifying tags and files in your\n" "arguments by using -t and -f, respectively.\n" "Commands:\n" "\thelp: Display this screen.\n" "\tadd: Add tag(s) to file(s).\n" "\tremove: Remove tag(s) from file(s).\n" "\tsearch: Look up files with a certain tag.\n" "\tlist: Display all tags on your system, and all\n" "\t\tof the files they are attached to.\n"; std::cout << helpText; } } <|endoftext|>
<commit_before>#ifndef COFFEE_MILL_PDB_RESIDUE #define COFFEE_MILL_PDB_RESIDUE #include "PDBAtom.hpp" #include <memory> namespace coffeemill { class PDBResidue { public: using size_type = std::size_t; using index_type = size_type; using element_type = std::shared_ptr<PDBAtom>; using container_type = std::vector<element_type>; using iterator = container_type::iterator; using const_iterator = container_type::const_iterator; public: PDBResidue(){} PDBResidue(size_type size) : atoms_(size){} ~PDBResidue() = default; size_type residue_id() const {return atoms_.front()->residue_id();} std::string residue() const {return atoms_.front()->residue();} bool empty() const {return atoms_.empty();} size_type size() const {return atoms_.size();} void clear() {return atoms_.clear();} void push_back(const element_type& atom){return atoms_.push_back(atom);} const element_type& front() const {return atoms_.front();} element_type& front() {return atoms_.front();} const element_type& at(index_type i) const {return atoms_.at(i);} element_type& at(index_type i) {return atoms_.at(i);} const element_type& operator[](index_type i) const {return atoms_[i];} element_type& operator[](index_type i) {return atoms_[i];} iterator begin() {return atoms_.begin();} iterator end() {return atoms_.end();} const_iterator cbegin() const {return atoms_.cbegin();} const_iterator cend() const {return atoms_.cend();} private: container_type atoms_; }; } #endif /* COFFEE_MILL_PDB_RESIDUE */ <commit_msg>add some method to PDBResidue<commit_after>#ifndef COFFEE_MILL_PDB_RESIDUE #define COFFEE_MILL_PDB_RESIDUE #include "PDBAtom.hpp" #include <memory> namespace coffeemill { class PDBResidue { public: using size_type = std::size_t; using index_type = size_type; using element_type = std::shared_ptr<PDBAtom>; using container_type = std::vector<element_type>; using iterator = container_type::iterator; using const_iterator = container_type::const_iterator; public: PDBResidue(){} PDBResidue(size_type size) : atoms_(size){} ~PDBResidue() = default; size_type residue_id() const {return atoms_.front()->residue_id();} const std::string& residue() const {return atoms_.front()->residue();} const std::string& chain_id() const {return atoms_.front()->chain_id();} bool empty() const {return atoms_.empty();} size_type size() const {return atoms_.size();} void clear() {return atoms_.clear();} void push_back(const element_type& atom){return atoms_.push_back(atom);} const element_type& front() const {return atoms_.front();} element_type& front() {return atoms_.front();} const element_type& back() const {return atoms_.back();} element_type& back() {return atoms_.back();} const element_type& at(index_type i) const {return atoms_.at(i);} element_type& at(index_type i) {return atoms_.at(i);} const element_type& operator[](index_type i) const {return atoms_[i];} element_type& operator[](index_type i) {return atoms_[i];} iterator begin() {return atoms_.begin();} iterator end() {return atoms_.end();} const_iterator cbegin() const {return atoms_.cbegin();} const_iterator cend() const {return atoms_.cend();} void dump() const { std::cerr << "residue " << this->residue() << std::endl; for(auto item : atoms_) std::cout << *item << std::endl; } private: container_type atoms_; }; } #endif /* COFFEE_MILL_PDB_RESIDUE */ <|endoftext|>
<commit_before>#include "capacitor.h" #include "time_ordered_set.h" #include "../utils/utils.h" #include "../utils/locker.h" #include "../timeutil.h" #include <cassert> #include <algorithm> #include <list> #include <map> #include <limits> #include <utility> #include <unordered_map> using namespace dariadb; using namespace dariadb::storage; class Capacitor::Private { public: typedef std::shared_ptr<TimeOrderedSet> tos_ptr; typedef std::list<tos_ptr> container; typedef std::unordered_map<dariadb::Id, container> dict; typedef std::unordered_map<dariadb::Id, tos_ptr> dict_last; typedef std::unordered_map<dariadb::Id, std::shared_ptr<dariadb::utils::Locker>> dict_locks; Private(const BaseStorage_ptr stor, const Capacitor::Params&params): _minTime(std::numeric_limits<dariadb::Time>::max()), _maxTime(std::numeric_limits<dariadb::Time>::min()), _bucks(), _last(), _stor(stor), _writed_count(0), _params(params) { } Private(const Private &other) : _minTime(other._minTime), _maxTime(other._maxTime), _bucks(other._bucks), _last(other._last), _stor(other._stor), _writed_count(other._writed_count), _params(other._params) {} ~Private() { } tos_ptr alloc_new() { return std::make_shared<TimeOrderedSet>(_params.max_size); } bool is_valid_time(const dariadb::Time &t)const { auto now=dariadb::timeutil::current_time(); auto past = (now - _params.write_window_deep); if (t< past) { return false; } else { return true; } } bool is_valid(const dariadb::Meas &m)const { return is_valid_time(m.time); } bool check_and_append(const dariadb::Meas&m) { if (!is_valid(m)) { return false; } tos_ptr target = get_target_to_write(m); if (target != nullptr) { target->append(m, true); _writed_count++; _minTime = std::min(_minTime, m.time); _maxTime = std::max(_maxTime, m.time); return true; }else{ assert(false); return false; } } bool append(const dariadb::Meas&m) { auto unlocker=lock_id(m.id); auto res = check_and_append(m); unlocker->unlock(); return res; } dariadb::utils::Locker_ptr lock_id(const dariadb::Id& id){ std::lock_guard<dariadb::utils::Locker> dlg(_dict_locker); dariadb::utils::Locker_ptr result=nullptr; auto it = _locks.find(id); if (it == _locks.end()) { result = std::make_shared<dariadb::utils::Locker>(); _locks.insert(std::make_pair(id, result)); result->lock(); } else { it->second->lock(); result=it->second; } return result; } void flush_old_sets() { std::lock_guard<dariadb::utils::Locker> lg(_locker); for (auto &kv : _bucks) { bool flushed = false; //while (kv.second.size()>0) for (auto it = kv.second.begin(); it != kv.second.end();++it) { auto v = *it; if (!is_valid_time(v->maxTime())) { flush_set(v); flushed = true; v->is_dropped = true; } } if (flushed) { auto r_if_it = std::remove_if( kv.second.begin(), kv.second.end(), [this](const tos_ptr c) { return c->is_dropped; }); kv.second.erase(r_if_it, kv.second.end()); } } } tos_ptr get_target_to_write(const Meas&m) { _locker.lock(); auto last_it=_last.find(m.id); _locker.unlock(); if(last_it ==_last.end()){ _locker.lock(); auto n=alloc_new(); _last.insert(std::make_pair(m.id, n)); _bucks[m.id].push_back(n); _locker.unlock(); return n; } if ((maxTime() <= m.time) || (last_it->second->inInterval(m))) { auto res=last_it->second; if (res->is_full()) { _locker.lock(); res=alloc_new(); _last[m.id]=res; _bucks[m.id].push_back(res); _locker.unlock(); } return res; } else { auto it = _bucks[m.id].rbegin(); for (; it != _bucks[m.id].rend(); ++it) { auto b = *it; if ((b->inInterval(m))|| (b->maxTime()<m.time)) { if(b->is_full()){ auto new_b = alloc_new(); _bucks[m.id].insert(it.base(),new_b); return new_b; } return b; } } auto new_b = alloc_new(); _bucks[m.id].push_front(new_b); return new_b; } } size_t size()const { size_t result = 0; std::for_each(_bucks.cbegin(), _bucks.cend(), [&result](const std::pair<dariadb::Id,container>&c) {result += c.second.size(); }); return result; } dariadb::Time minTime()const { return _minTime; } dariadb::Time maxTime()const { return _maxTime; } size_t writed_count()const { return _writed_count; } bool flush(){ std::lock_guard<dariadb::utils::Locker> lg(_locker); for (auto &kv : _bucks) { for(auto &v:kv.second){ if(!flush_set(v)){ return false; } } } clear(); return true; } bool flush_set(tos_ptr b){ auto arr = b->as_array(); auto stor_res = _stor->append(arr); _writed_count -= arr.size(); if (stor_res.writed != arr.size()) { return false; } return true; } void clear(){ this->_bucks.clear(); _last.clear(); } dariadb::Time get_write_window_deep()const{ return _params.write_window_deep; } protected: dariadb::Time _minTime; dariadb::Time _maxTime; dict _bucks; dict_last _last; BaseStorage_ptr _stor; size_t _writed_count; dariadb::utils::Locker _locker; Capacitor::Params _params; dict_locks _locks; dariadb::utils::Locker _dict_locker; }; Capacitor::~Capacitor(){ this->stop_worker(); } Capacitor::Capacitor(const BaseStorage_ptr stor, const Params&params) : dariadb::utils::PeriodWorker(std::chrono::milliseconds(params.write_window_deep + capasitor_sync_delta)), _Impl(new Capacitor::Private(stor,params)) { this->start_worker(); } bool Capacitor::append(const Meas & m){ return _Impl->append(m); } size_t Capacitor::size()const { return _Impl->size(); } dariadb::Time Capacitor::minTime()const { return _Impl->minTime(); } dariadb::Time Capacitor::maxTime()const { return _Impl->maxTime(); } size_t Capacitor::writed_count()const { return _Impl->writed_count(); } bool Capacitor::flush() {//write all to storage; return _Impl->flush(); } void Capacitor::clear() { return _Impl->clear(); } void Capacitor::call(){ this->_Impl->flush_old_sets(); } <commit_msg>capacitor: right size.<commit_after>#include "capacitor.h" #include "time_ordered_set.h" #include "../utils/utils.h" #include "../utils/locker.h" #include "../timeutil.h" #include <cassert> #include <algorithm> #include <list> #include <map> #include <limits> #include <utility> #include <unordered_map> using namespace dariadb; using namespace dariadb::storage; class Capacitor::Private { public: typedef std::shared_ptr<TimeOrderedSet> tos_ptr; typedef std::list<tos_ptr> container; typedef std::unordered_map<dariadb::Id, container> dict; typedef std::unordered_map<dariadb::Id, tos_ptr> dict_last; typedef std::unordered_map<dariadb::Id, std::shared_ptr<dariadb::utils::Locker>> dict_locks; Private(const BaseStorage_ptr stor, const Capacitor::Params&params): _minTime(std::numeric_limits<dariadb::Time>::max()), _maxTime(std::numeric_limits<dariadb::Time>::min()), _bucks(), _last(), _stor(stor), _writed_count(0), _params(params) { } Private(const Private &other) : _minTime(other._minTime), _maxTime(other._maxTime), _bucks(other._bucks), _last(other._last), _stor(other._stor), _writed_count(other._writed_count), _params(other._params) {} ~Private() { } tos_ptr alloc_new() { return std::make_shared<TimeOrderedSet>(_params.max_size); } bool is_valid_time(const dariadb::Time &t)const { auto now=dariadb::timeutil::current_time(); auto past = (now - _params.write_window_deep); if (t< past) { return false; } else { return true; } } bool is_valid(const dariadb::Meas &m)const { return is_valid_time(m.time); } bool check_and_append(const dariadb::Meas&m) { if (!is_valid(m)) { return false; } tos_ptr target = get_target_to_write(m); if (target != nullptr) { target->append(m, true); _writed_count++; _minTime = std::min(_minTime, m.time); _maxTime = std::max(_maxTime, m.time); return true; }else{ assert(false); return false; } } bool append(const dariadb::Meas&m) { auto unlocker=lock_id(m.id); auto res = check_and_append(m); unlocker->unlock(); return res; } dariadb::utils::Locker_ptr lock_id(const dariadb::Id& id){ std::lock_guard<dariadb::utils::Locker> dlg(_dict_locker); dariadb::utils::Locker_ptr result=nullptr; auto it = _locks.find(id); if (it == _locks.end()) { result = std::make_shared<dariadb::utils::Locker>(); _locks.insert(std::make_pair(id, result)); result->lock(); } else { it->second->lock(); result=it->second; } return result; } void flush_old_sets() { std::lock_guard<dariadb::utils::Locker> lg(_locker); for (auto &kv : _bucks) { bool flushed = false; //while (kv.second.size()>0) for (auto it = kv.second.begin(); it != kv.second.end();++it) { auto v = *it; if (!is_valid_time(v->maxTime())) { flush_set(v); flushed = true; v->is_dropped = true; } } if (flushed) { auto r_if_it = std::remove_if( kv.second.begin(), kv.second.end(), [this](const tos_ptr c) { return c->is_dropped; }); kv.second.erase(r_if_it, kv.second.end()); } } } tos_ptr get_target_to_write(const Meas&m) { _locker.lock(); auto last_it=_last.find(m.id); _locker.unlock(); if(last_it ==_last.end()){ _locker.lock(); auto n=alloc_new(); _last.insert(std::make_pair(m.id, n)); _bucks[m.id].push_back(n); _locker.unlock(); return n; } if ((maxTime() <= m.time) || (last_it->second->inInterval(m))) { auto res=last_it->second; if (res->is_full()) { _locker.lock(); res=alloc_new(); _last[m.id]=res; _bucks[m.id].push_back(res); _locker.unlock(); } return res; } else { auto it = _bucks[m.id].rbegin(); for (; it != _bucks[m.id].rend(); ++it) { auto b = *it; if ((b->inInterval(m))|| (b->maxTime()<m.time)) { if(b->is_full()){ auto new_b = alloc_new(); _bucks[m.id].insert(it.base(),new_b); return new_b; } return b; } } auto new_b = alloc_new(); _bucks[m.id].push_front(new_b); return new_b; } } size_t size()const { size_t result = 0; _locker.lock(); std::for_each(_bucks.cbegin(), _bucks.cend(), [&result](const std::pair<dariadb::Id,container>&c) { for (tos_ptr tptr : c.second) { result += tptr->size(); } }); std::for_each(_last.cbegin(), _last.cend(), [&result](const std::pair<dariadb::Id, tos_ptr>&c) {result += c.second->size();}); _locker.unlock(); return result; } dariadb::Time minTime()const { return _minTime; } dariadb::Time maxTime()const { return _maxTime; } size_t writed_count()const { return _writed_count; } bool flush(){ std::lock_guard<dariadb::utils::Locker> lg(_locker); for (auto &kv : _bucks) { for(auto &v:kv.second){ if(!flush_set(v)){ return false; } } } clear(); return true; } bool flush_set(tos_ptr b){ auto arr = b->as_array(); auto stor_res = _stor->append(arr); _writed_count -= arr.size(); if (stor_res.writed != arr.size()) { return false; } return true; } void clear(){ this->_bucks.clear(); _last.clear(); } dariadb::Time get_write_window_deep()const{ return _params.write_window_deep; } protected: dariadb::Time _minTime; dariadb::Time _maxTime; dict _bucks; dict_last _last; BaseStorage_ptr _stor; size_t _writed_count; mutable dariadb::utils::Locker _locker; Capacitor::Params _params; dict_locks _locks; dariadb::utils::Locker _dict_locker; }; Capacitor::~Capacitor(){ this->stop_worker(); } Capacitor::Capacitor(const BaseStorage_ptr stor, const Params&params) : dariadb::utils::PeriodWorker(std::chrono::milliseconds(params.write_window_deep + capasitor_sync_delta)), _Impl(new Capacitor::Private(stor,params)) { this->start_worker(); } bool Capacitor::append(const Meas & m){ return _Impl->append(m); } size_t Capacitor::size()const { return _Impl->size(); } dariadb::Time Capacitor::minTime()const { return _Impl->minTime(); } dariadb::Time Capacitor::maxTime()const { return _Impl->maxTime(); } size_t Capacitor::writed_count()const { return _Impl->writed_count(); } bool Capacitor::flush() {//write all to storage; return _Impl->flush(); } void Capacitor::clear() { return _Impl->clear(); } void Capacitor::call(){ this->_Impl->flush_old_sets(); } <|endoftext|>
<commit_before>/* Copyright (C) 2010-2011 Collabora Ltd. @author George Kiagiadakis <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "structs.h" #include "miniobject.h" #include "structure.h" #include "../QGlib/value.h" #include <cmath> #include <gst/gstvalue.h> #include <gst/gstminiobject.h> #include <gst/gstdatetime.h> namespace QGlib { GetTypeImpl<QDate>::operator Type() { return GST_TYPE_DATE; } GetTypeImpl<QDateTime>::operator Type() { return GST_TYPE_DATE_TIME; } } //namespace QGlib namespace QGst { namespace Private { void registerValueVTables() { struct ValueVTable_MiniObject { static void get(const QGlib::Value & value, void *data) { *reinterpret_cast<GstMiniObject **>(data) = static_cast<GstMiniObject *>(g_value_get_boxed(value)); }; static void set(QGlib::Value & value, const void *data) { g_value_set_boxed(value, *reinterpret_cast<GstMiniObject * const *>(data)); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<MiniObject>(), QGlib::ValueVTable(ValueVTable_MiniObject::set, ValueVTable_MiniObject::get)); struct ValueVTable_Fraction { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<Fraction*>(data)->numerator = gst_value_get_fraction_numerator(value); reinterpret_cast<Fraction*>(data)->denominator = gst_value_get_fraction_denominator(value); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_fraction(value, reinterpret_cast<Fraction const *>(data)->numerator, reinterpret_cast<Fraction const *>(data)->denominator); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<Fraction>(), QGlib::ValueVTable(ValueVTable_Fraction::set, ValueVTable_Fraction::get)); struct ValueVTable_IntRange { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<IntRange*>(data)->start = gst_value_get_int_range_min(value); reinterpret_cast<IntRange*>(data)->end = gst_value_get_int_range_max(value); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_int_range(value, reinterpret_cast<IntRange const *>(data)->start, reinterpret_cast<IntRange const *>(data)->end); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<IntRange>(), QGlib::ValueVTable(ValueVTable_IntRange::set, ValueVTable_IntRange::get)); struct ValueVTable_Int64Range { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<Int64Range*>(data)->start = gst_value_get_int64_range_min(value); reinterpret_cast<Int64Range*>(data)->end = gst_value_get_int64_range_max(value); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_int64_range(value, reinterpret_cast<Int64Range const *>(data)->start, reinterpret_cast<Int64Range const *>(data)->end); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<Int64Range>(), QGlib::ValueVTable(ValueVTable_Int64Range::set, ValueVTable_Int64Range::get)); struct ValueVTable_DoubleRange { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<DoubleRange*>(data)->start = gst_value_get_double_range_min(value); reinterpret_cast<DoubleRange*>(data)->end = gst_value_get_double_range_max(value); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_double_range(value, reinterpret_cast<DoubleRange const *>(data)->start, reinterpret_cast<DoubleRange const *>(data)->end); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<DoubleRange>(), QGlib::ValueVTable(ValueVTable_DoubleRange::set, ValueVTable_DoubleRange::get)); struct ValueVTable_FractionRange { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<FractionRange*>(data)->start.numerator = gst_value_get_fraction_numerator(gst_value_get_fraction_range_min(value)); reinterpret_cast<FractionRange*>(data)->start.denominator = gst_value_get_fraction_denominator(gst_value_get_fraction_range_min(value)); reinterpret_cast<FractionRange*>(data)->end.numerator = gst_value_get_fraction_numerator(gst_value_get_fraction_range_max(value)); reinterpret_cast<FractionRange*>(data)->end.denominator = gst_value_get_fraction_denominator(gst_value_get_fraction_range_max(value)); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_fraction_range_full(value, reinterpret_cast<FractionRange const *>(data)->start.numerator, reinterpret_cast<FractionRange const *>(data)->start.denominator, reinterpret_cast<FractionRange const *>(data)->end.numerator, reinterpret_cast<FractionRange const *>(data)->end.denominator); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<FractionRange>(), QGlib::ValueVTable(ValueVTable_FractionRange::set, ValueVTable_FractionRange::get)); struct ValueVTable_Structure { static void get(const QGlib::Value & value, void *data) { *reinterpret_cast<Structure*>(data) = Structure(gst_value_get_structure(value)); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_structure(value, *reinterpret_cast<Structure const *>(data)); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<Structure>(), QGlib::ValueVTable(ValueVTable_Structure::set, ValueVTable_Structure::get)); struct ValueVTable_QDate { static void get(const QGlib::Value & value, void *data) { const GDate *gdate = gst_value_get_date(value); *reinterpret_cast<QDate*>(data) = QDate(g_date_get_year(gdate), g_date_get_month(gdate), g_date_get_day(gdate)); } static void set(QGlib::Value & value, const void *data) { const QDate *qdate = reinterpret_cast<QDate const *>(data); GDate *gdate = g_date_new_dmy(qdate->day(), static_cast<GDateMonth>(qdate->month()), qdate->year()); gst_value_set_date(value, gdate); g_date_free(gdate); } }; QGlib::Value::registerValueVTable(QGlib::GetType<QDate>(), QGlib::ValueVTable(ValueVTable_QDate::set, ValueVTable_QDate::get)); struct ValueVTable_QDateTime { static void get(const QGlib::Value & value, void *data) { const GstDateTime *gdatetime = static_cast<GstDateTime*>(g_value_get_boxed(value)); QDate date = QDate(gst_date_time_get_year(gdatetime), gst_date_time_get_month(gdatetime), gst_date_time_get_day(gdatetime)); /* timezone conversion */ float tzoffset = gst_date_time_get_time_zone_offset(gdatetime); float hourOffset; float minutesOffset = std::modf(tzoffset, &hourOffset); int hour = gst_date_time_get_hour(gdatetime) - hourOffset; int minute = gst_date_time_get_minute(gdatetime) - (minutesOffset * 60); /* handle overflow */ if (minute >= 60) { hour++; minute -= 60; } else if (minute < 0) { hour--; minute = 60 + minute; } if (hour >= 24) { date = date.addDays(1); hour -= 24; } else if (hour < 0) { date = date.addDays(-1); hour = 24 + hour; } QTime time = QTime(hour, minute, gst_date_time_get_second(gdatetime), gst_date_time_get_microsecond(gdatetime)/1000); *reinterpret_cast<QDateTime*>(data) = QDateTime(date, time, Qt::UTC); } static void set(QGlib::Value & value, const void *data) { QDateTime qdatetime = reinterpret_cast<QDateTime const *>(data)->toUTC(); GstDateTime *gdatetime = gst_date_time_new(0.0f, qdatetime.date().year(), qdatetime.date().month(), qdatetime.date().day(), qdatetime.time().hour(), qdatetime.time().minute(), qdatetime.time().second() + (qdatetime.time().msec()/1000.0) ); g_value_take_boxed(value, gdatetime); } }; QGlib::Value::registerValueVTable(QGlib::GetType<QDateTime>(), QGlib::ValueVTable(ValueVTable_QDateTime::set, ValueVTable_QDateTime::get)); } } //namespace Private } //namespace QGst <commit_msg>src/QGst/value.cpp GST_TYPE_DATE was replaced with G_TYPE_DATE<commit_after>/* Copyright (C) 2010-2011 Collabora Ltd. @author George Kiagiadakis <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "structs.h" #include "miniobject.h" #include "structure.h" #include "../QGlib/value.h" #include <cmath> #include <gst/gstvalue.h> #include <gst/gstminiobject.h> #include <gst/gstdatetime.h> namespace QGlib { GetTypeImpl<QDate>::operator Type() { return G_TYPE_DATE; } GetTypeImpl<QDateTime>::operator Type() { return GST_TYPE_DATE_TIME; } } //namespace QGlib namespace QGst { namespace Private { void registerValueVTables() { struct ValueVTable_MiniObject { static void get(const QGlib::Value & value, void *data) { *reinterpret_cast<GstMiniObject **>(data) = static_cast<GstMiniObject *>(g_value_get_boxed(value)); }; static void set(QGlib::Value & value, const void *data) { g_value_set_boxed(value, *reinterpret_cast<GstMiniObject * const *>(data)); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<MiniObject>(), QGlib::ValueVTable(ValueVTable_MiniObject::set, ValueVTable_MiniObject::get)); struct ValueVTable_Fraction { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<Fraction*>(data)->numerator = gst_value_get_fraction_numerator(value); reinterpret_cast<Fraction*>(data)->denominator = gst_value_get_fraction_denominator(value); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_fraction(value, reinterpret_cast<Fraction const *>(data)->numerator, reinterpret_cast<Fraction const *>(data)->denominator); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<Fraction>(), QGlib::ValueVTable(ValueVTable_Fraction::set, ValueVTable_Fraction::get)); struct ValueVTable_IntRange { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<IntRange*>(data)->start = gst_value_get_int_range_min(value); reinterpret_cast<IntRange*>(data)->end = gst_value_get_int_range_max(value); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_int_range(value, reinterpret_cast<IntRange const *>(data)->start, reinterpret_cast<IntRange const *>(data)->end); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<IntRange>(), QGlib::ValueVTable(ValueVTable_IntRange::set, ValueVTable_IntRange::get)); struct ValueVTable_Int64Range { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<Int64Range*>(data)->start = gst_value_get_int64_range_min(value); reinterpret_cast<Int64Range*>(data)->end = gst_value_get_int64_range_max(value); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_int64_range(value, reinterpret_cast<Int64Range const *>(data)->start, reinterpret_cast<Int64Range const *>(data)->end); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<Int64Range>(), QGlib::ValueVTable(ValueVTable_Int64Range::set, ValueVTable_Int64Range::get)); struct ValueVTable_DoubleRange { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<DoubleRange*>(data)->start = gst_value_get_double_range_min(value); reinterpret_cast<DoubleRange*>(data)->end = gst_value_get_double_range_max(value); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_double_range(value, reinterpret_cast<DoubleRange const *>(data)->start, reinterpret_cast<DoubleRange const *>(data)->end); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<DoubleRange>(), QGlib::ValueVTable(ValueVTable_DoubleRange::set, ValueVTable_DoubleRange::get)); struct ValueVTable_FractionRange { static void get(const QGlib::Value & value, void *data) { reinterpret_cast<FractionRange*>(data)->start.numerator = gst_value_get_fraction_numerator(gst_value_get_fraction_range_min(value)); reinterpret_cast<FractionRange*>(data)->start.denominator = gst_value_get_fraction_denominator(gst_value_get_fraction_range_min(value)); reinterpret_cast<FractionRange*>(data)->end.numerator = gst_value_get_fraction_numerator(gst_value_get_fraction_range_max(value)); reinterpret_cast<FractionRange*>(data)->end.denominator = gst_value_get_fraction_denominator(gst_value_get_fraction_range_max(value)); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_fraction_range_full(value, reinterpret_cast<FractionRange const *>(data)->start.numerator, reinterpret_cast<FractionRange const *>(data)->start.denominator, reinterpret_cast<FractionRange const *>(data)->end.numerator, reinterpret_cast<FractionRange const *>(data)->end.denominator); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<FractionRange>(), QGlib::ValueVTable(ValueVTable_FractionRange::set, ValueVTable_FractionRange::get)); struct ValueVTable_Structure { static void get(const QGlib::Value & value, void *data) { *reinterpret_cast<Structure*>(data) = Structure(gst_value_get_structure(value)); }; static void set(QGlib::Value & value, const void *data) { gst_value_set_structure(value, *reinterpret_cast<Structure const *>(data)); }; }; QGlib::Value::registerValueVTable(QGlib::GetType<Structure>(), QGlib::ValueVTable(ValueVTable_Structure::set, ValueVTable_Structure::get)); struct ValueVTable_QDate { static void get(const QGlib::Value & value, void *data) { const GDate *gdate = static_cast<const GDate *>(g_value_get_boxed(value)); *reinterpret_cast<QDate*>(data) = QDate(g_date_get_year(gdate), g_date_get_month(gdate), g_date_get_day(gdate)); } static void set(QGlib::Value & value, const void *data) { const QDate *qdate = reinterpret_cast<QDate const *>(data); GDate *gdate = g_date_new_dmy(qdate->day(), static_cast<GDateMonth>(qdate->month()), qdate->year()); g_value_set_boxed(value, gdate); g_date_free(gdate); } }; QGlib::Value::registerValueVTable(QGlib::GetType<QDate>(), QGlib::ValueVTable(ValueVTable_QDate::set, ValueVTable_QDate::get)); struct ValueVTable_QDateTime { static void get(const QGlib::Value & value, void *data) { const GstDateTime *gdatetime = static_cast<GstDateTime*>(g_value_get_boxed(value)); QDate date = QDate(gst_date_time_get_year(gdatetime), gst_date_time_get_month(gdatetime), gst_date_time_get_day(gdatetime)); /* timezone conversion */ float tzoffset = gst_date_time_get_time_zone_offset(gdatetime); float hourOffset; float minutesOffset = std::modf(tzoffset, &hourOffset); int hour = gst_date_time_get_hour(gdatetime) - hourOffset; int minute = gst_date_time_get_minute(gdatetime) - (minutesOffset * 60); /* handle overflow */ if (minute >= 60) { hour++; minute -= 60; } else if (minute < 0) { hour--; minute = 60 + minute; } if (hour >= 24) { date = date.addDays(1); hour -= 24; } else if (hour < 0) { date = date.addDays(-1); hour = 24 + hour; } QTime time = QTime(hour, minute, gst_date_time_get_second(gdatetime), gst_date_time_get_microsecond(gdatetime)/1000); *reinterpret_cast<QDateTime*>(data) = QDateTime(date, time, Qt::UTC); } static void set(QGlib::Value & value, const void *data) { QDateTime qdatetime = reinterpret_cast<QDateTime const *>(data)->toUTC(); GstDateTime *gdatetime = gst_date_time_new(0.0f, qdatetime.date().year(), qdatetime.date().month(), qdatetime.date().day(), qdatetime.time().hour(), qdatetime.time().minute(), qdatetime.time().second() + (qdatetime.time().msec()/1000.0) ); g_value_take_boxed(value, gdatetime); } }; QGlib::Value::registerValueVTable(QGlib::GetType<QDateTime>(), QGlib::ValueVTable(ValueVTable_QDateTime::set, ValueVTable_QDateTime::get)); } } //namespace Private } //namespace QGst <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file TransactionQueue.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "Transaction.h" #include "TransactionQueue.h" using namespace std; using namespace eth; bool TransactionQueue::import(bytes const& _block) { // Check if we already know this transaction. h256 h = sha3(_block); if (m_data.count(h)) return false; try { // Check validity of _block as a transaction. To do this we just deserialise and attempt to determine the sender. If it doesn't work, the signature is bad. // The transaction's nonce may yet be invalid (or, it could be "valid" but we may be missing a marginally older transaction). Transaction t(_block); auto s = t.sender(); if (m_interest.count(s)) m_interestQueue.push_back(t); // If valid, append to blocks. m_data[h] = _block; } catch (InvalidTransactionFormat const& _e) { cwarn << "Ignoring invalid transaction: " << _e.description(); return false; } catch (std::exception const& _e) { cwarn << "Ignoring invalid transaction: " << _e.what(); return false; } return true; } void TransactionQueue::setFuture(std::pair<h256, bytes> const& _t) { if (m_data.count(_t.first)) { m_data.erase(_t.first); m_future.insert(make_pair(Transaction(_t.second).sender(), _t)); } } void TransactionQueue::noteGood(std::pair<h256, bytes> const& _t) { auto r = m_future.equal_range(Transaction(_t.second).sender()); for (auto it = r.first; it != r.second; ++it) m_data.insert(_t); cdebug << m_future; m_future.erase(r.first, r.second); cdebug << m_future; } <commit_msg>Remove debug code.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file TransactionQueue.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "Transaction.h" #include "TransactionQueue.h" using namespace std; using namespace eth; bool TransactionQueue::import(bytes const& _block) { // Check if we already know this transaction. h256 h = sha3(_block); if (m_data.count(h)) return false; try { // Check validity of _block as a transaction. To do this we just deserialise and attempt to determine the sender. If it doesn't work, the signature is bad. // The transaction's nonce may yet be invalid (or, it could be "valid" but we may be missing a marginally older transaction). Transaction t(_block); auto s = t.sender(); if (m_interest.count(s)) m_interestQueue.push_back(t); // If valid, append to blocks. m_data[h] = _block; } catch (InvalidTransactionFormat const& _e) { cwarn << "Ignoring invalid transaction: " << _e.description(); return false; } catch (std::exception const& _e) { cwarn << "Ignoring invalid transaction: " << _e.what(); return false; } return true; } void TransactionQueue::setFuture(std::pair<h256, bytes> const& _t) { if (m_data.count(_t.first)) { m_data.erase(_t.first); m_future.insert(make_pair(Transaction(_t.second).sender(), _t)); } } void TransactionQueue::noteGood(std::pair<h256, bytes> const& _t) { auto r = m_future.equal_range(Transaction(_t.second).sender()); for (auto it = r.first; it != r.second; ++it) m_data.insert(_t); m_future.erase(r.first, r.second); } <|endoftext|>
<commit_before> /*--------------------------------------------------------- * Includes *--------------------------------------------------------*/ #include "KingJelly.h" #include "RainEffect.h" /*--------------------------------------------------------- * Macros *--------------------------------------------------------*/ #define ABS(x) ((x<=0)?-x:x) /*--------------------------------------------------------- * Utility Functions *--------------------------------------------------------*/ uint32_t mod(int32_t a, int32_t b) { return (a%b+b)%b; } /*--------------------------------------------------------- * Methods *--------------------------------------------------------*/ BaseEffect* RainEffect::Create() { return new RainEffect(); } RainEffect::RainEffect() : mOffset(0), mHue(0.5f), mSpeed(10), mMod(100), mLen(10) {} void RainEffect::beginFrame(const FrameInfo& /*frame*/) { mMod = Input(Pot0)*255.0f; mHue = Input(Pot1); mSpeed = (int) ((1.0 - Input(Pot2)) * 20) + 1; mLen = (int) (Input(Pot3)*50) + 1; mOffset++; } void RainEffect::shader(Vec3& rgb, const PixelInfo& pixel) const { // position within a given strand uint32_t pos = pixel.index % mMod; uint32_t off = (mOffset/(int)mSpeed) % JellyPixel::kLedCount; // distance from the center pixel of the wave int distance = ABS(min(mod(pos - off, JellyPixel::kLedCount), mod(off - pos, JellyPixel::kLedCount))); // get dimmer based on distance from center float wave = max(0.0, (mLen-distance)/(double)mLen); /* if(pixel.index > 80 && pixel.index < 100) if(wave != 0.0) printf("%d %d %d (%d = %d, %d = %d) %d %f\n", mOffset, pos, off, (pos - off), mod(pos - off,100), off - pos, mod(off - pos, 100), distance,wave); */ hsv2rgb(rgb, mHue, 1.0f, wave); //printf("%d : (%f %f %f) : %f %f %f\n", pixel.index, rgb[0], rgb[1], rgb[2],mHue,1.0,wave); } <commit_msg>Reverted changes to RainEffect back to original code except mapping speed to Pot0.<commit_after> /*--------------------------------------------------------- * Includes *--------------------------------------------------------*/ #include "KingJelly.h" #include "RainEffect.h" /*--------------------------------------------------------- * Macros *--------------------------------------------------------*/ #define ABS(x) ((x<=0)?-x:x) /*--------------------------------------------------------- * Utility Functions *--------------------------------------------------------*/ uint32_t mod(int32_t a, int32_t b) { return (a%b+b)%b; } /*--------------------------------------------------------- * Methods *--------------------------------------------------------*/ BaseEffect* RainEffect::Create() { return new RainEffect(); } RainEffect::RainEffect() : mOffset(0), mHue(0.5f), mSpeed(10), mMod(100), mLen(10) {} void RainEffect::beginFrame(const FrameInfo& /*frame*/) { mMod = 90 + (int)(Input(Pot1)*255.0); mHue = Input(Pot2); mSpeed = (int) ((1.0 - Input(Pot0)) * 20) + 1; mLen = (int) (Input(Pot3)*50) + 1; mOffset++; } void RainEffect::shader(Vec3& rgb, const PixelInfo& pixel) const { // position within a given strand uint32_t pos = pixel.index % mMod; uint32_t off = (mOffset/(int)mSpeed) % JellyPixel::kLedCount; // distance from the center pixel of the wave int distance = ABS(min(mod(pos - off, JellyPixel::kLedCount), mod(off - pos, JellyPixel::kLedCount))); // get dimmer based on distance from center float wave = max(0.0, (mLen-distance)/(double)mLen); /* if(pixel.index > 80 && pixel.index < 100) if(wave != 0.0) printf("%d %d %d (%d = %d, %d = %d) %d %f\n", mOffset, pos, off, (pos - off), mod(pos - off,100), off - pos, mod(off - pos, 100), distance,wave); */ hsv2rgb(rgb, mHue, 1.0f, wave); //printf("%d : (%f %f %f) : %f %f %f\n", pixel.index, rgb[0], rgb[1], rgb[2],mHue,1.0,wave); } <|endoftext|>
<commit_before>#include "RandomWall.h" #include "RoomWall.h" #include <memory> void RandomWalls::generateContent(Room * room) { auto topWall = std::make_shared<RoomWall>(250, 50); room->spawn(topWall, room->getRandomPosition()); // room->spawn(wall, ); } <commit_msg>adding in random chance for vertical walls<commit_after>#include "RandomWall.h" #include "RoomWall.h" #include <memory> #include <random> void RandomWalls::generateContent(Room * room) { std::random_device rd; std::uniform_int_distribution<int> randDirection(0, 100); std::shared_ptr<RoomWall> wall; if (randDirection(rd) < 50) wall = std::make_shared<RoomWall>(250, 50); else wall = std::make_shared<RoomWall>(50, 250); room->spawn(wall, room->getRandomPosition()); // room->spawn(wall, ); } <|endoftext|>
<commit_before>#include "Rasterizer.h" #include <limits> //numerics::max #include "Utils.h" // Rasterizer::Rasterizer() : Renderer() { } Rasterizer::Rasterizer(World* world, const uint16_t image_width, const uint16_t image_height) : Renderer(world, image_width, image_height) { } Rasterizer::~Rasterizer(){ } void Rasterizer::render(const std::string output_path) { std::vector<double> depth = std::vector<double>(m_image_height * m_image_width, std::numeric_limits<double>::max()); for (auto& geometry_object : m_world->m_objects) { const std::vector<Triangle3D> triangles_of_object = geometry_object->tessellate(); for (auto& triangle_world : triangles_of_object) { const Triangle2D triangle_projected = m_world->m_camera->worldSpaceToScreenSpace(triangle_world); //TODO: Bounding box optimization for (int i = 0; i < (m_image_width * m_image_height); ++i) { uint16_t c = m_image_width * m_image_height; uint16_t pixel_image_x, pixel_image_y; Utils::convert1DIndexto2DIndex(pixel_image_x, pixel_image_y, i, m_image_width, m_image_height); RGBColor pixel = m_pixels[i]; const Point3D pixel_world = m_world->m_camera->imageSpaceToWorldSpace(m_image_width, m_image_height, pixel_image_x, pixel_image_y); const Point2D pixel_screen = Point2D(pixel_world.x, pixel_world.y); if (triangle_projected.contains(pixel_screen)) { const double current_depth = m_world->m_camera->getDepth(triangle_world, triangle_projected, pixel_screen); if (current_depth < depth[i]) { m_pixels[i] = geometry_object->m_color; depth[i] = current_depth; } } } } } //TODO Calculate illumination (fragment shader) exportImage(output_path); }; <commit_msg>Changed for index type from std::int to uint32<commit_after>#include "Rasterizer.h" #include <limits> //numerics::max #include "Utils.h" // Rasterizer::Rasterizer() : Renderer() { } Rasterizer::Rasterizer(World* world, const uint16_t image_width, const uint16_t image_height) : Renderer(world, image_width, image_height) { } Rasterizer::~Rasterizer(){ } void Rasterizer::render(const std::string output_path) { std::vector<double> depth = std::vector<double>(m_image_height * m_image_width, std::numeric_limits<double>::max()); for (auto& geometry_object : m_world->m_objects) { const std::vector<Triangle3D> triangles_of_object = geometry_object->tessellate(); for (auto& triangle_world : triangles_of_object) { const Triangle2D triangle_projected = m_world->m_camera->worldSpaceToScreenSpace(triangle_world); //TODO: Bounding box optimization for (uint32_t i = 0; i < (m_image_width * m_image_height); ++i) { uint16_t c = m_image_width * m_image_height; uint16_t pixel_image_x, pixel_image_y; Utils::convert1DIndexto2DIndex(pixel_image_x, pixel_image_y, i, m_image_width, m_image_height); const Point3D pixel_world = m_world->m_camera->imageSpaceToWorldSpace(m_image_width, m_image_height, pixel_image_x, pixel_image_y); const Point2D pixel_screen = Point2D(pixel_world.x, pixel_world.y); if (triangle_projected.contains(pixel_screen)) { const double current_depth = m_world->m_camera->getDepth(triangle_world, triangle_projected, pixel_screen); if (current_depth < depth[i]) { m_pixels[i] = geometry_object->m_color; depth[i] = current_depth; } } } } } //TODO Calculate illumination (fragment shader) exportImage(output_path); }; <|endoftext|>
<commit_before>/* * qdispatchqueue.cpp * * Copyright (c) 2011-2013 MLBA-Team. * All rights reserved. * * @LICENSE_HEADER_START@ * 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. * @LICENSE_HEADER_END@ */ #include <QRunnable> #include <QString> #include <QDebug> #include "../include/QtDispatch/qdispatch.h" #include "../include/QtDispatch/qblockrunnable.h" #include "../include/QtDispatch/qiterationblockrunnable.h" #include "qrunnableoperations.h" QT_BEGIN_NAMESPACE QDispatchQueue::QDispatchQueue ( const QString &label ) : xdispatch::queue( label.toStdString() ) { } QDispatchQueue::QDispatchQueue ( const char *label ) : xdispatch::queue( label ) { } QDispatchQueue::QDispatchQueue ( dispatch_queue_t dq ) : xdispatch::queue( dq ) { if( dq == NULL ) throw ( "Cannot construct queue" ); } QDispatchQueue::QDispatchQueue ( const QDispatchQueue &obj ) : xdispatch::queue( obj ){ } QDispatchQueue::QDispatchQueue ( const xdispatch::queue &obj ) : xdispatch::queue( obj ){ } QDispatchQueue::~QDispatchQueue (){ } void QDispatchQueue::async( QRunnable *runnable ) { Q_ASSERT( runnable ); async( new RunnableOperation( runnable ) ); } void QDispatchQueue::apply( QIterationRunnable *runnable, int times ) { Q_ASSERT( runnable ); apply( new IterationRunnableOperation( runnable ), times ); } void QDispatchQueue::after( QRunnable *runnable, const QTime &t ) { Q_ASSERT( runnable ); after( runnable, QDispatch::asDispatchTime( t ) ); } void QDispatchQueue::after( QRunnable *r, dispatch_time_t t ) { Q_ASSERT( r ); after( new RunnableOperation( r ), t ); } void QDispatchQueue::sync( QRunnable *runnable ) { Q_ASSERT( runnable ); sync( new RunnableOperation( runnable ) ); } void QDispatchQueue::setFinalizer( xdispatch::operation *op, const xdispatch::queue &q ) { finalizer( op, q ); } void QDispatchQueue::setFinalizer( QRunnable *r, const xdispatch::queue &dq ) { Q_ASSERT( r ); finalizer( new RunnableOperation( r ), dq ); } void QDispatchQueue::setTarget( const xdispatch::queue &q ) { target_queue( q ); } void QDispatchQueue::suspend() { xdispatch::queue::suspend(); } void QDispatchQueue::resume() { xdispatch::queue::resume(); } QDispatchQueue & QDispatchQueue::operator = ( const QDispatchQueue &other ) { if( this != &other ) xdispatch::queue::operator = ( other ); return *this; } Q_DECL_EXPORT QDebug operator << ( QDebug dbg, const QDispatchQueue *q ) { dbg.nospace() << "QDispatchQueue (" << q->label().c_str() << ")"; return dbg.space(); } Q_DECL_EXPORT QDebug operator << ( QDebug dbg, const QDispatchQueue &q ) { dbg.nospace() << "QDispatchQueue (" << q.label().c_str() << ")"; return dbg.space(); } QT_END_NAMESPACE<commit_msg>Made QDispatchQueue use the new argument order<commit_after>/* * qdispatchqueue.cpp * * Copyright (c) 2011-2013 MLBA-Team. * All rights reserved. * * @LICENSE_HEADER_START@ * 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. * @LICENSE_HEADER_END@ */ #include <QRunnable> #include <QString> #include <QDebug> #include "../include/QtDispatch/qdispatch.h" #include "../include/QtDispatch/qblockrunnable.h" #include "../include/QtDispatch/qiterationblockrunnable.h" #include "qrunnableoperations.h" QT_BEGIN_NAMESPACE QDispatchQueue::QDispatchQueue ( const QString &label ) : xdispatch::queue( label.toStdString() ) { } QDispatchQueue::QDispatchQueue ( const char *label ) : xdispatch::queue( label ) { } QDispatchQueue::QDispatchQueue ( dispatch_queue_t dq ) : xdispatch::queue( dq ) { if( dq == NULL ) throw ( "Cannot construct queue" ); } QDispatchQueue::QDispatchQueue ( const QDispatchQueue &obj ) : xdispatch::queue( obj ){ } QDispatchQueue::QDispatchQueue ( const xdispatch::queue &obj ) : xdispatch::queue( obj ){ } QDispatchQueue::~QDispatchQueue (){ } void QDispatchQueue::async( QRunnable *runnable ) { Q_ASSERT( runnable ); async( new RunnableOperation( runnable ) ); } void QDispatchQueue::apply( QIterationRunnable *runnable, int times ) { Q_ASSERT( runnable ); apply( times, new IterationRunnableOperation( runnable ) ); } void QDispatchQueue::after( QRunnable *runnable, const QTime &t ) { Q_ASSERT( runnable ); after( runnable, QDispatch::asDispatchTime( t ) ); } void QDispatchQueue::after( QRunnable *r, dispatch_time_t t ) { Q_ASSERT( r ); after( t, new RunnableOperation( r ) ); } void QDispatchQueue::sync( QRunnable *runnable ) { Q_ASSERT( runnable ); sync( new RunnableOperation( runnable ) ); } void QDispatchQueue::setFinalizer( xdispatch::operation *op, const xdispatch::queue &q ) { finalizer( op, q ); } void QDispatchQueue::setFinalizer( QRunnable *r, const xdispatch::queue &dq ) { Q_ASSERT( r ); finalizer( new RunnableOperation( r ), dq ); } void QDispatchQueue::setTarget( const xdispatch::queue &q ) { target_queue( q ); } void QDispatchQueue::suspend() { xdispatch::queue::suspend(); } void QDispatchQueue::resume() { xdispatch::queue::resume(); } QDispatchQueue & QDispatchQueue::operator = ( const QDispatchQueue &other ) { if( this != &other ) xdispatch::queue::operator = ( other ); return *this; } Q_DECL_EXPORT QDebug operator << ( QDebug dbg, const QDispatchQueue *q ) { dbg.nospace() << "QDispatchQueue (" << q->label().c_str() << ")"; return dbg.space(); } Q_DECL_EXPORT QDebug operator << ( QDebug dbg, const QDispatchQueue &q ) { dbg.nospace() << "QDispatchQueue (" << q.label().c_str() << ")"; return dbg.space(); } QT_END_NAMESPACE<|endoftext|>
<commit_before>#ifndef SORT_COMMON_H #define SORT_COMMON_H #include <algorithm> #include <complex> #include <ctime> #include <iostream> #include <string> #include <utility> #include <vector> #include <pthread.h> #include <cstdlib> #include <sys/time.h> #include <sys/resource.h> #include "NumGen.cpp" /*! Basic sorting class providing the framework for benchmarking the sorting algorithms. */ class SortCommon { public: typedef long unsigned int ContainType; typedef std::vector<ContainType> DataType; typedef std::pair<size_t, size_t> MinMaxPairsType; typedef std::vector<MinMaxPairsType> MinMaxVect; typedef size_t threadCount; //*! Default constructor. /*! This default constuctor sets the number of threads to a safe value (one) */ SortCommon(); //*! Default destructor. virtual ~SortCommon(); //*! Runs std::sort directly modifying the passed argument. /*! \param data_in the object getting sorted. */ virtual void Sort(DataType * , const threadCount ) = 0; //*! Benchmarks the sort returning the number of seconds required to run. /*! \param data_in the object getting sorted. Is passed in as constant. \returns The number of seconds necessary to run sort. Returns negative value if sort failed. */ double BenchmarkSort(const DataType *, const threadCount ); //*! Creates new data object /*! Creates a DataType object with size elments in a random order going from 0 up to size. \param size the number of elements to get created in the ranom data object. \returns A DataType object. */ static DataType * NewData(size_t size, bool ordered=false, bool reverse=false); //*! Confirms that a DataType object is sorted and returns true or false. /*! \param data_in the DataType object to confirm it is sorted. \retval true If DataType object is sorted. \retval false If DataType object is not sorted. */ bool CheckSort(const DataType * , const size_t); static void PrintDataType(const DataType *, std::string, bool = false); protected: static MinMaxVect buildPairs(size_t num_threads, size_t min, size_t max); static MinMaxVect buildPow2Pairs(size_t num_threads, size_t min, size_t max); private: double GetTime(); }; #endif <commit_msg>Backtracking on long unsigned int. Going back to unsigned int to keep code happy.<commit_after>#ifndef SORT_COMMON_H #define SORT_COMMON_H #include <algorithm> #include <complex> #include <ctime> #include <iostream> #include <string> #include <utility> #include <vector> #include <pthread.h> #include <cstdlib> #include <sys/time.h> #include <sys/resource.h> #include "NumGen.cpp" /*! Basic sorting class providing the framework for benchmarking the sorting algorithms. */ class SortCommon { public: typedef unsigned int ContainType; typedef std::vector<ContainType> DataType; typedef std::pair<size_t, size_t> MinMaxPairsType; typedef std::vector<MinMaxPairsType> MinMaxVect; typedef size_t threadCount; //*! Default constructor. /*! This default constuctor sets the number of threads to a safe value (one) */ SortCommon(); //*! Default destructor. virtual ~SortCommon(); //*! Runs std::sort directly modifying the passed argument. /*! \param data_in the object getting sorted. */ virtual void Sort(DataType * , const threadCount ) = 0; //*! Benchmarks the sort returning the number of seconds required to run. /*! \param data_in the object getting sorted. Is passed in as constant. \returns The number of seconds necessary to run sort. Returns negative value if sort failed. */ double BenchmarkSort(const DataType *, const threadCount ); //*! Creates new data object /*! Creates a DataType object with size elments in a random order going from 0 up to size. \param size the number of elements to get created in the ranom data object. \returns A DataType object. */ static DataType * NewData(size_t size, bool ordered=false, bool reverse=false); //*! Confirms that a DataType object is sorted and returns true or false. /*! \param data_in the DataType object to confirm it is sorted. \retval true If DataType object is sorted. \retval false If DataType object is not sorted. */ bool CheckSort(const DataType * , const size_t); static void PrintDataType(const DataType *, std::string, bool = false); protected: static MinMaxVect buildPairs(size_t num_threads, size_t min, size_t max); static MinMaxVect buildPow2Pairs(size_t num_threads, size_t min, size_t max); private: double GetTime(); }; #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pavel Kirienko <[email protected]> */ #pragma once #include <cassert> #include <cstdlib> #include <uavcan/linked_list.hpp> #include <uavcan/impl_constants.hpp> #include <uavcan/dynamic_memory.hpp> #include <uavcan/util/compile_time.hpp> namespace uavcan { /** * Slow but memory efficient KV container. * Type requirements: * Both key and value must be copyable, assignable and default constructible. * Key must implement a comparison operator. * Key's default constructor must initialize the object into invalid state. * Size of Key + Value + padding must not exceed MemPoolBlockSize. */ template <typename Key, typename Value, unsigned NumStaticEntries> class UAVCAN_EXPORT Map : Noncopyable { UAVCAN_PACKED_BEGIN struct KVPair { Key key; Value value; KVPair() { } KVPair(const Key& key, const Value& value) : key(key) , value(value) { } bool match(const Key& rhs) const { return rhs == key; } }; struct KVGroup : LinkedListNode<KVGroup> { enum { NumKV = (MemPoolBlockSize - sizeof(LinkedListNode<KVGroup>)) / sizeof(KVPair) }; KVPair kvs[NumKV]; KVGroup() { StaticAssert<(NumKV > 0)>::check(); IsDynamicallyAllocatable<KVGroup>::check(); } static KVGroup* instantiate(IAllocator& allocator) { void* const praw = allocator.allocate(sizeof(KVGroup)); if (praw == NULL) { return NULL; } return new (praw) KVGroup(); } static void destroy(KVGroup*& obj, IAllocator& allocator) { if (obj != NULL) { obj->~KVGroup(); allocator.deallocate(obj); obj = NULL; } } KVPair* find(const Key& key) { for (int i = 0; i < NumKV; i++) { if (kvs[i].match(key)) { return kvs + i; } } return NULL; } }; UAVCAN_PACKED_END LinkedListRoot<KVGroup> list_; IAllocator& allocator_; KVPair static_[NumStaticEntries]; KVPair* find(const Key& key) { for (unsigned i = 0; i < NumStaticEntries; i++) { if (static_[i].match(key)) { return static_ + i; } } KVGroup* p = list_.get(); while (p) { KVPair* const kv = p->find(key); if (kv) { return kv; } p = p->getNextListNode(); } return NULL; } void optimizeStorage() { while (true) { // Looking for first EMPTY static entry KVPair* stat = NULL; for (unsigned i = 0; i < NumStaticEntries; i++) { if (static_[i].match(Key())) { stat = static_ + i; break; } } if (stat == NULL) { break; } // Looking for the first NON-EMPTY dynamic entry, erasing immediately KVGroup* p = list_.get(); KVPair dyn; while (p) { bool stop = false; for (int i = 0; i < KVGroup::NumKV; i++) { if (!p->kvs[i].match(Key())) // Non empty { dyn = p->kvs[i]; // Copy by value p->kvs[i] = KVPair(); // Erase immediately stop = true; break; } } if (stop) { break; } p = p->getNextListNode(); } if (dyn.match(Key())) { break; } // Migrating *stat = dyn; } } void compact() { KVGroup* p = list_.get(); while (p) { KVGroup* const next = p->getNextListNode(); bool remove_this = true; for (int i = 0; i < KVGroup::NumKV; i++) { if (!p->kvs[i].match(Key())) { remove_this = false; break; } } if (remove_this) { list_.remove(p); KVGroup::destroy(p, allocator_); } p = next; } } struct YesPredicate { bool operator()(const Key& k, const Value& v) const { (void)k; (void)v; return true; } }; // This container is not copyable Map(const Map&); bool operator=(const Map&); public: Map(IAllocator& allocator) : allocator_(allocator) { assert(Key() == Key()); } ~Map() { removeAll(); } Value* access(const Key& key) { assert(!(key == Key())); KVPair* const kv = find(key); return kv ? &kv->value : NULL; } /// If entry with the same key already exists, it will be replaced Value* insert(const Key& key, const Value& value) { assert(!(key == Key())); remove(key); KVPair* const kv = find(Key()); if (kv) { *kv = KVPair(key, value); return &kv->value; } KVGroup* const kvg = KVGroup::instantiate(allocator_); if (kvg == NULL) { return NULL; } list_.insert(kvg); kvg->kvs[0] = KVPair(key, value); return &kvg->kvs[0].value; } void remove(const Key& key) { assert(!(key == Key())); KVPair* const kv = find(key); if (kv) { *kv = KVPair(); optimizeStorage(); compact(); } } /** * Remove entries where predicate returns true. * Predicate prototype: * bool (const Key& key, const Value& value) */ template <typename Predicate> void removeWhere(Predicate predicate) { unsigned num_removed = 0; for (unsigned i = 0; i < NumStaticEntries; i++) { if (!static_[i].match(Key())) { if (predicate(static_[i].key, static_[i].value)) { num_removed++; static_[i] = KVPair(); } } } KVGroup* p = list_.get(); while (p) { for (int i = 0; i < KVGroup::NumKV; i++) { const KVPair* const kv = p->kvs + i; if (!kv->match(Key())) { if (predicate(kv->key, kv->value)) { num_removed++; p->kvs[i] = KVPair(); } } } p = p->getNextListNode(); } if (num_removed > 0) { optimizeStorage(); compact(); } } template <typename Predicate> const Key* findFirstKey(Predicate predicate) const { for (unsigned i = 0; i < NumStaticEntries; i++) { if (!static_[i].match(Key())) { if (predicate(static_[i].key, static_[i].value)) { return &static_[i].key; } } } KVGroup* p = list_.get(); while (p) { for (int i = 0; i < KVGroup::NumKV; i++) { const KVPair* const kv = p->kvs + i; if (!kv->match(Key())) { if (predicate(kv->key, kv->value)) { return &p->kvs[i].key; } } } p = p->getNextListNode(); } return NULL; } void removeAll() { removeWhere(YesPredicate()); } bool isEmpty() const { return (getNumStaticPairs() == 0) && (getNumDynamicPairs() == 0); } /// For testing unsigned getNumStaticPairs() const { unsigned num = 0; for (unsigned i = 0; i < NumStaticEntries; i++) { if (!static_[i].match(Key())) { num++; } } return num; } /// For testing unsigned getNumDynamicPairs() const { unsigned num = 0; KVGroup* p = list_.get(); while (p) { for (int i = 0; i < KVGroup::NumKV; i++) { const KVPair* const kv = p->kvs + i; if (!kv->match(Key())) { num++; } } p = p->getNextListNode(); } return num; } }; } <commit_msg>Much space optimized Map<> container - saves 40kb of Flash for STM32 test (-O1)<commit_after>/* * Copyright (C) 2014 Pavel Kirienko <[email protected]> */ #pragma once #include <cassert> #include <cstdlib> #include <uavcan/linked_list.hpp> #include <uavcan/impl_constants.hpp> #include <uavcan/dynamic_memory.hpp> #include <uavcan/util/compile_time.hpp> namespace uavcan { /** * Slow but memory efficient KV container. * Type requirements: * Both key and value must be copyable, assignable and default constructible. * Key must implement a comparison operator. * Key's default constructor must initialize the object into invalid state. * Size of Key + Value + padding must not exceed MemPoolBlockSize. */ template <typename Key, typename Value, unsigned NumStaticEntries> class UAVCAN_EXPORT Map : Noncopyable { UAVCAN_PACKED_BEGIN struct KVPair { Key key; Value value; KVPair() { } KVPair(const Key& key, const Value& value) : key(key) , value(value) { } bool match(const Key& rhs) const { return rhs == key; } }; struct KVGroup : LinkedListNode<KVGroup> { enum { NumKV = (MemPoolBlockSize - sizeof(LinkedListNode<KVGroup>)) / sizeof(KVPair) }; KVPair kvs[NumKV]; KVGroup() { StaticAssert<(NumKV > 0)>::check(); IsDynamicallyAllocatable<KVGroup>::check(); } static KVGroup* instantiate(IAllocator& allocator) { void* const praw = allocator.allocate(sizeof(KVGroup)); if (praw == NULL) { return NULL; } return new (praw) KVGroup(); } static void destroy(KVGroup*& obj, IAllocator& allocator) { if (obj != NULL) { obj->~KVGroup(); allocator.deallocate(obj); obj = NULL; } } KVPair* find(const Key& key) { for (int i = 0; i < NumKV; i++) { if (kvs[i].match(key)) { return kvs + i; } } return NULL; } }; UAVCAN_PACKED_END LinkedListRoot<KVGroup> list_; IAllocator& allocator_; KVPair static_[NumStaticEntries]; KVPair* find(const Key& key); void optimizeStorage(); void compact(); struct YesPredicate { bool operator()(const Key& k, const Value& v) const { (void)k; (void)v; return true; } }; // This container is not copyable Map(const Map&); bool operator=(const Map&); public: Map(IAllocator& allocator) : allocator_(allocator) { assert(Key() == Key()); } ~Map() { removeAll(); } Value* access(const Key& key); /// If entry with the same key already exists, it will be replaced Value* insert(const Key& key, const Value& value); void remove(const Key& key); /** * Remove entries where predicate returns true. * Predicate prototype: * bool (const Key& key, const Value& value) */ template <typename Predicate> void removeWhere(Predicate predicate); template <typename Predicate> const Key* findFirstKey(Predicate predicate) const; void removeAll(); bool isEmpty() const; /// For testing unsigned getNumStaticPairs() const; /// For testing unsigned getNumDynamicPairs() const; }; // ---------------------------------------------------------------------------- /* * Map<> */ template <typename Key, typename Value, unsigned NumStaticEntries> typename Map<Key, Value, NumStaticEntries>::KVPair* Map<Key, Value, NumStaticEntries>::find(const Key& key) { for (unsigned i = 0; i < NumStaticEntries; i++) { if (static_[i].match(key)) { return static_ + i; } } KVGroup* p = list_.get(); while (p) { KVPair* const kv = p->find(key); if (kv) { return kv; } p = p->getNextListNode(); } return NULL; } template <typename Key, typename Value, unsigned NumStaticEntries> void Map<Key, Value, NumStaticEntries>::optimizeStorage() { while (true) { // Looking for first EMPTY static entry KVPair* stat = NULL; for (unsigned i = 0; i < NumStaticEntries; i++) { if (static_[i].match(Key())) { stat = static_ + i; break; } } if (stat == NULL) { break; } // Looking for the first NON-EMPTY dynamic entry, erasing immediately KVGroup* p = list_.get(); KVPair dyn; while (p) { bool stop = false; for (int i = 0; i < KVGroup::NumKV; i++) { if (!p->kvs[i].match(Key())) // Non empty { dyn = p->kvs[i]; // Copy by value p->kvs[i] = KVPair(); // Erase immediately stop = true; break; } } if (stop) { break; } p = p->getNextListNode(); } if (dyn.match(Key())) { break; } // Migrating *stat = dyn; } } template <typename Key, typename Value, unsigned NumStaticEntries> void Map<Key, Value, NumStaticEntries>::compact() { KVGroup* p = list_.get(); while (p) { KVGroup* const next = p->getNextListNode(); bool remove_this = true; for (int i = 0; i < KVGroup::NumKV; i++) { if (!p->kvs[i].match(Key())) { remove_this = false; break; } } if (remove_this) { list_.remove(p); KVGroup::destroy(p, allocator_); } p = next; } } template <typename Key, typename Value, unsigned NumStaticEntries> Value* Map<Key, Value, NumStaticEntries>::access(const Key& key) { assert(!(key == Key())); KVPair* const kv = find(key); return kv ? &kv->value : NULL; } template <typename Key, typename Value, unsigned NumStaticEntries> Value* Map<Key, Value, NumStaticEntries>::insert(const Key& key, const Value& value) { assert(!(key == Key())); remove(key); KVPair* const kv = find(Key()); if (kv) { *kv = KVPair(key, value); return &kv->value; } KVGroup* const kvg = KVGroup::instantiate(allocator_); if (kvg == NULL) { return NULL; } list_.insert(kvg); kvg->kvs[0] = KVPair(key, value); return &kvg->kvs[0].value; } template <typename Key, typename Value, unsigned NumStaticEntries> void Map<Key, Value, NumStaticEntries>::remove(const Key& key) { assert(!(key == Key())); KVPair* const kv = find(key); if (kv) { *kv = KVPair(); optimizeStorage(); compact(); } } template <typename Key, typename Value, unsigned NumStaticEntries> template <typename Predicate> void Map<Key, Value, NumStaticEntries>::removeWhere(Predicate predicate) { unsigned num_removed = 0; for (unsigned i = 0; i < NumStaticEntries; i++) { if (!static_[i].match(Key())) { if (predicate(static_[i].key, static_[i].value)) { num_removed++; static_[i] = KVPair(); } } } KVGroup* p = list_.get(); while (p) { for (int i = 0; i < KVGroup::NumKV; i++) { const KVPair* const kv = p->kvs + i; if (!kv->match(Key())) { if (predicate(kv->key, kv->value)) { num_removed++; p->kvs[i] = KVPair(); } } } p = p->getNextListNode(); } if (num_removed > 0) { optimizeStorage(); compact(); } } template <typename Key, typename Value, unsigned NumStaticEntries> template <typename Predicate> const Key* Map<Key, Value, NumStaticEntries>::findFirstKey(Predicate predicate) const { for (unsigned i = 0; i < NumStaticEntries; i++) { if (!static_[i].match(Key())) { if (predicate(static_[i].key, static_[i].value)) { return &static_[i].key; } } } KVGroup* p = list_.get(); while (p) { for (int i = 0; i < KVGroup::NumKV; i++) { const KVPair* const kv = p->kvs + i; if (!kv->match(Key())) { if (predicate(kv->key, kv->value)) { return &p->kvs[i].key; } } } p = p->getNextListNode(); } return NULL; } template <typename Key, typename Value, unsigned NumStaticEntries> void Map<Key, Value, NumStaticEntries>::removeAll() { removeWhere(YesPredicate()); } template <typename Key, typename Value, unsigned NumStaticEntries> bool Map<Key, Value, NumStaticEntries>::isEmpty() const { return (getNumStaticPairs() == 0) && (getNumDynamicPairs() == 0); } template <typename Key, typename Value, unsigned NumStaticEntries> unsigned Map<Key, Value, NumStaticEntries>::getNumStaticPairs() const { unsigned num = 0; for (unsigned i = 0; i < NumStaticEntries; i++) { if (!static_[i].match(Key())) { num++; } } return num; } template <typename Key, typename Value, unsigned NumStaticEntries> unsigned Map<Key, Value, NumStaticEntries>::getNumDynamicPairs() const { unsigned num = 0; KVGroup* p = list_.get(); while (p) { for (int i = 0; i < KVGroup::NumKV; i++) { const KVPair* const kv = p->kvs + i; if (!kv->match(Key())) { num++; } } p = p->getNextListNode(); } return num; } } <|endoftext|>
<commit_before>#include <cstdio> #include <vector> #include <ctime> #include <algorithm> #include <iterator> #include <fstream> // include & define dependent libraries and types #include <map> #include <utility> typedef struct { float left, top, right, bottom; } rect_t; typedef struct { float v1, v2, v3, v4; } com_t; // include the mamdani matrix generated with gen_cleaned.pl #include <mamdani.ixx> static inline float pDistance(std::pair<float, float> a, std::pair<float, float> b, float maxDistance2 = 1.41f) { __declspec(align(16)) float va[4] = { 0.f, 0.f, a.second, a.first, }; __declspec(align(16)) float vb[4] = { 0.f, 0.f, b.second, b.first, }; __m128 reg1 = _mm_load_ps(va); __m128 reg2 = _mm_load_ps(vb); reg1 = _mm_sub_ps(reg1, reg2); reg2 = reg1; reg1 = _mm_mul_ps(reg1, reg2); _mm_store_ps(va, reg1); float temp = va[2] + va[3]; return temp; #if 0 float temp = (va[2] + va[3]) / maxDistance2; if (temp > maxDistance2) return 1; else return temp / maxDistance2; #endif } int main(int argc, char* argv[]) { // time i/o separately since it takes a while volatile clock_t cstartio = clock(); #pragma warning(disable:4996) FILE* f = fopen("date.txt", "r"); //std::fstream g("output.txt", std::ios::out); FILE* g = fopen("output.txt", "w"); // store the input in a vector for faster processing std::vector<float> inputs; inputs.reserve(10002); while (!feof(f)) { float d; fscanf(f, "%f", &d); inputs.push_back(d); } #ifdef STRESS_TEST inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); #endif std::vector<float> outputs(inputs.size()); volatile clock_t cstopio = clock(); volatile double spentio = (double)(cstopio - cstartio) / CLOCKS_PER_SEC; printf("Took %lfs to _read_ %ld values\n", spentio, inputs.size()); // time the computation volatile clock_t cstart = clock(); // state variables float lastErr = 0.0; // previous error; initially 0 auto func = [&](float err) -> float { // compute the derivate of the error using the previous value float derr = err - lastErr; // locate the partition the current point falls in auto found = std::find_if(g_mamdani.begin(), g_mamdani.end(), [&derr, &err](decltype(g_mamdani.front())& o) -> bool { return o.first.left <= err && o.first.right > err && o.first.top <= derr && o.first.bottom > derr; }); float val = 0.0; if (found != g_mamdani.end()) { #ifdef BILINEAR_INTERPOLATION // setup values float errUnit = (err - found->first.left) / g_extents[0]; float derrUnit = (derr - found->first.top) / g_extents[1]; // use trigonometric interpolation auto l = [](float t) -> float { //return 1 - powf(1 - t, 1.392f); //return 1 - powf(1 - t, 5.f/4.f); return 1.f - tanf(3.14159f / 4.f * (1 - t)); }; errUnit = l(errUnit); derrUnit = l(errUnit); //errUnit = sinf(errUnit * 3.14159f/2.f); //derrUnit = sinf(derrUnit * 3.14159f/2.f); static __declspec(align(16)) float leftTerms[4] = { 1.f, 0.f, 1.f, 0.f }; __declspec(align(16)) float va[4] = { -errUnit, errUnit, -errUnit, errUnit }; static __declspec(align(16)) float rightTerms[4] = { 1.f, 1.f, 0.f, 0.f }; __declspec(align(16)) float vb[4] = { -derrUnit, -derrUnit, derrUnit, derrUnit }; // computations __m128 reg1, reg2, reg3; reg1 = _mm_load_ps(leftTerms); reg3 = _mm_load_ps(va); reg1 = _mm_add_ps(reg1, reg3); reg2 = _mm_load_ps(rightTerms); reg3 = _mm_load_ps(vb); reg2 = _mm_add_ps(reg2, reg3); reg1 = _mm_mul_ps(reg1, reg2); memcpy(va, (float*)(&found->second), 4 * sizeof(float)); reg2 = _mm_load_ps(va); reg1 = _mm_mul_ps(reg1, reg2); _mm_store_ps(va, reg1); val = va[0] + va[1] + va[2] + va[3]; #else // inverse distance weighting // (v[i] * (1-d[i]) / (1-d[i]) __declspec(align(16)) float va[4]; memcpy(va, (float*)&(found->second), 4 * sizeof(float)); std::pair<float, float> p(err, derr); std::pair<float, float> c1(found->first.left, found->first.top), c2(found->first.right, found->first.top), c3(found->first.left, found->first.bottom), c4(found->first.right, found->first.bottom); __declspec(align(16)) float vb[4] = { pDistance(c1, p), pDistance(c2, p), pDistance(c3, p), pDistance(c4, p), }; for (size_t i = 0; i < 4; ++i) { if (vb[i] < 1.0e-7f) { val = va[i]; goto done; } else { vb[i] = powf(vb[i], 1.f/1.8f); } } __m128 reg1, reg2; // compute weights static __declspec(align(16)) float ones[4] = { 1.f, 1.f, 1.f, 1.f }; // -- fiddle with the distances reg1 = _mm_load_ps(vb); //reg1 = _mm_sqrt_ps(reg1); //reg1 = _mm_mul_ps(reg1, reg1); // -- subtract from 1 reg2 = _mm_load_ps(ones); reg2 = _mm_div_ps(reg2, reg1); // multiply the values reg1 = _mm_load_ps(va); reg1 = _mm_mul_ps(reg1, reg2); // retrieve the values _mm_store_ps(va, reg1); _mm_store_ps(vb, reg2); // compute final value __declspec(align(16)) float vc[8] = { va[0], va[1], vb[0], vb[1], va[2], va[3], vb[2], vb[3], }; reg1 = _mm_load_ps(vc); reg2 = _mm_load_ps(vc + 4); reg1 = _mm_add_ps(reg1, reg2); _mm_store_ps(va, reg1); val = (va[0] + va[1]) / (va[2] + va[3]); #endif } done: // update state lastErr = err; // store the result return val; }; // process all inputs with our stateful function std::transform(inputs.begin(), inputs.end(), outputs.begin(), func); volatile clock_t cend = clock(); // report spent time volatile double spent = (double)(cend - cstart) / CLOCKS_PER_SEC; printf("Took %lfs to process %ld values\n", spent, inputs.size()); // time the output separately cstartio = clock(); //std::copy(outputs.begin(), outputs.end(), std::ostream_iterator<float>(g, "\n")); lastErr = 0; for (size_t i = 0; i < inputs.size(); ++i) { fprintf(g, "%10.6f, %10.6f => %10.6f\n", inputs[i], inputs[i] - lastErr, outputs[i]); lastErr = inputs[i]; } cstopio = clock(); spentio = (double)(cstopio - cstartio) / CLOCKS_PER_SEC; printf("Took %lfs to write %ld values to disk\n", spentio, outputs.size()); return 0; }<commit_msg>if I round at 2 decimals, the results are spot on<commit_after>#include <cstdio> #include <vector> #include <ctime> #include <algorithm> #include <iterator> #include <fstream> // include & define dependent libraries and types #include <map> #include <utility> typedef struct { float left, top, right, bottom; } rect_t; typedef struct { float v1, v2, v3, v4; } com_t; // include the mamdani matrix generated with gen_cleaned.pl #include <mamdani.ixx> static inline float pDistance(std::pair<float, float> a, std::pair<float, float> b, float maxDistance2 = 1.41f) { __declspec(align(16)) float va[4] = { 0.f, 0.f, a.second, a.first, }; __declspec(align(16)) float vb[4] = { 0.f, 0.f, b.second, b.first, }; __m128 reg1 = _mm_load_ps(va); __m128 reg2 = _mm_load_ps(vb); reg1 = _mm_sub_ps(reg1, reg2); reg2 = reg1; reg1 = _mm_mul_ps(reg1, reg2); _mm_store_ps(va, reg1); #if 1 float temp = va[2] + va[3]; return temp; #else float temp = (va[2] + va[3]) / maxDistance2; if (temp > maxDistance2) return 1; else return temp / maxDistance2; #endif } int main(int argc, char* argv[]) { // time i/o separately since it takes a while volatile clock_t cstartio = clock(); #pragma warning(disable:4996) FILE* f = fopen("date.txt", "r"); //std::fstream g("output.txt", std::ios::out); FILE* g = fopen("output.txt", "w"); // store the input in a vector for faster processing std::vector<float> inputs; inputs.reserve(10002); while (!feof(f)) { float d; fscanf(f, "%f", &d); inputs.push_back(d); } #ifdef STRESS_TEST inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); inputs.insert(inputs.end(), inputs.begin(), inputs.end()); #endif std::vector<float> outputs(inputs.size()); volatile clock_t cstopio = clock(); volatile double spentio = (double)(cstopio - cstartio) / CLOCKS_PER_SEC; printf("Took %lfs to _read_ %ld values\n", spentio, inputs.size()); // time the computation volatile clock_t cstart = clock(); // state variables float lastErr = 0.0; // previous error; initially 0 auto func = [&](float err) -> float { // compute the derivate of the error using the previous value float derr = err - lastErr; // locate the partition the current point falls in auto found = std::find_if(g_mamdani.begin(), g_mamdani.end(), [&derr, &err](decltype(g_mamdani.front())& o) -> bool { return o.first.left <= err && o.first.right > err && o.first.top <= derr && o.first.bottom > derr; }); float val = 0.0; if (found != g_mamdani.end()) { #ifdef BILINEAR_INTERPOLATION // setup values float errUnit = (err - found->first.left) / g_extents[0]; float derrUnit = (derr - found->first.top) / g_extents[1]; // use trigonometric interpolation auto l = [](float t) -> float { //return 1 - powf(1 - t, 1.392f); //return 1 - powf(1 - t, 5.f/4.f); return 1.f - tanf(3.14159f / 4.f * (1 - t)); }; errUnit = l(errUnit); derrUnit = l(errUnit); //errUnit = sinf(errUnit * 3.14159f/2.f); //derrUnit = sinf(derrUnit * 3.14159f/2.f); static __declspec(align(16)) float leftTerms[4] = { 1.f, 0.f, 1.f, 0.f }; __declspec(align(16)) float va[4] = { -errUnit, errUnit, -errUnit, errUnit }; static __declspec(align(16)) float rightTerms[4] = { 1.f, 1.f, 0.f, 0.f }; __declspec(align(16)) float vb[4] = { -derrUnit, -derrUnit, derrUnit, derrUnit }; // computations __m128 reg1, reg2, reg3; reg1 = _mm_load_ps(leftTerms); reg3 = _mm_load_ps(va); reg1 = _mm_add_ps(reg1, reg3); reg2 = _mm_load_ps(rightTerms); reg3 = _mm_load_ps(vb); reg2 = _mm_add_ps(reg2, reg3); reg1 = _mm_mul_ps(reg1, reg2); memcpy(va, (float*)(&found->second), 4 * sizeof(float)); reg2 = _mm_load_ps(va); reg1 = _mm_mul_ps(reg1, reg2); _mm_store_ps(va, reg1); val = va[0] + va[1] + va[2] + va[3]; #else // inverse distance weighting // (v[i] * (1-d[i]) / (1-d[i]) __declspec(align(16)) float va[4]; memcpy(va, (float*)&(found->second), 4 * sizeof(float)); std::pair<float, float> p((err - found->first.left)/g_extents[0], (derr - found->first.top)/g_extents[1]); std::pair<float, float> c1(0.f, 0.f), c2(1.f, 0.f), c3(0.f, 1.f), c4(1.f, 1.f); __declspec(align(16)) float vb[4] = { pDistance(c1, p), pDistance(c2, p), pDistance(c3, p), pDistance(c4, p), }; for (size_t i = 0; i < 4; ++i) { if (vb[i] < 1.0e-7f) { val = va[i]; goto done; } else { //vb[i] = powf(vb[i], 1.f/1.85f); vb[i] = powf(vb[i], 1.f / 1.857f); } } __m128 reg1, reg2; // compute weights static __declspec(align(16)) float ones[4] = { 1.f, 1.f, 1.f, 1.f }; // -- fiddle with the distances reg1 = _mm_load_ps(vb); //reg1 = _mm_sqrt_ps(reg1); //reg1 = _mm_mul_ps(reg1, reg1); // -- invert reg2 = _mm_load_ps(ones); reg2 = _mm_div_ps(reg2, reg1); // multiply the values reg1 = _mm_load_ps(va); reg1 = _mm_mul_ps(reg1, reg2); // retrieve the values _mm_store_ps(va, reg1); _mm_store_ps(vb, reg2); // compute final value __declspec(align(16)) float vc[8] = { va[0], va[1], vb[0], vb[1], va[2], va[3], vb[2], vb[3], }; reg1 = _mm_load_ps(vc); reg2 = _mm_load_ps(vc + 4); reg1 = _mm_add_ps(reg1, reg2); _mm_store_ps(va, reg1); val = (va[0] + va[1]) / (va[2] + va[3]); #endif } done: // update state lastErr = err; // store the result return val; }; // process all inputs with our stateful function std::transform(inputs.begin(), inputs.end(), outputs.begin(), func); volatile clock_t cend = clock(); // report spent time volatile double spent = (double)(cend - cstart) / CLOCKS_PER_SEC; printf("Took %lfs to process %ld values\n", spent, inputs.size()); // time the output separately cstartio = clock(); //std::copy(outputs.begin(), outputs.end(), std::ostream_iterator<float>(g, "\n")); lastErr = 0; for (size_t i = 0; i < inputs.size(); ++i) { //fprintf(g, "%10.6f, %10.6f => %10.6f\n", inputs[i], inputs[i] - lastErr, outputs[i]); fprintf(g, "%10.6f, %10.6f => %6.2f\n", inputs[i], inputs[i] - lastErr, outputs[i]); lastErr = inputs[i]; } cstopio = clock(); spentio = (double)(cstopio - cstartio) / CLOCKS_PER_SEC; printf("Took %lfs to write %ld values to disk\n", spentio, outputs.size()); return 0; }<|endoftext|>
<commit_before>void MUONdigit (Int_t evNumber1=0, Int_t evNumber2=0, Int_t ibg=1, Int_t bgr=10) { // Dynamically link some shared libs if (gClassTable->GetID("AliRun") < 0) { gROOT->LoadMacro("loadlibs.C"); loadlibs(); } // Connect the Root Galice file containing Geometry, Kine and Hits TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject("galice.root"); if (file) file->Close(); file = new TFile("galice.root","UPDATE"); // Get AliRun object from file or create it if not on file if (!gAlice) { gAlice = (AliRun*)file->Get("gAlice"); if (gAlice) printf("AliRun object found on file\n"); if (!gAlice) gAlice = new AliRun("gAlice","Alice test program"); } AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON"); if (pMUON) { // creation AliMUONMerger* merger = new AliMUONMerger(); // configuration merger->SetMode(0); merger->SetSignalEventNumber(0); merger->SetBackgroundEventNumber(0); merger->SetBackgroundFileName("bg.root"); // pass pMUON->SetMerger(merger); } // Action ! // // Loop over events // for (int nev=evNumber1; nev<= evNumber2; nev++) { Int_t nparticles = gAlice->GetEvent(nev); cout << "nev " << nev <<endl; cout << "nparticles " << nparticles <<endl; if (nev < evNumber1) continue; if (nparticles <= 0) return; gAlice->SDigits2Digits(); char hname[30]; sprintf(hname,"TreeD%d",nev); gAlice->TreeD()->Write(hname); // reset tree gAlice->TreeD()->Reset(); } // event loop } <commit_msg>Calculate and pass current background event number.<commit_after>void MUONdigit (Int_t evNumber1=0, Int_t evNumber2=0, Int_t ibg=0, Int_t bgr=10) { // Dynamically link some shared libs if (gClassTable->GetID("AliRun") < 0) { gROOT->LoadMacro("loadlibs.C"); loadlibs(); } // Connect the Root Galice file containing Geometry, Kine and Hits TFile *file = (TFile*)gROOT->GetListOfFiles()->FindObject("galice.root"); if (file) file->Close(); file = new TFile("galice.root","UPDATE"); // Get AliRun object from file or create it if not on file if (!gAlice) { gAlice = (AliRun*)file->Get("gAlice"); if (gAlice) printf("AliRun object found on file\n"); if (!gAlice) gAlice = new AliRun("gAlice","Alice test program"); } AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON"); if (pMUON) { // creation AliMUONMerger* merger = new AliMUONMerger(); // configuration if (ibg) { merger->SetMode(ibg); merger->SetBackgroundFileName("bg.root"); } // pass pMUON->SetMerger(merger); } // Action ! // // Loop over events // for (int nev=evNumber1; nev<= evNumber2; nev++) { Int_t nparticles = gAlice->GetEvent(nev); cout << "nev " << nev <<endl; cout << "nparticles " << nparticles <<endl; if (nev < evNumber1) continue; if (nparticles <= 0) return; Int_t nbgr_ev = Int_t(nev*bgr/(evNumber2+1)); if (ibg) { merger->SetBackgroundEventNumber(nbgr_ev); } gAlice->SDigits2Digits(); char hname[30]; sprintf(hname,"TreeD%d",nev); gAlice->TreeD()->Write(hname); // reset tree gAlice->TreeD()->Reset(); } // event loop } <|endoftext|>
<commit_before>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <QDateTime> #include <QString> #include <QVariantMap> #include <TelepathyQt4/Account> #include <TelepathyQt4/AbstractClientHandler> #include <TelepathyQt4/Channel> #include <TelepathyQt4/ChannelRequest> #include <TelepathyQt4/ClientRegistrar> #include <TelepathyQt4/Connection> #include <TelepathyQt4/Debug> #include <TelepathyQt4/PendingClientOperation> #include <TelepathyQt4/Types> #include <telepathy-glib/debug.h> #include <glib-object.h> #include <dbus/dbus-glib.h> #include <tests/lib/test.h> using namespace Tp; class MyHandler : public AbstractClientHandler { public: MyHandler(const ChannelClassList &channelFilter, bool bypassApproval = false, bool listenRequests = false) : AbstractClientHandler(channelFilter, listenRequests), mBypassApproval(bypassApproval) { } ~MyHandler() { } bool bypassApproval() const { return mBypassApproval; } QList<ChannelPtr> handledChannels() const { return mHandledChannels; } void handleChannels(PendingClientOperation *operation, const AccountPtr &account, const ConnectionPtr &connection, const QList<ChannelPtr> &channels, const QList<ChannelRequestPtr> &requestsSatisfied, const QDateTime &userActionTime, const QVariantMap &handlerInfo) { mHandleChannelsAccount = account; mHandleChannelsConnection = connection; mHandleChannelsChannels = channels; mHandleChannelsRequestsSatisfied = requestsSatisfied; mHandleChannelsUserActionTime = userActionTime; mHandleChannelsHandlerInfo = handlerInfo; mHandledChannels.append(channels); operation->setFinished(); } void addRequest(const ChannelRequestPtr &request) { mAddRequestRequest = request; } void removeRequest(const ChannelRequestPtr &request, const QString &errorName, const QString &errorMessage) { mRemoveRequestRequest = request; mRemoveRequestErrorName = errorName; mRemoveRequestErrorMessage = errorMessage; } bool mBypassApproval; AccountPtr mHandleChannelsAccount; ConnectionPtr mHandleChannelsConnection; QList<ChannelPtr> mHandleChannelsChannels; QList<ChannelRequestPtr> mHandleChannelsRequestsSatisfied; QDateTime mHandleChannelsUserActionTime; QVariantMap mHandleChannelsHandlerInfo; QList<ChannelPtr> mHandledChannels; ChannelRequestPtr mAddRequestRequest; ChannelRequestPtr mRemoveRequestRequest; QString mRemoveRequestErrorName; QString mRemoveRequestErrorMessage; }; class TestClientHandler : public Test { Q_OBJECT public: TestClientHandler(QObject *parent = 0) : Test(parent) { } private Q_SLOTS: void initTestCase(); void init(); void testRegister(); void cleanup(); void cleanupTestCase(); private: ClientRegistrarPtr mClientRegistrar; }; void TestClientHandler::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("client-handler"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); mClientRegistrar = ClientRegistrar::create("foo"); } void TestClientHandler::init() { initImpl(); } void TestClientHandler::testRegister() { ChannelClassList filters; QMap<QString, QDBusVariant> filter; filter.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QDBusVariant(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT)); filter.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), QDBusVariant(Tp::HandleTypeContact)); filters.append(filter); SharedPtr<MyHandler> myHandler = SharedPtr<MyHandler>( new MyHandler(filters)); mClientRegistrar->registerClient(AbstractClientPtr::dynamicCast(myHandler)); QDBusConnection bus = mClientRegistrar->dbusConnection(); QDBusConnectionInterface *iface = bus.interface(); QStringList registeredServicesNames = iface->registeredServiceNames(); QVERIFY(registeredServicesNames.contains( "org.freedesktop.Telepathy.Client.foo")); } void TestClientHandler::cleanup() { cleanupImpl(); } void TestClientHandler::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestClientHandler) #include "_gen/client-handler.cpp.moc.hpp" <commit_msg>client-handler test: Added test to AddRequest/RemoveRequest.<commit_after>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <QDateTime> #include <QString> #include <QVariantMap> #include <TelepathyQt4/Account> #include <TelepathyQt4/AccountManager> #include <TelepathyQt4/AbstractClientHandler> #include <TelepathyQt4/Channel> #include <TelepathyQt4/ChannelRequest> #include <TelepathyQt4/ClientHandlerInterface> #include <TelepathyQt4/ClientInterfaceRequestsInterface> #include <TelepathyQt4/ClientRegistrar> #include <TelepathyQt4/Connection> #include <TelepathyQt4/Debug> #include <TelepathyQt4/PendingAccount> #include <TelepathyQt4/PendingClientOperation> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/Types> #include <telepathy-glib/debug.h> #include <glib-object.h> #include <dbus/dbus-glib.h> #include <tests/lib/contacts-conn.h> #include <tests/lib/echo/chan.h> #include <tests/lib/test.h> using namespace Tp; using namespace Tp::Client; class ChannelRequestAdaptor : public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.freedesktop.Telepathy.ChannelRequest") Q_CLASSINFO("D-Bus Introspection", "" " <interface name=\"org.freedesktop.Telepathy.ChannelRequest\" >\n" " <property name=\"Account\" type=\"o\" access=\"read\" />\n" " <property name=\"UserActionTime\" type=\"x\" access=\"read\" />\n" " <property name=\"PreferredHandler\" type=\"s\" access=\"read\" />\n" " <property name=\"Requests\" type=\"aa{sv}\" access=\"read\" />\n" " <property name=\"Interfaces\" type=\"as\" access=\"read\" />\n" " <method name=\"Proceed\" />\n" " <method name=\"Cancel\" />\n" " <signal name=\"Failed\" >\n" " <arg name=\"Error\" type=\"s\" />\n" " <arg name=\"Message\" type=\"s\" />\n" " </signal>\n" " <signal name=\"Succeeded\" />" " </interface>\n" "") Q_PROPERTY(QDBusObjectPath Account READ Account) Q_PROPERTY(qulonglong UserActionTime READ UserActionTime) Q_PROPERTY(QString PreferredHandler READ PreferredHandler) Q_PROPERTY(QualifiedPropertyValueMapList Requests READ Requests) Q_PROPERTY(QStringList Interfaces READ Interfaces) public: ChannelRequestAdaptor(QDBusObjectPath account, qulonglong userActionTime, QString preferredHandler, QualifiedPropertyValueMapList requests, QStringList interfaces, QObject *parent) : QDBusAbstractAdaptor(parent), mAccount(account), mUserActionTime(userActionTime), mPreferredHandler(preferredHandler), mRequests(requests), mInterfaces(interfaces) { } virtual ~ChannelRequestAdaptor() { } public: // Properties inline QDBusObjectPath Account() const { return mAccount; } inline qulonglong UserActionTime() const { return mUserActionTime; } inline QString PreferredHandler() const { return mPreferredHandler; } inline QualifiedPropertyValueMapList Requests() const { return mRequests; } inline QStringList Interfaces() const { return mInterfaces; } public Q_SLOTS: // Methods void Proceed() { } void Cancel() { } Q_SIGNALS: // Signals void Failed(const QString &error, const QString &message); void Succeeded(); private: QDBusObjectPath mAccount; qulonglong mUserActionTime; QString mPreferredHandler; QualifiedPropertyValueMapList mRequests; QStringList mInterfaces; }; class MyHandler : public AbstractClientHandler { Q_OBJECT public: MyHandler(const ChannelClassList &channelFilter, bool bypassApproval = false, bool listenRequests = false) : AbstractClientHandler(channelFilter, listenRequests), mBypassApproval(bypassApproval) { } ~MyHandler() { } bool bypassApproval() const { return mBypassApproval; } QList<ChannelPtr> handledChannels() const { return mHandledChannels; } void handleChannels(PendingClientOperation *operation, const AccountPtr &account, const ConnectionPtr &connection, const QList<ChannelPtr> &channels, const QList<ChannelRequestPtr> &requestsSatisfied, const QDateTime &userActionTime, const QVariantMap &handlerInfo) { mHandleChannelsAccount = account; mHandleChannelsConnection = connection; mHandleChannelsChannels = channels; mHandleChannelsRequestsSatisfied = requestsSatisfied; mHandleChannelsUserActionTime = userActionTime; mHandleChannelsHandlerInfo = handlerInfo; mHandledChannels.append(channels); operation->setFinished(); } void addRequest(const ChannelRequestPtr &request) { mAddRequestRequest = request; emit requestAdded(request); } void removeRequest(const ChannelRequestPtr &request, const QString &errorName, const QString &errorMessage) { mRemoveRequestRequest = request; mRemoveRequestErrorName = errorName; mRemoveRequestErrorMessage = errorMessage; emit requestRemoved(request, errorName, errorMessage); } bool mBypassApproval; AccountPtr mHandleChannelsAccount; ConnectionPtr mHandleChannelsConnection; QList<ChannelPtr> mHandleChannelsChannels; QList<ChannelRequestPtr> mHandleChannelsRequestsSatisfied; QDateTime mHandleChannelsUserActionTime; QVariantMap mHandleChannelsHandlerInfo; QList<ChannelPtr> mHandledChannels; ChannelRequestPtr mAddRequestRequest; ChannelRequestPtr mRemoveRequestRequest; QString mRemoveRequestErrorName; QString mRemoveRequestErrorMessage; Q_SIGNALS: void requestAdded(const Tp::ChannelRequestPtr &request); void requestRemoved(const Tp::ChannelRequestPtr &request, const QString &errorName, const QString &errorMessage); }; class TestClientHandler : public Test { Q_OBJECT public: TestClientHandler(QObject *parent = 0) : Test(parent), mConnService(0), mBaseConnService(0), mContactRepo(0), mTextChanService(0) { } protected Q_SLOTS: void expectRequestChange(); private Q_SLOTS: void initTestCase(); void init(); void testRegister(); void testRequests(); void cleanup(); void cleanupTestCase(); private: ContactsConnection *mConnService; TpBaseConnection *mBaseConnService; TpHandleRepoIface *mContactRepo; ExampleEchoChannel *mTextChanService; AccountManagerPtr mAM; AccountPtr mAccount; ConnectionPtr mConn; QString mTextChanPath; QString mConnName; QString mConnPath; ClientRegistrarPtr mClientRegistrar; QString mChannelRequestBusName; QString mChannelRequestPath; SharedPtr<MyHandler> mHandler; QString mHandlerBusName; QString mHandlerPath; }; void TestClientHandler::expectRequestChange() { mLoop->exit(0); } void TestClientHandler::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("client-handler"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); mAM = AccountManager::create(); QVERIFY(connect(mAM->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAM->isReady(), true); QVariantMap parameters; parameters["account"] = "foobar"; PendingAccount *pacc = mAM->createAccount("foo", "bar", "foobar", parameters); QVERIFY(connect(pacc, SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(pacc->account()); mAccount = pacc->account(); gchar *name; gchar *connPath; GError *error = 0; mConnService = CONTACTS_CONNECTION(g_object_new( CONTACTS_TYPE_CONNECTION, "account", "[email protected]", "protocol", "example", 0)); QVERIFY(mConnService != 0); mBaseConnService = TP_BASE_CONNECTION(mConnService); QVERIFY(mBaseConnService != 0); QVERIFY(tp_base_connection_register(mBaseConnService, "example", &name, &connPath, &error)); QVERIFY(error == 0); QVERIFY(name != 0); QVERIFY(connPath != 0); mConnName = QString::fromAscii(name); mConnPath = QString::fromAscii(connPath); g_free(name); g_free(connPath); mConn = Connection::create(mConnName, mConnPath); QCOMPARE(mConn->isReady(), false); mConn->requestConnect(); QVERIFY(connect(mConn->requestConnect(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mConn->isReady(), true); QCOMPARE(static_cast<uint>(mConn->status()), static_cast<uint>(Connection::StatusConnected)); // create a Channel by magic, rather than doing D-Bus round-trips for it mContactRepo = tp_base_connection_get_handles(mBaseConnService, TP_HANDLE_TYPE_CONTACT); guint handle = tp_handle_ensure(mContactRepo, "someone@localhost", 0, 0); mTextChanPath = mConnPath + QLatin1String("/TextChannel"); QByteArray chanPath(mTextChanPath.toAscii()); mTextChanService = EXAMPLE_ECHO_CHANNEL(g_object_new( EXAMPLE_TYPE_ECHO_CHANNEL, "connection", mConnService, "object-path", chanPath.data(), "handle", handle, NULL)); tp_handle_unref(mContactRepo, handle); mClientRegistrar = ClientRegistrar::create("foo"); QDBusConnection bus = mClientRegistrar->dbusConnection(); mChannelRequestBusName = "org.freedesktop.Telepathy.ChannelDispatcher"; mChannelRequestPath = "/org/freedesktop/Telepathy/ChannelRequest/Request1"; QObject *request = new QObject(this); uint userActionTime = QDateTime::currentDateTime().toTime_t(); new ChannelRequestAdaptor(QDBusObjectPath(mAccount->objectPath()), userActionTime, QString(), QualifiedPropertyValueMapList(), QStringList(), request); QVERIFY(bus.registerService(mChannelRequestBusName)); QVERIFY(bus.registerObject(mChannelRequestPath, request)); } void TestClientHandler::init() { initImpl(); } void TestClientHandler::testRegister() { ChannelClassList filters; QMap<QString, QDBusVariant> filter; filter.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QDBusVariant(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT)); filter.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), QDBusVariant(Tp::HandleTypeContact)); filters.append(filter); mHandler = SharedPtr<MyHandler>( new MyHandler(filters, false, true)); mClientRegistrar->registerClient(AbstractClientPtr::dynamicCast(mHandler)); QDBusConnection bus = mClientRegistrar->dbusConnection(); QDBusConnectionInterface *busIface = bus.interface(); QStringList registeredServicesNames = busIface->registeredServiceNames(); QVERIFY(registeredServicesNames.contains( "org.freedesktop.Telepathy.Client.foo")); mHandlerBusName = "org.freedesktop.Telepathy.Client.foo"; mHandlerPath = "/org/freedesktop/Telepathy/Client/foo"; } void TestClientHandler::testRequests() { QDBusConnection bus = mClientRegistrar->dbusConnection(); ClientInterfaceRequestsInterface *handlerRequestsIface = new ClientInterfaceRequestsInterface(bus, mHandlerBusName, mHandlerPath, this); connect(mHandler.data(), SIGNAL(requestAdded(const Tp::ChannelRequestPtr &)), SLOT(expectRequestChange())); handlerRequestsIface->AddRequest(QDBusObjectPath(mChannelRequestPath), QVariantMap()); if (!mHandler->mAddRequestRequest) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mHandler->mAddRequestRequest->objectPath(), mChannelRequestPath); connect(mHandler.data(), SIGNAL(requestRemoved(const Tp::ChannelRequestPtr &, const QString &, const QString &)), SLOT(expectRequestChange())); handlerRequestsIface->RemoveRequest(QDBusObjectPath(mChannelRequestPath), TELEPATHY_ERROR_NOT_AVAILABLE, "Not available"); if (!mHandler->mRemoveRequestRequest) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mHandler->mRemoveRequestRequest->objectPath(), mChannelRequestPath); QCOMPARE(mHandler->mRemoveRequestErrorName, QString(TELEPATHY_ERROR_NOT_AVAILABLE)); QCOMPARE(mHandler->mRemoveRequestErrorMessage, QString("Not available")); } void TestClientHandler::cleanup() { cleanupImpl(); } void TestClientHandler::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestClientHandler) #include "_gen/client-handler.cpp.moc.hpp" <|endoftext|>
<commit_before>#ifndef SDL_CONFIG_HH #define SDL_CONFIG_HH //Forced Config //#undef HAVE_OPENGL //engine call seems to work... 3D part postponed... #undef THREAD //Normal Setup #define DEFAULT_DISPLAY_WIDTH 640 #define DEFAULT_DISPLAY_HEIGHT 480 #define DEFAULT_DISPLAY_BPP 0 //0 for current display pixel mode //beware ! 0 only usable for Display Surface, not for RGB ones !! #define DEFAULT_WINDOW_TITLE "RAGE::SDL" //Mandatory #include <SDL.h> //Mandatory because we use RWOps for the wrapper, and we even wrap it #include <SDL_rwops.h> //Mandatory because we also wrap OpenGL //TODO : NO_OPENGL option in build #include <SDL_opengl.h> //Might be needed //#if defined(WIN32) && !defined(GL_BGR) //#define GL_BGR GL_BGR_EXT //#endif //Conditionals #ifdef HAVE_SDLIMAGE #include "SDL_image.h" #endif #ifdef HAVE_SDLNET #include "SDL_net.h" #endif #ifdef HAVE_SDLTTF #include "SDL_ttf.h" #endif #ifdef THREAD #include <SDL_thread.h> #endif #if SDL_VERSION_ATLEAST(1, 2, 7) #include "SDL_cpuinfo.h" #endif //utils #include <iostream> #include <string> #include <sstream> #include <stdexcept> #include <vector> #include "Logger.hh" #ifdef DEBUG #include <cassert> #endif //REMINDER : For audio, (SDL_mixer) have alook at http://gameprogrammer.com/gpwiki/Audio_lib /** * \class Version * * \ingroup General * * \brief This class provides access to both linked and compiled SDL versions and specific CPU features check... * * \author Alex * * \date 2005/12/26 * * Contact: [email protected] * */ namespace RAGE { namespace SDL { //global, namespace visible, declaration : extern Logger Log; //list of supported optional modules... //if those modules are used and there are not linked with RAGE::SDL, an error message will be returned. typedef enum { Main ,Image ,Net }Module; std::string GetError(Module = Main); namespace TTF{ //declaring the bridge class to access TTF features class Font; std::string GetError(); //maybe derivate from SDL::Version ? class Version { SDL_version _compiled; SDL_version _linked; public: Version(); ~Version(); //Version is 0.0.0 if not available for some reason ( not compiled with or not linked ) int getcompiledmajor() const; int getcompiledminor() const; int getcompiledpatch() const; int getlinkedmajor() const; int getlinkedminor() const; int getlinkedpatch() const; //return true if linked and compiled version are not null and matches exactly bool isValid() const; //return true if linked is not null and superior or equal to compiled bool isSupported() const; //Display the version. Usefull for debugging purpose... friend Logger & operator << (Logger& log, const Version & v); }; //checks if compiled Version is different from 0.0.0 bool isCompiled(); //checks if linked version is different from 0.0.0 bool isLinked(); } class Version { SDL_version _compiled; SDL_version _linked; public: Version(); ~Version(); int getcompiledmajor() const; int getcompiledminor() const; int getcompiledpatch() const; int getlinkedmajor() const; int getlinkedminor() const; int getlinkedpatch() const; //check if link and compiled matches bool check() const; friend Logger & operator << (Logger& log, const Version & v); }; #if SDL_VERSION_ATLEAST(1, 2, 7) class CPU { public: static bool hasRDTSC(); static bool hasMMX(); static bool hasMMXExt(); static bool has3DNow(); static bool has3DNowExt(); //static bool hasSSE(); //static bool hasSSEExt(); static bool hasAltiVec(); }; #endif } } #endif <commit_msg>fixes for GCC on BSD...<commit_after>#ifndef SDL_CONFIG_HH #define SDL_CONFIG_HH //Forced Config //#undef HAVE_OPENGL //engine call seems to work... 3D part postponed... #undef THREAD //Normal Setup #define DEFAULT_DISPLAY_WIDTH 640 #define DEFAULT_DISPLAY_HEIGHT 480 #define DEFAULT_DISPLAY_BPP 0 //0 for current display pixel mode //beware ! 0 only usable for Display Surface, not for RGB ones !! #define DEFAULT_WINDOW_TITLE "RAGE::SDL" //Mandatory #include <SDL.h> //Mandatory because we use RWOps for the wrapper, and we even wrap it #include <SDL_rwops.h> #ifdef HAVE_OPENGL #include <SDL_opengl.h> #endif //Might be needed //#if defined(WIN32) && !defined(GL_BGR) //#define GL_BGR GL_BGR_EXT //#endif //Conditionals #ifdef HAVE_SDLIMAGE #include "SDL_image.h" #endif #ifdef HAVE_SDLNET #include "SDL_net.h" #endif #ifdef HAVE_SDLTTF #include "SDL_ttf.h" #endif #ifdef THREAD #include <SDL_thread.h> #endif #if SDL_VERSION_ATLEAST(1, 2, 7) #include "SDL_cpuinfo.h" #endif //utils #include <iostream> #include <string> #include <sstream> #include <stdexcept> #include <vector> #include "Logger.hh" #ifdef DEBUG #include <cassert> #endif //REMINDER : For audio, (SDL_mixer) have alook at http://gameprogrammer.com/gpwiki/Audio_lib /** * \class Version * * \ingroup General * * \brief This class provides access to both linked and compiled SDL versions and specific CPU features check... * * \author Alex * * \date 2005/12/26 * * Contact: [email protected] * */ namespace RAGE { namespace SDL { //global, namespace visible, declaration : extern Logger Log; //list of supported optional modules... //if those modules are used and there are not linked with RAGE::SDL, an error message will be returned. typedef enum { Main ,Image ,Net }Module; std::string GetError(Module = Main); namespace TTF{ //declaring the bridge class to access TTF features class Font; std::string GetError(); //maybe derivate from SDL::Version ? class Version { SDL_version _compiled; SDL_version _linked; public: Version(); ~Version(); //Version is 0.0.0 if not available for some reason ( not compiled with or not linked ) int getcompiledmajor() const; int getcompiledminor() const; int getcompiledpatch() const; int getlinkedmajor() const; int getlinkedminor() const; int getlinkedpatch() const; //return true if linked and compiled version are not null and matches exactly bool isValid() const; //return true if linked is not null and superior or equal to compiled bool isSupported() const; //Display the version. Usefull for debugging purpose... friend Logger & operator << (Logger& log, const Version & v); }; //checks if compiled Version is different from 0.0.0 bool isCompiled(); //checks if linked version is different from 0.0.0 bool isLinked(); } class Version { SDL_version _compiled; SDL_version _linked; public: Version(); ~Version(); int getcompiledmajor() const; int getcompiledminor() const; int getcompiledpatch() const; int getlinkedmajor() const; int getlinkedminor() const; int getlinkedpatch() const; //check if link and compiled matches bool check() const; friend Logger & operator << (Logger& log, const Version & v); }; #if SDL_VERSION_ATLEAST(1, 2, 7) class CPU { public: static bool hasRDTSC(); static bool hasMMX(); static bool hasMMXExt(); static bool has3DNow(); static bool has3DNowExt(); //static bool hasSSE(); //static bool hasSSEExt(); static bool hasAltiVec(); }; #endif } } #endif <|endoftext|>
<commit_before>#ifndef CPPUT_TESTHARNESS_HPP #define CPPUT_TESTHARNESS_HPP /////////////////////////////////////////////////////////////////////////////// /// /// \brief A light-weight and easy to use unit testing framework for C++ /// \details Header-only unit testing framework that makes unit testing easy /// and quick to set up. /// \version 0.2.0 /// \date December 2011 /// \author Tommy Back /// /// /// Simply include this header file to get started. /// /// \code /// #include <cpput/TestHarness.h> /// #include <Foo.h> /// /// TEST(Foo, some_descriptive_name) /// { /// // Arrange /// Foo foo; /// // Act /// bool result = foo.isBar(); /// // Assert /// ASSERT_TRUE(result); /// } /// \endcode /// /// In case you want to keep a single file with tests that compile to an /// executable you can also add the main function to the end of the file. /// This is simple to do with the provided macro: /// /// \code /// CPPUT_TEST_MAIN; /// \endcode /// /// For larger test suits, it's recommended to group the tests per class /// in separate files and let the compiler combine them into a single /// executable which has a main.cpp file that only has the main function /// declared. /// /// \example /// [Test_Foo.cpp] /// /// \code /// #include <cpput/TestHarness.h> /// #include <Foo.h> /// /// TEST(Foo, foo_bar_z) /// { /// ... /// \endcode /// /// [main.cpp] /// /// \code /// #include <cpput/TestHarness.h> /// /// CPPUT_TEST_MAIN; /// \endcode /// /// #include <iostream> #include <iomanip> #include <string> #include <sstream> #include <ctime> namespace cpput { struct ResultWriter { virtual ~ResultWriter() {} virtual void startTest(const std::string& className, const std::string& name) = 0; virtual void endTest(bool success) = 0; virtual void failure(const std::string& filename, std::size_t line, const std::string& message) = 0; virtual int getNumberOfFailures() const = 0; }; // ---------------------------------------------------------------------------- class TextResultWriter : public ResultWriter { public: TextResultWriter() : testCount_(0) , failures_(0) { } virtual ~TextResultWriter() { if (failures_ == 0) { std::cout << "\nAll tests pass.\n"; return; } else { std::cout << "\n" << failures_ << " out of " << testCount_ << " tests failed.\n"; } } virtual void startTest(const std::string&, const std::string&) { testCount_++; } virtual void endTest(bool success) { if (success) std::cout << '.'; else std::cout << 'F'; } virtual void failure(const std::string& filename, std::size_t line, const std::string& message) { failures_++; std::cout << "Failure: " << filename << ", line " << line << ": " << message << '\n'; } virtual int getNumberOfFailures() const { return failures_; } private: int testCount_; int failures_; }; // ---------------------------------------------------------------------------- class XmlResultWriter : public ResultWriter { public: XmlResultWriter() : startTime_(0) { std::cout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; std::cout << "<testsuite>\n"; } virtual ~XmlResultWriter() { std::cout << "</testsuite>\n"; } virtual void startTest(const std::string& className, const std::string& name) { startTime_ = std::clock(); std::cout << " <testcase classname=\"" << className << "\" name=\"" << name << "\" time=\""; } virtual void endTest(bool success) { if (success) { std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\""; std::cout << "/>\n"; } else std::cout << " </testcase>\n"; } virtual void failure(const std::string& filename, std::size_t line, const std::string& message) { std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\""; std::cout << ">\n" << " <failure>" << message << " in " << filename << ", line " << line << "</failure>\n"; failureCount_++; } virtual int getNumberOfFailures() const { return failureCount_; } private: std::clock_t startTime_; int failureCount_; }; // ---------------------------------------------------------------------------- struct Result { Result(const std::string& testClassName, const std::string& testName, ResultWriter& out) : out_(out) , pass_(true) { out_.startTest(testClassName, testName); } ~Result() { out_.endTest(pass_); } template <typename T, typename U> void addFailure(const char* filename, std::size_t line, T expected, U actual) { pass_ = false; std::stringstream ss; ss << std::setprecision(20) << "failed comparison, expected " << expected << " got " << actual << "\n"; out_.failure(filename, line, ss.str()); } void addFailure(const char* filename, std::size_t line, const char* message) { pass_ = false; out_.failure(filename, line, message); } ResultWriter& out_; bool pass_; }; // ---------------------------------------------------------------------------- class Repository; class Case { friend class Repository; public: Case(const char* className, const char* name); virtual ~Case() {} void run(ResultWriter& out) { Result result(test_unit_class_name_, test_unit_name_, out); try { do_run(result); } catch (const std::exception& e) { result.addFailure(__FILE__, __LINE__, std::string("Unexpected exception: ").append(e.what()).c_str()); } catch (...) { result.addFailure(__FILE__, __LINE__, "Unspecified exception!"); } } Case* next() { return test_unit_next_; } private: virtual void do_run(Result& testResult_) = 0; private: std::string test_unit_class_name_; std::string test_unit_name_; Case* test_unit_next_; }; // ---------------------------------------------------------------------------- class Repository { public: static Repository& instance() { static Repository repo; return repo; } void add(Case* tc) { if (!cases_) { cases_ = tc; return; } // add as last Case* tmp = cases_; while (tmp->test_unit_next_) tmp = tmp->test_unit_next_; tmp->test_unit_next_ = tc; } Case* getCases() { return cases_; } private: Repository() : cases_(0) {} Repository(const Repository& other); Repository& operator=(const Repository& rhs) const; private: Case* cases_; }; inline Case::Case(const char* className, const char* name) : test_unit_class_name_(className) , test_unit_name_(name) , test_unit_next_(0) { Repository::instance().add(this); } // ---------------------------------------------------------------------------- inline int runAllTests(ResultWriter& writer) { Case* c = Repository::instance().getCases(); while (c) { c->run(writer); c = c->next(); } return writer.getNumberOfFailures(); } } // namespace cpput // Convenience macro to get main function. #define CPPUT_TEST_MAIN \ int main(int argc, char* argv[]) { \ if (argc == 2 && std::string(argv[1]) == "--xml") { \ cpput::XmlResultWriter writer; \ return ::cpput::runAllTests(writer); \ } \ cpput::TextResultWriter writer; \ return ::cpput::runAllTests(writer); \ } // ---------------------------------------------------------------------------- // Test Case Macros // ---------------------------------------------------------------------------- /// Stand-alone test case. /// #define TEST(group,name) \ class group##name##Test : public cpput::Case \ { \ public: \ group##name##Test() : cpput::Case(#group,#name) {} \ virtual ~group##name##Test() {} \ private: \ virtual void do_run(cpput::Result& testResult_); \ } group##name##TestInstance; \ inline void group##name##Test::do_run(cpput::Result& testResult_) /// Test case with fixture. /// #define TEST_F(group,name) \ class group##name##FixtureTest : public group { \ public: \ void do_run(cpput::Result& testResult_); \ }; \ class group##name##Test : public cpput::Case { \ public: \ group##name##Test() : Case(#group,#name) {} \ virtual void do_run(cpput::Result& testResult_); \ } group##name##TestInstance; \ inline void group##name##Test::do_run(cpput::Result& testResult_) { \ group##name##FixtureTest test; \ test.do_run(testResult_); \ } \ inline void group##name##FixtureTest::do_run(cpput::Result& testResult_) // ---------------------------------------------------------------------------- // Assertion Macros // ---------------------------------------------------------------------------- #define ASSERT_TRUE(expression) \ { \ if (expression) \ return; \ testResult_.addFailure(__FILE__, __LINE__, #expression); \ } #define ASSERT_FALSE(expression) ASSERT_TRUE(!(expression)) #define ASSERT_EQ(expected,actual) \ { \ if (!((expected) == (actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_NEQ(expected,actual) \ { \ if (((expected) == (actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_STREQ(expected,actual) { \ if (!(std::string(expected) == std::string(actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_NEAR(expected,actual,epsilon) \ { \ double actualTmp = actual; \ double expectedTmp = expected; \ double diff = expectedTmp - actualTmp; \ if ((diff > epsilon) || (-diff > epsilon)) \ { \ testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \ return; \ } \ } #endif // CPPUT_TESTHARNESS_HPP <commit_msg>Simplification of else.<commit_after>#ifndef CPPUT_TESTHARNESS_HPP #define CPPUT_TESTHARNESS_HPP /////////////////////////////////////////////////////////////////////////////// /// /// \brief A light-weight and easy to use unit testing framework for C++ /// \details Header-only unit testing framework that makes unit testing easy /// and quick to set up. /// \version 0.2.0 /// \date December 2011 /// \author Tommy Back /// /// /// Simply include this header file to get started. /// /// \code /// #include <cpput/TestHarness.h> /// #include <Foo.h> /// /// TEST(Foo, some_descriptive_name) /// { /// // Arrange /// Foo foo; /// // Act /// bool result = foo.isBar(); /// // Assert /// ASSERT_TRUE(result); /// } /// \endcode /// /// In case you want to keep a single file with tests that compile to an /// executable you can also add the main function to the end of the file. /// This is simple to do with the provided macro: /// /// \code /// CPPUT_TEST_MAIN; /// \endcode /// /// For larger test suits, it's recommended to group the tests per class /// in separate files and let the compiler combine them into a single /// executable which has a main.cpp file that only has the main function /// declared. /// /// \example /// [Test_Foo.cpp] /// /// \code /// #include <cpput/TestHarness.h> /// #include <Foo.h> /// /// TEST(Foo, foo_bar_z) /// { /// ... /// \endcode /// /// [main.cpp] /// /// \code /// #include <cpput/TestHarness.h> /// /// CPPUT_TEST_MAIN; /// \endcode /// /// #include <iostream> #include <iomanip> #include <string> #include <sstream> #include <ctime> namespace cpput { struct ResultWriter { virtual ~ResultWriter() {} virtual void startTest(const std::string& className, const std::string& name) = 0; virtual void endTest(bool success) = 0; virtual void failure(const std::string& filename, std::size_t line, const std::string& message) = 0; virtual int getNumberOfFailures() const = 0; }; // ---------------------------------------------------------------------------- class TextResultWriter : public ResultWriter { public: TextResultWriter() : testCount_(0) , failures_(0) { } virtual ~TextResultWriter() { if (failures_ == 0) { std::cout << "\nAll tests pass.\n"; return; } std::cout << "\n" << failures_ << " out of " << testCount_ << " tests failed.\n"; } virtual void startTest(const std::string&, const std::string&) { testCount_++; } virtual void endTest(bool success) { if (success) std::cout << '.'; else std::cout << 'F'; } virtual void failure(const std::string& filename, std::size_t line, const std::string& message) { failures_++; std::cout << "Failure: " << filename << ", line " << line << ": " << message << '\n'; } virtual int getNumberOfFailures() const { return failures_; } private: int testCount_; int failures_; }; // ---------------------------------------------------------------------------- class XmlResultWriter : public ResultWriter { public: XmlResultWriter() : startTime_(0) { std::cout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; std::cout << "<testsuite>\n"; } virtual ~XmlResultWriter() { std::cout << "</testsuite>\n"; } virtual void startTest(const std::string& className, const std::string& name) { startTime_ = std::clock(); std::cout << " <testcase classname=\"" << className << "\" name=\"" << name << "\" time=\""; } virtual void endTest(bool success) { if (success) { std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\""; std::cout << "/>\n"; } else std::cout << " </testcase>\n"; } virtual void failure(const std::string& filename, std::size_t line, const std::string& message) { std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\""; std::cout << ">\n" << " <failure>" << message << " in " << filename << ", line " << line << "</failure>\n"; failureCount_++; } virtual int getNumberOfFailures() const { return failureCount_; } private: std::clock_t startTime_; int failureCount_; }; // ---------------------------------------------------------------------------- struct Result { Result(const std::string& testClassName, const std::string& testName, ResultWriter& out) : out_(out) , pass_(true) { out_.startTest(testClassName, testName); } ~Result() { out_.endTest(pass_); } template <typename T, typename U> void addFailure(const char* filename, std::size_t line, T expected, U actual) { pass_ = false; std::stringstream ss; ss << std::setprecision(20) << "failed comparison, expected " << expected << " got " << actual << "\n"; out_.failure(filename, line, ss.str()); } void addFailure(const char* filename, std::size_t line, const char* message) { pass_ = false; out_.failure(filename, line, message); } ResultWriter& out_; bool pass_; }; // ---------------------------------------------------------------------------- class Repository; class Case { friend class Repository; public: Case(const char* className, const char* name); virtual ~Case() {} void run(ResultWriter& out) { Result result(test_unit_class_name_, test_unit_name_, out); try { do_run(result); } catch (const std::exception& e) { result.addFailure(__FILE__, __LINE__, std::string("Unexpected exception: ").append(e.what()).c_str()); } catch (...) { result.addFailure(__FILE__, __LINE__, "Unspecified exception!"); } } Case* next() { return test_unit_next_; } private: virtual void do_run(Result& testResult_) = 0; private: std::string test_unit_class_name_; std::string test_unit_name_; Case* test_unit_next_; }; // ---------------------------------------------------------------------------- class Repository { public: static Repository& instance() { static Repository repo; return repo; } void add(Case* tc) { if (!cases_) { cases_ = tc; return; } // add as last Case* tmp = cases_; while (tmp->test_unit_next_) tmp = tmp->test_unit_next_; tmp->test_unit_next_ = tc; } Case* getCases() { return cases_; } private: Repository() : cases_(0) {} Repository(const Repository& other); Repository& operator=(const Repository& rhs) const; private: Case* cases_; }; inline Case::Case(const char* className, const char* name) : test_unit_class_name_(className) , test_unit_name_(name) , test_unit_next_(0) { Repository::instance().add(this); } // ---------------------------------------------------------------------------- inline int runAllTests(ResultWriter& writer) { Case* c = Repository::instance().getCases(); while (c) { c->run(writer); c = c->next(); } return writer.getNumberOfFailures(); } } // namespace cpput // Convenience macro to get main function. #define CPPUT_TEST_MAIN \ int main(int argc, char* argv[]) { \ if (argc == 2 && std::string(argv[1]) == "--xml") { \ cpput::XmlResultWriter writer; \ return ::cpput::runAllTests(writer); \ } \ cpput::TextResultWriter writer; \ return ::cpput::runAllTests(writer); \ } // ---------------------------------------------------------------------------- // Test Case Macros // ---------------------------------------------------------------------------- /// Stand-alone test case. /// #define TEST(group,name) \ class group##name##Test : public cpput::Case \ { \ public: \ group##name##Test() : cpput::Case(#group,#name) {} \ virtual ~group##name##Test() {} \ private: \ virtual void do_run(cpput::Result& testResult_); \ } group##name##TestInstance; \ inline void group##name##Test::do_run(cpput::Result& testResult_) /// Test case with fixture. /// #define TEST_F(group,name) \ class group##name##FixtureTest : public group { \ public: \ void do_run(cpput::Result& testResult_); \ }; \ class group##name##Test : public cpput::Case { \ public: \ group##name##Test() : Case(#group,#name) {} \ virtual void do_run(cpput::Result& testResult_); \ } group##name##TestInstance; \ inline void group##name##Test::do_run(cpput::Result& testResult_) { \ group##name##FixtureTest test; \ test.do_run(testResult_); \ } \ inline void group##name##FixtureTest::do_run(cpput::Result& testResult_) // ---------------------------------------------------------------------------- // Assertion Macros // ---------------------------------------------------------------------------- #define ASSERT_TRUE(expression) \ { \ if (expression) \ return; \ testResult_.addFailure(__FILE__, __LINE__, #expression); \ } #define ASSERT_FALSE(expression) ASSERT_TRUE(!(expression)) #define ASSERT_EQ(expected,actual) \ { \ if (!((expected) == (actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_NEQ(expected,actual) \ { \ if (((expected) == (actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_STREQ(expected,actual) { \ if (!(std::string(expected) == std::string(actual))) \ { \ testResult_.addFailure(__FILE__, __LINE__, expected, actual); \ return; \ } \ } #define ASSERT_NEAR(expected,actual,epsilon) \ { \ double actualTmp = actual; \ double expectedTmp = expected; \ double diff = expectedTmp - actualTmp; \ if ((diff > epsilon) || (-diff > epsilon)) \ { \ testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \ return; \ } \ } #endif // CPPUT_TESTHARNESS_HPP <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include <gtest/gtest.h> #include <unistd.h> #include <algorithm> #include <cstdio> #include <cstring> #include <string> #include "../../cvmfs/encrypt.h" #include "../../cvmfs/hash.h" #include "../../cvmfs/util.h" #include "testutil.h" using namespace std; // NOLINT namespace cipher { TEST(T_Encrypt, Entropy) { // Enough entropy for 100,000 256 bit keys? for (unsigned i = 0; i < 100000; ++i) { UniquePtr<Key> k(Key::CreateRandomly(32)); ASSERT_TRUE(k.IsValid()); } } TEST(T_Encrypt, KeyFiles) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string tmp_path; FILE *f = CreateTempFile("./key", 0600, "w+", &tmp_path); ASSERT_TRUE(f != NULL); fclose(f); EXPECT_FALSE(k->SaveToFile("/no/such/file")); EXPECT_TRUE(k->SaveToFile(tmp_path)); UniquePtr<Key> k_restore1(Key::CreateFromFile(tmp_path)); ASSERT_TRUE(k_restore1.IsValid()); EXPECT_EQ(k->size(), k_restore1->size()); EXPECT_EQ( 0, memcmp(k->data(), k_restore1->data(), std::min(k->size(), k_restore1->size())) ); EXPECT_EQ(0, truncate(tmp_path.c_str(), 0)); UniquePtr<Key> k_restore2(Key::CreateFromFile(tmp_path)); EXPECT_FALSE(k_restore2.IsValid()); unlink(tmp_path.c_str()); UniquePtr<Key> k_restore3(Key::CreateFromFile(tmp_path)); EXPECT_FALSE(k_restore3.IsValid()); } TEST(T_Encrypt, DecryptWrongEnvelope) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); UniquePtr<Key> k_bad(Key::CreateRandomly(1)); ASSERT_TRUE(k_bad.IsValid()); string ciphertext; string plaintext; int retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext = "X"; ciphertext[0] = 0xF0; retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext[0] = 0x0F; retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext[0] = cipher.algorithm() << 4; retval = Cipher::Decrypt(ciphertext, *k_bad, &plaintext); EXPECT_FALSE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); } TEST(T_Encrypt, None) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string empty; string dummy = "Hello, World!"; string ciphertext; string plaintext; bool retval; retval = cipher.Encrypt(empty, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(empty, plaintext); retval = cipher.Encrypt(dummy, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(dummy, plaintext); } TEST(T_Encrypt, Aes_256_Cbc) { CipherAes256Cbc cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string empty; string dummy = "Hello, World!"; string ciphertext; string ciphertext_two; string plaintext; bool retval; retval = cipher.Encrypt(empty, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(empty, plaintext); retval = cipher.Encrypt(dummy, *k, &ciphertext); EXPECT_TRUE(retval); retval = cipher.Encrypt(dummy, *k, &ciphertext_two); EXPECT_TRUE(retval); // Initialization vector should differ EXPECT_NE(ciphertext, ciphertext_two); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(dummy, plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, 1), *k, &plaintext); EXPECT_EQ("", plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, 1 + cipher.block_size()), *k, &plaintext); EXPECT_EQ("", plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, ciphertext.length()-1), *k, &plaintext); EXPECT_EQ("", plaintext); } TEST(T_Encrypt, Aes_256_Cbc_Iv) { CipherAes256Cbc cipher; // Many Iv requests in a short time should still return unique IVs shash::Md5 md5; for (unsigned i = 0; i < 100000; ++i) { shash::Md5 next_iv = cipher.GenerateIv(); ASSERT_NE(md5, next_iv); md5 = next_iv; } } } // namespace cipher <commit_msg>add unit test for key memory database<commit_after>/** * This file is part of the CernVM File System. */ #include <gtest/gtest.h> #include <unistd.h> #include <algorithm> #include <cstdio> #include <cstring> #include <string> #include "../../cvmfs/encrypt.h" #include "../../cvmfs/hash.h" #include "../../cvmfs/util.h" #include "testutil.h" using namespace std; // NOLINT namespace cipher { TEST(T_Encrypt, Entropy) { // Enough entropy for 100,000 256 bit keys? for (unsigned i = 0; i < 100000; ++i) { UniquePtr<Key> k(Key::CreateRandomly(32)); ASSERT_TRUE(k.IsValid()); } } TEST(T_Encrypt, KeyFiles) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string tmp_path; FILE *f = CreateTempFile("./key", 0600, "w+", &tmp_path); ASSERT_TRUE(f != NULL); fclose(f); EXPECT_FALSE(k->SaveToFile("/no/such/file")); EXPECT_TRUE(k->SaveToFile(tmp_path)); UniquePtr<Key> k_restore1(Key::CreateFromFile(tmp_path)); ASSERT_TRUE(k_restore1.IsValid()); EXPECT_EQ(k->size(), k_restore1->size()); EXPECT_EQ( 0, memcmp(k->data(), k_restore1->data(), std::min(k->size(), k_restore1->size())) ); EXPECT_EQ(0, truncate(tmp_path.c_str(), 0)); UniquePtr<Key> k_restore2(Key::CreateFromFile(tmp_path)); EXPECT_FALSE(k_restore2.IsValid()); unlink(tmp_path.c_str()); UniquePtr<Key> k_restore3(Key::CreateFromFile(tmp_path)); EXPECT_FALSE(k_restore3.IsValid()); } TEST(T_Encrypt, MemoryKeyDatabase) { MemoryKeyDatabase database; UniquePtr<Key> k(Key::CreateRandomly(32)); string id; EXPECT_TRUE(database.StoreNew(k.weak_ref(), &id)); EXPECT_FALSE(database.StoreNew(k.weak_ref(), &id)); EXPECT_EQ(NULL, database.Find("not available")); const Key *found = database.Find(id); EXPECT_EQ(k.weak_ref(), found); } TEST(T_Encrypt, DecryptWrongEnvelope) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); UniquePtr<Key> k_bad(Key::CreateRandomly(1)); ASSERT_TRUE(k_bad.IsValid()); string ciphertext; string plaintext; int retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext = "X"; ciphertext[0] = 0xF0; retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext[0] = 0x0F; retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_FALSE(retval); ciphertext[0] = cipher.algorithm() << 4; retval = Cipher::Decrypt(ciphertext, *k_bad, &plaintext); EXPECT_FALSE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); } TEST(T_Encrypt, None) { CipherNone cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string empty; string dummy = "Hello, World!"; string ciphertext; string plaintext; bool retval; retval = cipher.Encrypt(empty, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(empty, plaintext); retval = cipher.Encrypt(dummy, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(dummy, plaintext); } TEST(T_Encrypt, Aes_256_Cbc) { CipherAes256Cbc cipher; UniquePtr<Key> k(Key::CreateRandomly(cipher.key_size())); ASSERT_TRUE(k.IsValid()); string empty; string dummy = "Hello, World!"; string ciphertext; string ciphertext_two; string plaintext; bool retval; retval = cipher.Encrypt(empty, *k, &ciphertext); EXPECT_TRUE(retval); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(empty, plaintext); retval = cipher.Encrypt(dummy, *k, &ciphertext); EXPECT_TRUE(retval); retval = cipher.Encrypt(dummy, *k, &ciphertext_two); EXPECT_TRUE(retval); // Initialization vector should differ EXPECT_NE(ciphertext, ciphertext_two); retval = Cipher::Decrypt(ciphertext, *k, &plaintext); EXPECT_TRUE(retval); EXPECT_EQ(dummy, plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, 1), *k, &plaintext); EXPECT_EQ("", plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, 1 + cipher.block_size()), *k, &plaintext); EXPECT_EQ("", plaintext); retval = Cipher::Decrypt(ciphertext.substr(0, ciphertext.length()-1), *k, &plaintext); EXPECT_EQ("", plaintext); } TEST(T_Encrypt, Aes_256_Cbc_Iv) { CipherAes256Cbc cipher; // Many Iv requests in a short time should still return unique IVs shash::Md5 md5; for (unsigned i = 0; i < 100000; ++i) { shash::Md5 next_iv = cipher.GenerateIv(); ASSERT_NE(md5, next_iv); md5 = next_iv; } } } // namespace cipher <|endoftext|>
<commit_before>#include "collisionSystem.hpp" #include <fstream> #include <string> #include <sstream> #include "player.hpp" namespace aw { CollisionType CollisionSystem::checkCollision(const Player &player) { //Check every vertex for collision for (std::size_t i = 0; i < 3; ++i) { if (player.getVertexPosition(i).y < 0) continue; std::size_t xPosInTiles = static_cast<std::size_t>(player.getVertexPosition(i).x / 25.f); std::size_t yPosInTiles = static_cast<std::size_t>(player.getVertexPosition(i).y / 25.f); if (xPosInTiles < m_collisionCollums.size()-1) { auto result = m_collisionCollums[xPosInTiles].getCollision(yPosInTiles); if (result != CollisionType::NOTHING) { return result; } } } return CollisionType::NOTHING; } void CollisionSystem::loadMap(const std::string &path) { std::fstream file(path.c_str(), std::ios::in); if (!file.good()) return; std::string line; while (std::getline(file, line)) { if (line == "[Blocks]") { while (std::getline(file, line)) { if (line == "[/Blocks]") { break; } std::stringstream sstr(line); std::size_t start, end; sstr >> start >> end; m_collisionCollums.push_back(CollisionCollum()); if (start < 100000) { m_collisionCollums.back().setStartAndEnd(start, end); for (std::size_t i = start; i <= end; ++i) { int type; int useless; sstr >> useless >> type; if (type == 0) { m_collisionCollums.back().push_back(CollisionType::NOTHING); } else if (type == 1) { m_collisionCollums.back().push_back(CollisionType::WALL); } else if (type == 2) { m_collisionCollums.back().push_back(CollisionType::FINISH); } } } } } } file.close(); } }<commit_msg>Fixed a vector out of bounds error<commit_after>#include "collisionSystem.hpp" #include <fstream> #include <string> #include <sstream> #include "player.hpp" namespace aw { CollisionType CollisionSystem::checkCollision(const Player &player) { //Check every vertex for collision for (std::size_t i = 0; i < 3; ++i) { if (player.getVertexPosition(i).y < 0) continue; std::size_t xPosInTiles = static_cast<std::size_t>(player.getVertexPosition(i).x / 25.f); std::size_t yPosInTiles = static_cast<std::size_t>(player.getVertexPosition(i).y / 25.f); if (xPosInTiles < m_collisionCollums.size()) { auto result = m_collisionCollums[xPosInTiles].getCollision(yPosInTiles); if (result != CollisionType::NOTHING) { return result; } } } return CollisionType::NOTHING; } void CollisionSystem::loadMap(const std::string &path) { std::fstream file(path.c_str(), std::ios::in); if (!file.good()) return; std::string line; while (std::getline(file, line)) { if (line == "[Blocks]") { while (std::getline(file, line)) { if (line == "[/Blocks]") { break; } std::stringstream sstr(line); std::size_t start, end; sstr >> start >> end; m_collisionCollums.push_back(CollisionCollum()); if (start < 100000) { m_collisionCollums.back().setStartAndEnd(start, end); for (std::size_t i = start; i <= end; ++i) { int type; int useless; sstr >> useless >> type; if (type == 0) { m_collisionCollums.back().push_back(CollisionType::NOTHING); } else if (type == 1) { m_collisionCollums.back().push_back(CollisionType::WALL); } else if (type == 2) { m_collisionCollums.back().push_back(CollisionType::FINISH); } } } } } } file.close(); } }<|endoftext|>
<commit_before>/* * Copyright (c) 2014 Eran Pe'er. * * This program is made available under the terms of the MIT License. * * Created on Mar 10, 2014 */ #if defined (__GNUG__) #include <string> #include <iosfwd> #include <stdexcept> #include <tuple> #include <type_traits> #include "tpunit++.hpp" #include "fakeit.hpp" #include "mockutils/Formatter.hpp" using namespace fakeit; struct GccTypeInfoTests: tpunit::TestFixture { GccTypeInfoTests() : tpunit::TestFixture( // TEST(GccTypeInfoTests::simple_inheritance_dynamic_down_cast), TEST(GccTypeInfoTests::mutiple_inheritance_upcast)) { } struct TopLeft { int topLeft; virtual int f()=0; }; struct Left: public TopLeft { int left; virtual int f() override = 0; }; struct A: public Left { int a; virtual int f() override = 0; }; void simple_inheritance_dynamic_down_cast() { Mock<A> aMock; // no need for base classes list on gcc. Fake(Method(aMock,f)); A& a = aMock.get(); Left* left = &a; TopLeft* topLeft = &a; A* aPtr = dynamic_cast<A*>(left); ASSERT_EQUAL(0, aPtr->f()); aPtr = dynamic_cast<A*>(topLeft); ASSERT_EQUAL(0, aPtr->f()); left = dynamic_cast<Left*>(topLeft); ASSERT_EQUAL(0, left->f()); } struct TopRight { int topRight; virtual int f()=0; }; struct Right: public TopRight { int right; virtual int f() override = 0; }; struct B: public Left, public Right { int b; virtual int f() override = 0; }; void mutiple_inheritance_upcast() { //Mock<B> bMock; // should not compile } } __GccTypeInfoTests; #endif <commit_msg>fix tests<commit_after>/* * Copyright (c) 2014 Eran Pe'er. * * This program is made available under the terms of the MIT License. * * Created on Mar 10, 2014 */ #if defined (__GNUG__) #include <string> #include <iosfwd> #include <stdexcept> #include <tuple> #include <type_traits> #include "tpunit++.hpp" #include "fakeit.hpp" using namespace fakeit; struct GccTypeInfoTests: tpunit::TestFixture { GccTypeInfoTests() : tpunit::TestFixture( // TEST(GccTypeInfoTests::simple_inheritance_dynamic_down_cast), TEST(GccTypeInfoTests::mutiple_inheritance_upcast)) { } struct TopLeft { int topLeft; virtual int f()=0; }; struct Left: public TopLeft { int left; virtual int f() override = 0; }; struct A: public Left { int a; virtual int f() override = 0; }; void simple_inheritance_dynamic_down_cast() { Mock<A> aMock; // no need for base classes list on gcc. Fake(Method(aMock,f)); A& a = aMock.get(); Left* left = &a; TopLeft* topLeft = &a; A* aPtr = dynamic_cast<A*>(left); ASSERT_EQUAL(0, aPtr->f()); aPtr = dynamic_cast<A*>(topLeft); ASSERT_EQUAL(0, aPtr->f()); left = dynamic_cast<Left*>(topLeft); ASSERT_EQUAL(0, left->f()); } struct TopRight { int topRight; virtual int f()=0; }; struct Right: public TopRight { int right; virtual int f() override = 0; }; struct B: public Left, public Right { int b; virtual int f() override = 0; }; void mutiple_inheritance_upcast() { //Mock<B> bMock; // should not compile } } __GccTypeInfoTests; #endif <|endoftext|>
<commit_before>/* * INTEL CONFIDENTIAL * Copyright © 2011 Intel * Corporation All Rights Reserved. * * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Intel Corporation or its suppliers * or licensors. Title to the Material remains with Intel Corporation or its * suppliers and licensors. The Material contains trade secrets and proprietary * and confidential information of Intel or its suppliers and licensors. The * Material is protected by worldwide copyright and trade secret laws and * treaty provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed, or * disclosed in any way without Intel’s prior express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Intel in writing. * * CREATED: 2011-06-01 * UPDATED: 2011-07-27 */ #include "Subsystem.h" #include "ComponentLibrary.h" #include "InstanceDefinition.h" #include "XmlParameterSerializingContext.h" #include "ParameterAccessContext.h" #include "ConfigurationAccessContext.h" #include "SubsystemObjectCreator.h" #include "MappingData.h" #include <assert.h> #include <sstream> #define base CConfigurableElement CSubsystem::CSubsystem(const string& strName) : base(strName), _pComponentLibrary(new CComponentLibrary), _pInstanceDefinition(new CInstanceDefinition), _bBigEndian(false) { // Note: A subsystem contains instance components // InstanceDefintion and ComponentLibrary objects are then not chosen to be children // They'll be delt with locally } CSubsystem::~CSubsystem() { // Remove subsystem objects SubsystemObjectListIterator subsystemObjectIt; for (subsystemObjectIt = _subsystemObjectList.begin(); subsystemObjectIt != _subsystemObjectList.end(); ++subsystemObjectIt) { delete *subsystemObjectIt; } // Remove susbsystem creators uint32_t uiIndex; for (uiIndex = 0; uiIndex < _subsystemObjectCreatorArray.size(); uiIndex++) { delete _subsystemObjectCreatorArray[uiIndex]; } // Order matters! delete _pInstanceDefinition; delete _pComponentLibrary; } string CSubsystem::getKind() const { return "Subsystem"; } // Susbsystem Endianness bool CSubsystem::isBigEndian() const { return _bBigEndian; } // Susbsystem sanity bool CSubsystem::isAlive() const { return true; } // Resynchronization after subsystem restart needed bool CSubsystem::needResync(bool bClear) { (void)bClear; return false; } // From IXmlSink bool CSubsystem::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) { // Context CXmlParameterSerializingContext& parameterBuildContext = static_cast<CXmlParameterSerializingContext&>(serializingContext); // Install temporary component library for further component creation parameterBuildContext.setComponentLibrary(_pComponentLibrary); CXmlElement childElement; // XML populate ComponentLibrary xmlElement.getChildElement("ComponentLibrary", childElement); if (!_pComponentLibrary->fromXml(childElement, serializingContext)) { return false; } // XML populate InstanceDefintion xmlElement.getChildElement("InstanceDefintion", childElement); if (!_pInstanceDefinition->fromXml(childElement, serializingContext)) { return false; } // Create components _pInstanceDefinition->createInstances(this); // Execute mapping to create subsystem mapping entities string strError; if (!mapSubsystemElements(strError)) { serializingContext.setError(strError); return false; } // Endianness _bBigEndian = xmlElement.getAttributeBoolean("Endianness", "Big"); return true; } // XML configuration settings parsing bool CSubsystem::serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const { // Fix Endianness configurationAccessContext.setBigEndianSubsystem(_bBigEndian); return base::serializeXmlSettings(xmlConfigurationSettingsElementContent, configurationAccessContext); } bool CSubsystem::mapSubsystemElements(string& strError) { // Default mapping context _contextStack.push(CMappingContext(_contextMappingKeyArray.size())); // Map all instantiated subelements in subsystem uint32_t uiNbChildren = getNbChildren(); uint32_t uiChild; for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { CInstanceConfigurableElement* pInstanceConfigurableChildElement = static_cast<CInstanceConfigurableElement*>(getChild(uiChild)); if (!pInstanceConfigurableChildElement->map(*this, strError)) { return false; } } return true; } // Parameter access bool CSubsystem::accessValue(CPathNavigator& pathNavigator, string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const { // Deal with Endianness parameterAccessContext.setBigEndianSubsystem(_bBigEndian); return base::accessValue(pathNavigator, strValue, bSet, parameterAccessContext); } // Formats the mapping of the ConfigurableElements string CSubsystem::formatMappingDataList( const list<const CConfigurableElement*>& configurableElementPath) const { // The list is parsed in reverse order because it has been filled from the leaf to the trunk // of the tree. When formatting the mapping, we want to start from the subsystem level ostringstream ossStream; list<const CConfigurableElement*>::const_reverse_iterator it; for (it = configurableElementPath.rbegin(); it != configurableElementPath.rend(); ++it) { const CInstanceConfigurableElement* pInstanceConfigurableElement = static_cast<const CInstanceConfigurableElement*>(*it); ossStream << pInstanceConfigurableElement->getFormattedMapping() << ", "; } return ossStream.str(); } // Find the CSubystemObject containing a specific CInstanceConfigurableElement const CSubsystemObject* CSubsystem::findSubsystemObjectFromConfigurableElement( const CInstanceConfigurableElement* pInstanceConfigurableElement) const { const CSubsystemObject* pSubsystemObject = NULL; list<CSubsystemObject*>::const_iterator it; for (it = _subsystemObjectList.begin(); it != _subsystemObjectList.end(); ++it) { // Check if one of the SubsystemObjects is associated with a ConfigurableElement // corresponding to the expected one pSubsystemObject = *it; if (pSubsystemObject->getConfigurableElement() == pInstanceConfigurableElement) { break; } } return pSubsystemObject; } void CSubsystem::findSubsystemLevelMappingKeyValue( const CInstanceConfigurableElement* pInstanceConfigurableElement, string& strMappingKey, string& strMappingValue) const { // Find creator to get key name vector<CSubsystemObjectCreator*>::const_iterator it; for (it = _subsystemObjectCreatorArray.begin(); it != _subsystemObjectCreatorArray.end(); ++it) { const CSubsystemObjectCreator* pSubsystemObjectCreator = *it; strMappingKey = pSubsystemObjectCreator->getMappingKey(); // Check if the ObjectCreator MappingKey corresponds to the element mapping data const string* pStrValue; if (pInstanceConfigurableElement->getMappingData(strMappingKey, pStrValue)) { strMappingValue = *pStrValue; return; } } assert(0); } // Formats the mapping data as a comma separated list of key value pairs string CSubsystem::getFormattedSubsystemMappingData( const CInstanceConfigurableElement* pInstanceConfigurableElement) const { // Find the SubsystemObject related to pInstanceConfigurableElement const CSubsystemObject* pSubsystemObject = findSubsystemObjectFromConfigurableElement( pInstanceConfigurableElement); // Exit if node does not correspond to a SubsystemObject if (pSubsystemObject == NULL) { return ""; } // Find SubsystemCreator mapping key string strMappingKey; string strMappingValue; // mapping value where amends are not replaced by their value findSubsystemLevelMappingKeyValue(pInstanceConfigurableElement, strMappingKey, strMappingValue); // Find SubSystemObject mapping value (with amends replaced by their value) return strMappingKey + ":" + pSubsystemObject->getFormattedMappingValue(); } string CSubsystem::getMapping(list<const CConfigurableElement*>& configurableElementPath) const { if (configurableElementPath.empty()) { return ""; } // Get the first element, which is the element containing the amended mapping const CInstanceConfigurableElement* pInstanceConfigurableElement = static_cast<const CInstanceConfigurableElement*>(configurableElementPath.front()); configurableElementPath.pop_front(); // Now the list only contains elements whose mapping are related to the context // Format context mapping data string strValue = formatMappingDataList(configurableElementPath); // Print the mapping of the first node, which corresponds to a SubsystemObject strValue += getFormattedSubsystemMappingData(pInstanceConfigurableElement); return strValue; } void CSubsystem::logValue(string& strValue, CErrorContext& errorContext) const { CParameterAccessContext& parameterAccessContext = static_cast<CParameterAccessContext&>(errorContext); // Deal with Endianness parameterAccessContext.setBigEndianSubsystem(_bBigEndian); return base::logValue(strValue, errorContext); } // Used for simulation and virtual subsystems void CSubsystem::setDefaultValues(CParameterAccessContext& parameterAccessContext) const { // Deal with Endianness parameterAccessContext.setBigEndianSubsystem(_bBigEndian); base::setDefaultValues(parameterAccessContext); } // Belonging subsystem const CSubsystem* CSubsystem::getBelongingSubsystem() const { return this; } // Subsystem context mapping keys publication void CSubsystem::addContextMappingKey(const string& strMappingKey) { _contextMappingKeyArray.push_back(strMappingKey); } // Subsystem object creator publication (strong reference) void CSubsystem::addSubsystemObjectFactory(CSubsystemObjectCreator* pSubsystemObjectCreator) { _subsystemObjectCreatorArray.push_back(pSubsystemObjectCreator); } // Generic error handling from derived subsystem classes string CSubsystem::getMappingError(const string& strKey, const string& strMessage, const CInstanceConfigurableElement* pInstanceConfigurableElement) const { return getName() + " " + getKind() + " " + "mapping:\n" + strKey + " " + "error: \"" + strMessage + "\" " + "for element " + pInstanceConfigurableElement->getPath(); } // Mapping generic context handling bool CSubsystem::handleMappingContext( const CInstanceConfigurableElement* pInstanceConfigurableElement, CMappingContext& context, string& strError) const { // Feed context with found mapping data uint32_t uiItem; for (uiItem = 0; uiItem < _contextMappingKeyArray.size(); uiItem++) { const string& strKey = _contextMappingKeyArray[uiItem]; const string* pStrValue; if (pInstanceConfigurableElement->getMappingData(strKey, pStrValue)) { // Assign item to context if (!context.setItem(uiItem, &strKey, pStrValue)) { strError = getMappingError(strKey, "Already set", pInstanceConfigurableElement); return false; } } } return true; } // Subsystem object creation handling bool CSubsystem::handleSubsystemObjectCreation( CInstanceConfigurableElement* pInstanceConfigurableElement, CMappingContext& context, bool& bHasCreatedSubsystemObject, string& strError) { uint32_t uiItem; bHasCreatedSubsystemObject = false; for (uiItem = 0; uiItem < _subsystemObjectCreatorArray.size(); uiItem++) { const CSubsystemObjectCreator* pSubsystemObjectCreator = _subsystemObjectCreatorArray[uiItem]; // Mapping key string strKey = pSubsystemObjectCreator->getMappingKey(); // Object id const string* pStrValue; if (pInstanceConfigurableElement->getMappingData(strKey, pStrValue)) { // First check context consistency // (required ancestors must have been set prior to object creation) uint32_t uiAncestorKey; uint32_t uiAncestorMask = pSubsystemObjectCreator->getAncestorMask(); for (uiAncestorKey = 0; uiAncestorKey < _contextMappingKeyArray.size(); uiAncestorKey++) { if (!((1 << uiAncestorKey) & uiAncestorMask)) { // Ancestor not required continue; } // Check ancestor was provided if (!context.iSet(uiAncestorKey)) { strError = getMappingError(strKey, _contextMappingKeyArray[uiAncestorKey] + " not set", pInstanceConfigurableElement); return false; } } // Then check configurable element size is correct if (pInstanceConfigurableElement->getFootPrint() > pSubsystemObjectCreator->getMaxConfigurableElementSize()) { string strSizeError = "Size should not exceed " + pSubsystemObjectCreator->getMaxConfigurableElementSize(); strError = getMappingError(strKey, strSizeError, pInstanceConfigurableElement); return false; } // Do create object and keep its track _subsystemObjectList.push_back(pSubsystemObjectCreator->objectCreate( *pStrValue, pInstanceConfigurableElement, context)); // Indicate subsytem creation to caller bHasCreatedSubsystemObject = true; // The subsystem Object has been instantiated, no need to continue looking for an // instantiation mapping break; } } return true; } // From IMapper // Handle a configurable element mapping bool CSubsystem::mapBegin(CInstanceConfigurableElement* pInstanceConfigurableElement, bool& bKeepDiving, string& strError) { // Get current context CMappingContext context = _contextStack.top(); // Add mapping in context if (!handleMappingContext(pInstanceConfigurableElement, context, strError)) { return false; } // Push context _contextStack.push(context); // Assume diving by default bKeepDiving = true; // Deal with ambiguous usage of parameter blocks bool bShouldCreateSubsystemObject = true; switch(pInstanceConfigurableElement->getType()) { case CInstanceConfigurableElement::EComponent: return true; case CInstanceConfigurableElement::EParameterBlock: // Subsystem object creation is optional in parameter blocks bShouldCreateSubsystemObject = false; // No break case CInstanceConfigurableElement::EBitParameterBlock: case CInstanceConfigurableElement::EParameter: case CInstanceConfigurableElement::EStringParameter: bool bHasCreatedSubsystemObject; if (!handleSubsystemObjectCreation(pInstanceConfigurableElement, context, bHasCreatedSubsystemObject, strError)) { return false; } // Check for creation error if (bShouldCreateSubsystemObject && !bHasCreatedSubsystemObject) { strError = getMappingError("Not found", "Subsystem object mapping key is missing", pInstanceConfigurableElement); return false; } // Not created and no error, keep diving bKeepDiving = !bHasCreatedSubsystemObject; return true; default: assert(0); return false; } } void CSubsystem::mapEnd() { // Unstack context _contextStack.pop(); } <commit_msg>[PFW] Add possibility to put mapping info in component nodes<commit_after>/* * INTEL CONFIDENTIAL * Copyright © 2011 Intel * Corporation All Rights Reserved. * * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Intel Corporation or its suppliers * or licensors. Title to the Material remains with Intel Corporation or its * suppliers and licensors. The Material contains trade secrets and proprietary * and confidential information of Intel or its suppliers and licensors. The * Material is protected by worldwide copyright and trade secret laws and * treaty provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed, or * disclosed in any way without Intel’s prior express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Intel in writing. * * CREATED: 2011-06-01 * UPDATED: 2011-07-27 */ #include "Subsystem.h" #include "ComponentLibrary.h" #include "InstanceDefinition.h" #include "XmlParameterSerializingContext.h" #include "ParameterAccessContext.h" #include "ConfigurationAccessContext.h" #include "SubsystemObjectCreator.h" #include "MappingData.h" #include <assert.h> #include <sstream> #define base CConfigurableElement CSubsystem::CSubsystem(const string& strName) : base(strName), _pComponentLibrary(new CComponentLibrary), _pInstanceDefinition(new CInstanceDefinition), _bBigEndian(false) { // Note: A subsystem contains instance components // InstanceDefintion and ComponentLibrary objects are then not chosen to be children // They'll be delt with locally } CSubsystem::~CSubsystem() { // Remove subsystem objects SubsystemObjectListIterator subsystemObjectIt; for (subsystemObjectIt = _subsystemObjectList.begin(); subsystemObjectIt != _subsystemObjectList.end(); ++subsystemObjectIt) { delete *subsystemObjectIt; } // Remove susbsystem creators uint32_t uiIndex; for (uiIndex = 0; uiIndex < _subsystemObjectCreatorArray.size(); uiIndex++) { delete _subsystemObjectCreatorArray[uiIndex]; } // Order matters! delete _pInstanceDefinition; delete _pComponentLibrary; } string CSubsystem::getKind() const { return "Subsystem"; } // Susbsystem Endianness bool CSubsystem::isBigEndian() const { return _bBigEndian; } // Susbsystem sanity bool CSubsystem::isAlive() const { return true; } // Resynchronization after subsystem restart needed bool CSubsystem::needResync(bool bClear) { (void)bClear; return false; } // From IXmlSink bool CSubsystem::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) { // Context CXmlParameterSerializingContext& parameterBuildContext = static_cast<CXmlParameterSerializingContext&>(serializingContext); // Install temporary component library for further component creation parameterBuildContext.setComponentLibrary(_pComponentLibrary); CXmlElement childElement; // XML populate ComponentLibrary xmlElement.getChildElement("ComponentLibrary", childElement); if (!_pComponentLibrary->fromXml(childElement, serializingContext)) { return false; } // XML populate InstanceDefintion xmlElement.getChildElement("InstanceDefintion", childElement); if (!_pInstanceDefinition->fromXml(childElement, serializingContext)) { return false; } // Create components _pInstanceDefinition->createInstances(this); // Execute mapping to create subsystem mapping entities string strError; if (!mapSubsystemElements(strError)) { serializingContext.setError(strError); return false; } // Endianness _bBigEndian = xmlElement.getAttributeBoolean("Endianness", "Big"); return true; } // XML configuration settings parsing bool CSubsystem::serializeXmlSettings(CXmlElement& xmlConfigurationSettingsElementContent, CConfigurationAccessContext& configurationAccessContext) const { // Fix Endianness configurationAccessContext.setBigEndianSubsystem(_bBigEndian); return base::serializeXmlSettings(xmlConfigurationSettingsElementContent, configurationAccessContext); } bool CSubsystem::mapSubsystemElements(string& strError) { // Default mapping context _contextStack.push(CMappingContext(_contextMappingKeyArray.size())); // Map all instantiated subelements in subsystem uint32_t uiNbChildren = getNbChildren(); uint32_t uiChild; for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { CInstanceConfigurableElement* pInstanceConfigurableChildElement = static_cast<CInstanceConfigurableElement*>(getChild(uiChild)); if (!pInstanceConfigurableChildElement->map(*this, strError)) { return false; } } return true; } // Parameter access bool CSubsystem::accessValue(CPathNavigator& pathNavigator, string& strValue, bool bSet, CParameterAccessContext& parameterAccessContext) const { // Deal with Endianness parameterAccessContext.setBigEndianSubsystem(_bBigEndian); return base::accessValue(pathNavigator, strValue, bSet, parameterAccessContext); } // Formats the mapping of the ConfigurableElements string CSubsystem::formatMappingDataList( const list<const CConfigurableElement*>& configurableElementPath) const { // The list is parsed in reverse order because it has been filled from the leaf to the trunk // of the tree. When formatting the mapping, we want to start from the subsystem level ostringstream ossStream; list<const CConfigurableElement*>::const_reverse_iterator it; for (it = configurableElementPath.rbegin(); it != configurableElementPath.rend(); ++it) { const CInstanceConfigurableElement* pInstanceConfigurableElement = static_cast<const CInstanceConfigurableElement*>(*it); ossStream << pInstanceConfigurableElement->getFormattedMapping() << ", "; } return ossStream.str(); } // Find the CSubystemObject containing a specific CInstanceConfigurableElement const CSubsystemObject* CSubsystem::findSubsystemObjectFromConfigurableElement( const CInstanceConfigurableElement* pInstanceConfigurableElement) const { const CSubsystemObject* pSubsystemObject = NULL; list<CSubsystemObject*>::const_iterator it; for (it = _subsystemObjectList.begin(); it != _subsystemObjectList.end(); ++it) { // Check if one of the SubsystemObjects is associated with a ConfigurableElement // corresponding to the expected one pSubsystemObject = *it; if (pSubsystemObject->getConfigurableElement() == pInstanceConfigurableElement) { break; } } return pSubsystemObject; } void CSubsystem::findSubsystemLevelMappingKeyValue( const CInstanceConfigurableElement* pInstanceConfigurableElement, string& strMappingKey, string& strMappingValue) const { // Find creator to get key name vector<CSubsystemObjectCreator*>::const_iterator it; for (it = _subsystemObjectCreatorArray.begin(); it != _subsystemObjectCreatorArray.end(); ++it) { const CSubsystemObjectCreator* pSubsystemObjectCreator = *it; strMappingKey = pSubsystemObjectCreator->getMappingKey(); // Check if the ObjectCreator MappingKey corresponds to the element mapping data const string* pStrValue; if (pInstanceConfigurableElement->getMappingData(strMappingKey, pStrValue)) { strMappingValue = *pStrValue; return; } } assert(0); } // Formats the mapping data as a comma separated list of key value pairs string CSubsystem::getFormattedSubsystemMappingData( const CInstanceConfigurableElement* pInstanceConfigurableElement) const { // Find the SubsystemObject related to pInstanceConfigurableElement const CSubsystemObject* pSubsystemObject = findSubsystemObjectFromConfigurableElement( pInstanceConfigurableElement); // Exit if node does not correspond to a SubsystemObject if (pSubsystemObject == NULL) { return ""; } // Find SubsystemCreator mapping key string strMappingKey; string strMappingValue; // mapping value where amends are not replaced by their value findSubsystemLevelMappingKeyValue(pInstanceConfigurableElement, strMappingKey, strMappingValue); // Find SubSystemObject mapping value (with amends replaced by their value) return strMappingKey + ":" + pSubsystemObject->getFormattedMappingValue(); } string CSubsystem::getMapping(list<const CConfigurableElement*>& configurableElementPath) const { if (configurableElementPath.empty()) { return ""; } // Get the first element, which is the element containing the amended mapping const CInstanceConfigurableElement* pInstanceConfigurableElement = static_cast<const CInstanceConfigurableElement*>(configurableElementPath.front()); configurableElementPath.pop_front(); // Now the list only contains elements whose mapping are related to the context // Format context mapping data string strValue = formatMappingDataList(configurableElementPath); // Print the mapping of the first node, which corresponds to a SubsystemObject strValue += getFormattedSubsystemMappingData(pInstanceConfigurableElement); return strValue; } void CSubsystem::logValue(string& strValue, CErrorContext& errorContext) const { CParameterAccessContext& parameterAccessContext = static_cast<CParameterAccessContext&>(errorContext); // Deal with Endianness parameterAccessContext.setBigEndianSubsystem(_bBigEndian); return base::logValue(strValue, errorContext); } // Used for simulation and virtual subsystems void CSubsystem::setDefaultValues(CParameterAccessContext& parameterAccessContext) const { // Deal with Endianness parameterAccessContext.setBigEndianSubsystem(_bBigEndian); base::setDefaultValues(parameterAccessContext); } // Belonging subsystem const CSubsystem* CSubsystem::getBelongingSubsystem() const { return this; } // Subsystem context mapping keys publication void CSubsystem::addContextMappingKey(const string& strMappingKey) { _contextMappingKeyArray.push_back(strMappingKey); } // Subsystem object creator publication (strong reference) void CSubsystem::addSubsystemObjectFactory(CSubsystemObjectCreator* pSubsystemObjectCreator) { _subsystemObjectCreatorArray.push_back(pSubsystemObjectCreator); } // Generic error handling from derived subsystem classes string CSubsystem::getMappingError(const string& strKey, const string& strMessage, const CInstanceConfigurableElement* pInstanceConfigurableElement) const { return getName() + " " + getKind() + " " + "mapping:\n" + strKey + " " + "error: \"" + strMessage + "\" " + "for element " + pInstanceConfigurableElement->getPath(); } // Mapping generic context handling bool CSubsystem::handleMappingContext( const CInstanceConfigurableElement* pInstanceConfigurableElement, CMappingContext& context, string& strError) const { // Feed context with found mapping data uint32_t uiItem; for (uiItem = 0; uiItem < _contextMappingKeyArray.size(); uiItem++) { const string& strKey = _contextMappingKeyArray[uiItem]; const string* pStrValue; if (pInstanceConfigurableElement->getMappingData(strKey, pStrValue)) { // Assign item to context if (!context.setItem(uiItem, &strKey, pStrValue)) { strError = getMappingError(strKey, "Already set", pInstanceConfigurableElement); return false; } } } return true; } // Subsystem object creation handling bool CSubsystem::handleSubsystemObjectCreation( CInstanceConfigurableElement* pInstanceConfigurableElement, CMappingContext& context, bool& bHasCreatedSubsystemObject, string& strError) { uint32_t uiItem; bHasCreatedSubsystemObject = false; for (uiItem = 0; uiItem < _subsystemObjectCreatorArray.size(); uiItem++) { const CSubsystemObjectCreator* pSubsystemObjectCreator = _subsystemObjectCreatorArray[uiItem]; // Mapping key string strKey = pSubsystemObjectCreator->getMappingKey(); // Object id const string* pStrValue; if (pInstanceConfigurableElement->getMappingData(strKey, pStrValue)) { // First check context consistency // (required ancestors must have been set prior to object creation) uint32_t uiAncestorKey; uint32_t uiAncestorMask = pSubsystemObjectCreator->getAncestorMask(); for (uiAncestorKey = 0; uiAncestorKey < _contextMappingKeyArray.size(); uiAncestorKey++) { if (!((1 << uiAncestorKey) & uiAncestorMask)) { // Ancestor not required continue; } // Check ancestor was provided if (!context.iSet(uiAncestorKey)) { strError = getMappingError(strKey, _contextMappingKeyArray[uiAncestorKey] + " not set", pInstanceConfigurableElement); return false; } } // Then check configurable element size is correct if (pInstanceConfigurableElement->getFootPrint() > pSubsystemObjectCreator->getMaxConfigurableElementSize()) { string strSizeError = "Size should not exceed " + pSubsystemObjectCreator->getMaxConfigurableElementSize(); strError = getMappingError(strKey, strSizeError, pInstanceConfigurableElement); return false; } // Do create object and keep its track _subsystemObjectList.push_back(pSubsystemObjectCreator->objectCreate( *pStrValue, pInstanceConfigurableElement, context)); // Indicate subsytem creation to caller bHasCreatedSubsystemObject = true; // The subsystem Object has been instantiated, no need to continue looking for an // instantiation mapping break; } } return true; } // From IMapper // Handle a configurable element mapping bool CSubsystem::mapBegin(CInstanceConfigurableElement* pInstanceConfigurableElement, bool& bKeepDiving, string& strError) { // Get current context CMappingContext context = _contextStack.top(); // Add mapping in context if (!handleMappingContext(pInstanceConfigurableElement, context, strError)) { return false; } // Push context _contextStack.push(context); // Assume diving by default bKeepDiving = true; // Deal with ambiguous usage of parameter blocks bool bShouldCreateSubsystemObject = true; switch(pInstanceConfigurableElement->getType()) { case CInstanceConfigurableElement::EComponent: case CInstanceConfigurableElement::EParameterBlock: // Subsystem object creation is optional in parameter blocks bShouldCreateSubsystemObject = false; // No break case CInstanceConfigurableElement::EBitParameterBlock: case CInstanceConfigurableElement::EParameter: case CInstanceConfigurableElement::EStringParameter: bool bHasCreatedSubsystemObject; if (!handleSubsystemObjectCreation(pInstanceConfigurableElement, context, bHasCreatedSubsystemObject, strError)) { return false; } // Check for creation error if (bShouldCreateSubsystemObject && !bHasCreatedSubsystemObject) { strError = getMappingError("Not found", "Subsystem object mapping key is missing", pInstanceConfigurableElement); return false; } // Not created and no error, keep diving bKeepDiving = !bHasCreatedSubsystemObject; return true; default: assert(0); return false; } } void CSubsystem::mapEnd() { // Unstack context _contextStack.pop(); } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Dimitri Diakopoulos 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fstream> #include "WavEncoder.h" using namespace nqr; inline void toBytes(int value, char * arr) { arr[0] = (value) & 0xFF; arr[1] = (value >> 8) & 0xFF; arr[2] = (value >> 16) & 0xFF; arr[3] = (value >> 24) & 0xFF; } //////////////////////////// // Wave File Encoding // //////////////////////////// int WavEncoder::WriteFile(const EncoderParams p, const AudioData * d, const std::string & path) { assert(d->samples.size() > 0); // Cast away const because we know what we are doing (Hopefully?) float * sampleData = const_cast<float *>(d->samples.data()); size_t sampleDataSize = d->samples.size(); std::vector<float> sampleDataOptionalMix; if (sampleDataSize <= 32) { return EncoderError::InsufficientSampleData; } if (d->channelCount < 1 || d->channelCount > 8) { return EncoderError::UnsupportedChannelConfiguration; } // Handle Channel Mixing -- // Mono => Stereo if (d->channelCount == 1 && p.channelCount == 2) { sampleDataOptionalMix.resize(sampleDataSize * 2); MonoToStereo(sampleData, sampleDataOptionalMix.data(), sampleDataSize); // Mix // Re-point data sampleData = sampleDataOptionalMix.data(); sampleDataSize = sampleDataOptionalMix.size(); } // Stereo => Mono else if (d->channelCount == 2 && p.channelCount == 1) { sampleDataOptionalMix.resize(sampleDataSize / 2); StereoToMono(sampleData, sampleDataOptionalMix.data(), sampleDataSize); // Mix // Re-point data sampleData = sampleDataOptionalMix.data(); sampleDataSize = sampleDataOptionalMix.size(); } else if (d->channelCount == p.channelCount) { // No op } else { return EncoderError::UnsupportedChannelMix; } // -- End Channel Mixing auto maxFileSizeInBytes = std::numeric_limits<uint32_t>::max(); auto samplesSizeInBytes = (sampleDataSize * GetFormatBitsPerSample(p.targetFormat)) / 8; // 64 arbitrary if ((samplesSizeInBytes - 64) >= maxFileSizeInBytes) { return EncoderError::BufferTooBig; } // Don't support PCM_64 or PCM_DBL if (GetFormatBitsPerSample(p.targetFormat) > 32) { return EncoderError::UnsupportedBitdepth; } std::ofstream fout(path.c_str(), std::ios::out | std::ios::binary); if (!fout.is_open()) { return EncoderError::FileIOError; } char * chunkSizeBuff = new char[4]; // Initial size (this is changed after we're done writing the file) toBytes(36, chunkSizeBuff); // RIFF file header fout.write(GenerateChunkCodeChar('R', 'I', 'F', 'F'), 4); fout.write(chunkSizeBuff, 4); fout.write(GenerateChunkCodeChar('W', 'A', 'V', 'E'), 4); // Fmt header auto header = MakeWaveHeader(p, d->sampleRate); fout.write(reinterpret_cast<char*>(&header), sizeof(WaveChunkHeader)); auto sourceBits = GetFormatBitsPerSample(d->sourceFormat); auto targetBits = GetFormatBitsPerSample(p.targetFormat); //////////////////////////// //@todo - channel mixing! // //////////////////////////// // Write out fact chunk if (p.targetFormat == PCM_FLT) { uint32_t four = 4; uint32_t dataSz = int(sampleDataSize / p.channelCount); fout.write(GenerateChunkCodeChar('f', 'a', 'c', 't'), 4); fout.write(reinterpret_cast<const char *>(&four), 4); fout.write(reinterpret_cast<const char *>(&dataSz), 4); // Number of samples (per channel) } // Data header fout.write(GenerateChunkCodeChar('d', 'a', 't', 'a'), 4); // + data chunk size toBytes(int(samplesSizeInBytes), chunkSizeBuff); fout.write(chunkSizeBuff, 4); if (targetBits <= sourceBits && p.targetFormat != PCM_FLT) { // At most need this number of bytes in our copy std::vector<uint8_t> samplesCopy(samplesSizeInBytes); ConvertFromFloat32(samplesCopy.data(), sampleData, sampleDataSize, p.targetFormat, p.dither); fout.write(reinterpret_cast<const char*>(samplesCopy.data()), samplesSizeInBytes); } else { // Handle PCM_FLT. Coming in from AudioData ensures we start with 32 bits, so we're fine // since we've also rejected formats with more than 32 bits above. fout.write(reinterpret_cast<const char*>(sampleData), samplesSizeInBytes); } // Padding byte if (isOdd(samplesSizeInBytes)) { const char * zero = ""; fout.write(zero, 1); } // Find size long totalSize = fout.tellp(); // Modify RIFF header fout.seekp(4); // Total size of the file, less 8 bytes for the RIFF header toBytes(int(totalSize - 8), chunkSizeBuff); fout.write(chunkSizeBuff, 4); delete[] chunkSizeBuff; return EncoderError::NoError; } //////////////////////////// // Opus File Encoding // //////////////////////////// #include "opus/opusfile/include/opusfile.h" // Opus only supports a 48k samplerate... int OggOpusEncoder::WriteFile(const EncoderParams p, const AudioData * d, const std::string & path) { assert(d->samples.size() > 0); OpusEncoder * enc; enc = opus_encoder_create(48000, 1, OPUS_APPLICATION_AUDIO, nullptr); // How big should this be? std::vector<uint8_t> encodedBuffer(1024); auto encoded_size = opus_encode_float(enc, d->samples.data(), d->frameSize, encodedBuffer.data(), encodedBuffer.size()); // Cast away const because we know what we are doing (Hopefully?) float * sampleData = const_cast<float *>(d->samples.data()); const size_t sampleDataSize = d->samples.size(); return EncoderError::NoError; } <commit_msg>oggwriter (header + tags) for opus<commit_after>/* Copyright (c) 2015, Dimitri Diakopoulos 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fstream> #include "WavEncoder.h" using namespace nqr; static inline void to_bytes(uint8_t value, char * arr) { arr[0] = (value) & 0xFF; } static inline void to_bytes(uint16_t value, char * arr) { arr[0] = (value) & 0xFF; arr[1] = (value >> 8) & 0xFF; } static inline void to_bytes(uint32_t value, char * arr) { arr[0] = (value) & 0xFF; arr[1] = (value >> 8) & 0xFF; arr[2] = (value >> 16) & 0xFF; arr[3] = (value >> 24) & 0xFF; } //////////////////////////// // Wave File Encoding // //////////////////////////// int WavEncoder::WriteFile(const EncoderParams p, const AudioData * d, const std::string & path) { assert(d->samples.size() > 0); // Cast away const because we know what we are doing (Hopefully?) float * sampleData = const_cast<float *>(d->samples.data()); size_t sampleDataSize = d->samples.size(); std::vector<float> sampleDataOptionalMix; if (sampleDataSize <= 32) { return EncoderError::InsufficientSampleData; } if (d->channelCount < 1 || d->channelCount > 8) { return EncoderError::UnsupportedChannelConfiguration; } // Handle Channel Mixing -- // Mono => Stereo if (d->channelCount == 1 && p.channelCount == 2) { sampleDataOptionalMix.resize(sampleDataSize * 2); MonoToStereo(sampleData, sampleDataOptionalMix.data(), sampleDataSize); // Mix // Re-point data sampleData = sampleDataOptionalMix.data(); sampleDataSize = sampleDataOptionalMix.size(); } // Stereo => Mono else if (d->channelCount == 2 && p.channelCount == 1) { sampleDataOptionalMix.resize(sampleDataSize / 2); StereoToMono(sampleData, sampleDataOptionalMix.data(), sampleDataSize); // Mix // Re-point data sampleData = sampleDataOptionalMix.data(); sampleDataSize = sampleDataOptionalMix.size(); } else if (d->channelCount == p.channelCount) { // No op } else { return EncoderError::UnsupportedChannelMix; } // -- End Channel Mixing auto maxFileSizeInBytes = std::numeric_limits<uint32_t>::max(); auto samplesSizeInBytes = (sampleDataSize * GetFormatBitsPerSample(p.targetFormat)) / 8; // 64 arbitrary if ((samplesSizeInBytes - 64) >= maxFileSizeInBytes) { return EncoderError::BufferTooBig; } // Don't support PC64 or PCDBL if (GetFormatBitsPerSample(p.targetFormat) > 32) { return EncoderError::UnsupportedBitdepth; } std::ofstream fout(path.c_str(), std::ios::out | std::ios::binary); if (!fout.is_open()) { return EncoderError::FileIOError; } char * chunkSizeBuff = new char[4]; // Initial size (this is changed after we're done writing the file) to_bytes(uint32_t(36), chunkSizeBuff); // RIFF file header fout.write(GenerateChunkCodeChar('R', 'I', 'F', 'F'), 4); fout.write(chunkSizeBuff, 4); fout.write(GenerateChunkCodeChar('W', 'A', 'V', 'E'), 4); // Fmt header auto header = MakeWaveHeader(p, d->sampleRate); fout.write(reinterpret_cast<char*>(&header), sizeof(WaveChunkHeader)); auto sourceBits = GetFormatBitsPerSample(d->sourceFormat); auto targetBits = GetFormatBitsPerSample(p.targetFormat); //////////////////////////// //@todo - channel mixing! // //////////////////////////// // Write out fact chunk if (p.targetFormat == PCM_FLT) { uint32_t four = 4; uint32_t dataSz = int(sampleDataSize / p.channelCount); fout.write(GenerateChunkCodeChar('f', 'a', 'c', 't'), 4); fout.write(reinterpret_cast<const char *>(&four), 4); fout.write(reinterpret_cast<const char *>(&dataSz), 4); // Number of samples (per channel) } // Data header fout.write(GenerateChunkCodeChar('d', 'a', 't', 'a'), 4); // + data chunk size to_bytes(uint32_t(samplesSizeInBytes), chunkSizeBuff); fout.write(chunkSizeBuff, 4); if (targetBits <= sourceBits && p.targetFormat != PCM_FLT) { // At most need this number of bytes in our copy std::vector<uint8_t> samplesCopy(samplesSizeInBytes); ConvertFromFloat32(samplesCopy.data(), sampleData, sampleDataSize, p.targetFormat, p.dither); fout.write(reinterpret_cast<const char*>(samplesCopy.data()), samplesSizeInBytes); } else { // Handle PCFLT. Coming in from AudioData ensures we start with 32 bits, so we're fine // since we've also rejected formats with more than 32 bits above. fout.write(reinterpret_cast<const char*>(sampleData), samplesSizeInBytes); } // Padding byte if (isOdd(samplesSizeInBytes)) { const char * zero = ""; fout.write(zero, 1); } // Find size long totalSize = fout.tellp(); // Modify RIFF header fout.seekp(4); // Total size of the file, less 8 bytes for the RIFF header to_bytes(uint32_t(totalSize - 8), chunkSizeBuff); fout.write(chunkSizeBuff, 4); delete[] chunkSizeBuff; return EncoderError::NoError; } //////////////////////////// // Opus File Encoding // //////////////////////////// #include "opus/opusfile/include/opusfile.h" #include "ogg/ogg.h" typedef std::pair<std::string, std::string> metadata_type; class OggWriter { void write_to_ostream(bool flush) { while (ogg_stream_pageout(&oss, &page)) { ostream->write(reinterpret_cast<char*>(page.header), static_cast<std::streamsize>(page.header_len)); ostream->write(reinterpret_cast<char*>(page.body), static_cast<std::streamsize>(page.body_len)); } if (flush && ogg_stream_flush(&oss, &page)) { ostream->write(reinterpret_cast<char*>(page.header), static_cast<std::streamsize>(page.header_len)); ostream->write(reinterpret_cast<char*>(page.body), static_cast<std::streamsize>(page.body_len)); } } std::vector<char> make_header(int channel_count, int preskip, long sample_rate, int gain) { std::vector<char> header; std::array<char, 9> streacount = {{ 0x0, 0x1, 0x1, 0x2, 0x2, 0x3, 0x4, 0x5, 0x5 }}; std::array<char, 9> coupled_streacount = {{ 0x0, 0x0, 0x1, 0x1, 0x2, 0x2, 0x2, 0x2, 0x3 }}; std::array<char, 1> chan_map_1 = {{ 0x0 }}; std::array<char, 2> chan_map_2 = {{ 0x0, 0x1 }}; std::array<char, 3> chan_map_3 = {{ 0x0, 0x2, 0x1 }}; std::array<char, 4> chan_map_4 = {{ 0x0, 0x1, 0x2, 0x3 }}; std::array<char, 5> chan_map_5 = {{ 0x0, 0x4, 0x1, 0x2, 0x3 }}; std::array<char, 6> chan_map_6 = {{ 0x0, 0x4, 0x1, 0x2, 0x3, 0x5 }}; std::array<char, 7> chan_map_7 = {{ 0x0, 0x4, 0x1, 0x2, 0x3, 0x5, 0x6 }}; std::array<char, 8> chan_map_8 = {{ 0x0, 0x6, 0x1, 0x2, 0x3, 0x4, 0x5, 0x7 }}; std::array<char, 9> _preamble = {{ 'O', 'p', 'u', 's', 'H', 'e', 'a', 'd', 0x1 }}; std::array<char, 1> _channel_count; std::array<char, 2> _preskip; std::array<char, 4> _sample_rate; std::array<char, 2> _gain; std::array<char, 1> _channel_family = {{ 0x1 }}; to_bytes(uint8_t(channel_count), _channel_count.data()); to_bytes(uint16_t(preskip), _channel_count.data()); to_bytes(uint32_t(sample_rate), _channel_count.data()); to_bytes(uint16_t(gain), _channel_count.data()); header.insert(header.end(), _preamble.cbegin(), _preamble.cend()); header.insert(header.end(), _channel_count.cbegin(), _channel_count.cend()); header.insert(header.end(), _preskip.cbegin(), _preskip.cend()); header.insert(header.end(), _sample_rate.cbegin(), _sample_rate.cend()); header.insert(header.end(), _gain.cbegin(), _gain.cend()); header.insert(header.end(), _channel_family.cbegin(), _channel_family.cend()); header.push_back(streacount[channel_count]); header.push_back(coupled_streacount[channel_count]); switch (channel_count) { case 1: header.insert(header.end(), chan_map_1.cbegin(), chan_map_1.cend()); break; case 2: header.insert(header.end(), chan_map_2.cbegin(), chan_map_2.cend()); break; case 3: header.insert(header.end(), chan_map_3.cbegin(), chan_map_3.cend()); break; case 4: header.insert(header.end(), chan_map_4.cbegin(), chan_map_4.cend()); break; case 5: header.insert(header.end(), chan_map_5.cbegin(), chan_map_5.cend()); break; case 6: header.insert(header.end(), chan_map_6.cbegin(), chan_map_6.cend()); break; case 7: header.insert(header.end(), chan_map_7.cbegin(), chan_map_7.cend()); break; case 8: header.insert(header.end(), chan_map_8.cbegin(), chan_map_8.cend()); break; default: throw std::runtime_error("couldn't map channel data"); } return header; } std::vector<char> make_tags(const std::string & vendor, const std::vector<metadata_type> & metadata) { std::vector<char> tags; std::array<char, 8> _preamble = {{ 'O', 'p', 'u', 's', 'T', 'a', 'g', 's' }}; std::array<char, 4> _vendor_length; std::array<char, 4> _metadata_count; to_bytes(uint32_t(vendor.size()), _vendor_length.data()); to_bytes(uint32_t(metadata.size()), _metadata_count.data()); tags.insert(tags.end(), _preamble.cbegin() , _preamble.cend()); tags.insert(tags.end(), _vendor_length.cbegin() , _vendor_length.cend()); tags.insert(tags.end(), vendor.cbegin() , vendor.cend()); tags.insert(tags.end(), _metadata_count.cbegin() , _metadata_count.cend()); // Process metadata. for (const auto & metadata_entry : metadata) { std::array<char, 4> _metadata_entry_length; std::string entry = metadata_entry.first + "=" + metadata_entry.second; to_bytes(uint32_t(entry.size()), _metadata_entry_length.data()); tags.insert(tags.end(), _metadata_entry_length.cbegin(), _metadata_entry_length.cend()); tags.insert(tags.end(), entry.cbegin() , entry.cend()); } return tags; } ogg_int64_t packet_number; ogg_int64_t granule; ogg_page page; ogg_stream_state oss; int channel_count; long sample_rate; int bits_per_sample; std::ofstream * ostream; std::string description; std::vector<metadata_type> metadata; public: OggWriter(int channel_count, long sample_rate, int bits_per_sample, std::ofstream & stream, const std::vector<metadata_type> & metadata) { channel_count = channel_count; sample_rate = sample_rate; bits_per_sample = bits_per_sample; ostream = &stream; metadata = metadata; int oss_init_error; int packet_write_error; ogg_packet header_packet; ogg_packet tags_packet; std::vector<char> header_vector; std::vector<char> tags_vector; description = "Ogg"; packet_number = 0; granule = 0; // Validate parameters if (channel_count < 1 && channel_count > 255) throw std::runtime_error("Channel count must be between 1 and 255."); // Initialize the Ogg stream. oss_init_error = ogg_stream_init(&oss, 12345); if (oss_init_error) throw std::runtime_error("Could not initialize the Ogg stream state."); // Initialize the header packet. header_vector = make_header(channel_count, 3840, sample_rate, 0); header_packet.packet = reinterpret_cast<unsigned char*>(header_vector.data()); header_packet.bytes = header_vector.size(); header_packet.b_o_s = 1; header_packet.e_o_s = 0; header_packet.granulepos = 0; header_packet.packetno = packet_number++; // Initialize tags tags_vector = make_tags("libnyquist", metadata); tags_packet.packet = reinterpret_cast<unsigned char*>(tags_vector.data()); tags_packet.bytes = tags_vector.size(); tags_packet.b_o_s = 0; tags_packet.e_o_s = 0; tags_packet.granulepos = 0; tags_packet.packetno = packet_number++; // Write header page packet_write_error = ogg_stream_packetin(&oss, &header_packet); if (packet_write_error) throw std::runtime_error("Could not write header packet to the Ogg stream."); write_to_ostream(true); // Write tags page packet_write_error = ogg_stream_packetin(&oss, &tags_packet); if (packet_write_error) throw std::runtime_error("Could not write tags packet to the Ogg stream."); write_to_ostream(true); } ~OggWriter() { write_to_ostream(true); ogg_stream_clear(&oss); } bool write(char * data, std::streamsize length, size_t sample_count, bool end); }; // Opus only supports a 48k samplerate... int OggOpusEncoder::WriteFile(const EncoderParams p, const AudioData * d, const std::string & path) { assert(d->samples.size() > 0); OpusEncoder * enc; enc = opus_encoder_create(48000, 1, OPUS_APPLICATION_AUDIO, nullptr); // How big should this be? std::vector<uint8_t> encodedBuffer(1024); auto encoded_size = opus_encode_float(enc, d->samples.data(), d->frameSize, encodedBuffer.data(), encodedBuffer.size()); // Cast away const because we know what we are doing (Hopefully?) float * sampleData = const_cast<float *>(d->samples.data()); const size_t sampleDataSize = d->samples.size(); return EncoderError::NoError; } <|endoftext|>
<commit_before>#include <sys/errno.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/uio.h> #include <errno.h> #include <limits.h> #include <signal.h> #include <unistd.h> #include <common/buffer.h> #include <common/limits.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/io_system.h> #define IO_READ_BUFFER_SIZE 65536 IOSystem::Handle::Handle(int fd, Channel *owner) : log_("/io/system/handle"), fd_(fd), owner_(owner), close_callback_(NULL), close_action_(NULL), read_amount_(0), read_buffer_(), read_callback_(NULL), read_action_(NULL), write_buffer_(), write_callback_(NULL), write_action_(NULL) { } IOSystem::Handle::~Handle() { ASSERT(fd_ == -1); ASSERT(close_action_ == NULL); ASSERT(close_callback_ == NULL); ASSERT(read_action_ == NULL); ASSERT(read_callback_ == NULL); ASSERT(write_action_ == NULL); ASSERT(write_callback_ == NULL); } void IOSystem::Handle::close_callback(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(fd_ != -1); int rv = ::close(fd_); if (rv == -1) { switch (errno) { case EAGAIN: close_action_ = close_schedule(); break; default: close_callback_->event(Event(Event::Error, errno)); Action *a = EventSystem::instance()->schedule(close_callback_); close_action_ = a; close_callback_ = NULL; break; } return; } fd_ = -1; close_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(close_callback_); close_action_ = a; close_callback_ = NULL; } void IOSystem::Handle::close_cancel(void) { ASSERT(close_action_ != NULL); close_action_->cancel(); close_action_ = NULL; if (close_callback_ != NULL) { delete close_callback_; close_callback_ = NULL; } } Action * IOSystem::Handle::close_schedule(void) { ASSERT(close_action_ == NULL); Callback *cb = callback(this, &IOSystem::Handle::close_callback); Action *a = EventSystem::instance()->schedule(cb); return (a); } void IOSystem::Handle::read_callback(Event e) { read_action_->cancel(); read_action_ = NULL; switch (e.type_) { case Event::EOS: case Event::Done: break; case Event::Error: { DEBUG(log_) << "Poll returned error: " << e; read_callback_->event(e); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; return; } default: HALT(log_) << "Unexpected event: " << e; } size_t rlen; if (read_amount_ == 0) rlen = IO_READ_BUFFER_SIZE; else { rlen = read_amount_ - read_buffer_.length(); ASSERT(rlen != 0); if (rlen > IO_READ_BUFFER_SIZE) rlen = IO_READ_BUFFER_SIZE; } /* * A bit of discussion is warranted on this: * * In tack, IOV_MAX BufferSegments are allocated and read in to with * readv(2), and then the lengths are adjusted and the ones that are * empty are freed. It's also possible to set the expected lengths * first (and only allocate * roundup(rlen, BUFFER_SEGMENT_SIZE) / BUFFER_SEGMENT_SIZE * BufferSegments, though really IOV_MAX (or some chosen number) seems * a bit better since most of our reads right now are read_amount_==0) * and put them into a Buffer and trim the leftovers, which is a bit * nicer. * * Since our read_amount_ is usually 0, though, we're kind of at the * mercy chance (well, not really) as to how much data we will read, * which means a sizable amount of thrashing of memory; allocating and * freeing BufferSegments. * * By comparison, stack space is cheap in userland and allocating 64K * of it here is pretty painless. Reading to it is fast and then * copying only what we need into BufferSegments isn't very costly. * Indeed, since readv can't sparsely-populate each data pointer, it * has to do some data shuffling, already. Benchmarking would be a * good idea, but it seems like there are arguments both ways. Of * course, tack is very fast and this code path hasn't been thrashed * half so much. When tack is adjusted to use the IO system and Pipes * in the future, if performance degradation is noticeable, perhaps * it will worth it to switch. For now, absence any idea of the real * read sizes in the wild, doing nothing and not thrashing memory is * decidedly more appealing. */ uint8_t data[IO_READ_BUFFER_SIZE]; ssize_t len = ::read(fd_, data, sizeof data); if (len == -1) { switch (errno) { case EAGAIN: read_action_ = read_schedule(); break; default: read_callback_->event(Event(Event::Error, errno, read_buffer_)); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; read_buffer_.clear(); read_amount_ = 0; break; } return; } /* * XXX * If we get an EOS from EventPoll, should we just terminate after that * one read? How can we tell how much data is still available to be * read? Will we get it all in one read? Eventually, one would expect * to get a read with a length of 0, or an error, but will kevent even * continue to fire off read events? */ if (len == 0) { read_callback_->event(Event(Event::EOS, 0, read_buffer_)); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; read_buffer_.clear(); read_amount_ = 0; return; } read_buffer_.append(data, len); read_action_ = read_schedule(); } void IOSystem::Handle::read_cancel(void) { ASSERT(read_action_ != NULL); read_action_->cancel(); read_action_ = NULL; if (read_callback_ != NULL) { delete read_callback_; read_callback_ = NULL; } } Action * IOSystem::Handle::read_schedule(void) { ASSERT(read_action_ == NULL); if (!read_buffer_.empty() && read_buffer_.length() >= read_amount_) { if (read_amount_ == 0) read_amount_ = read_buffer_.length(); read_callback_->event(Event(Event::Done, 0, Buffer(read_buffer_, read_amount_))); Action *a = EventSystem::instance()->schedule(read_callback_); read_callback_ = NULL; read_buffer_.skip(read_amount_); read_amount_ = 0; return (a); } EventCallback *cb = callback(this, &IOSystem::Handle::read_callback); Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb); return (a); } void IOSystem::Handle::write_callback(Event e) { write_action_->cancel(); write_action_ = NULL; switch (e.type_) { case Event::Done: break; case Event::Error: { DEBUG(log_) << "Poll returned error: " << e; write_callback_->event(e); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; return; } default: HALT(log_) << "Unexpected event: " << e; } /* XXX This doesn't handle UDP nicely. Right? */ /* XXX If a UDP packet is > IOV_MAX segments, this will break it. */ struct iovec iov[IOV_MAX]; size_t iovcnt = write_buffer_.fill_iovec(iov, IOV_MAX); ssize_t len = ::writev(fd_, iov, iovcnt); if (len == -1) { switch (errno) { case EAGAIN: write_action_ = write_schedule(); break; default: write_callback_->event(Event(Event::Error, errno)); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; break; } return; } write_buffer_.skip(len); if (write_buffer_.empty()) { write_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; return; } write_action_ = write_schedule(); } void IOSystem::Handle::write_cancel(void) { ASSERT(write_action_ != NULL); write_action_->cancel(); write_action_ = NULL; if (write_callback_ != NULL) { delete write_callback_; write_callback_ = NULL; } } Action * IOSystem::Handle::write_schedule(void) { ASSERT(write_action_ == NULL); EventCallback *cb = callback(this, &IOSystem::Handle::write_callback); Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb); return (a); } IOSystem::IOSystem(void) : log_("/io/system"), handle_map_() { /* * Prepare system to handle IO. */ INFO(log_) << "Starting IO system."; /* * Disable SIGPIPE. * * Because errors are returned asynchronously and may occur at any time, * there may be a pending write to a file descriptor which has * previously thrown an error. There are changes that could be made to * the scheduler to work around this, but they are not desirable. */ if (::signal(SIGPIPE, SIG_IGN) == SIG_ERR) HALT(log_) << "Could not disable SIGPIPE."; /* * Up the file descriptor limit. * * Probably this should be configurable, but there's no harm on modern * systems and for the performance-critical applications using the IO * system, more file descriptors is better. */ struct rlimit rlim; int rv = ::getrlimit(RLIMIT_NOFILE, &rlim); if (rv == 0) { if (rlim.rlim_cur < rlim.rlim_max) { rlim.rlim_cur = rlim.rlim_max; rv = ::setrlimit(RLIMIT_NOFILE, &rlim); if (rv == -1) { INFO(log_) << "Unable to increase file descriptor limit."; } } } else { INFO(log_) << "Unable to get file descriptor limit."; } } IOSystem::~IOSystem() { ASSERT(handle_map_.empty()); } void IOSystem::attach(int fd, Channel *owner) { ASSERT(handle_map_.find(handle_key_t(fd, owner)) == handle_map_.end()); handle_map_[handle_key_t(fd, owner)] = new IOSystem::Handle(fd, owner); } void IOSystem::detach(int fd, Channel *owner) { handle_map_t::iterator it; IOSystem::Handle *h; it = handle_map_.find(handle_key_t(fd, owner)); ASSERT(it != handle_map_.end()); h = it->second; ASSERT(h != NULL); ASSERT(h->owner_ == owner); handle_map_.erase(it); delete h; } Action * IOSystem::close(int fd, Channel *owner, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->close_callback_ == NULL); ASSERT(h->close_action_ == NULL); ASSERT(h->read_callback_ == NULL); ASSERT(h->read_action_ == NULL); ASSERT(h->write_callback_ == NULL); ASSERT(h->write_action_ == NULL); ASSERT(h->fd_ != -1); h->close_callback_ = cb; h->close_action_ = h->close_schedule(); return (cancellation(h, &IOSystem::Handle::close_cancel)); } Action * IOSystem::read(int fd, Channel *owner, size_t amount, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->read_callback_ == NULL); ASSERT(h->read_action_ == NULL); h->read_amount_ = amount; h->read_callback_ = cb; h->read_action_ = h->read_schedule(); return (cancellation(h, &IOSystem::Handle::read_cancel)); } Action * IOSystem::write(int fd, Channel *owner, Buffer *buffer, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->write_callback_ == NULL); ASSERT(h->write_action_ == NULL); ASSERT(h->write_buffer_.empty()); ASSERT(!buffer->empty()); h->write_buffer_.append(buffer); buffer->clear(); h->write_callback_ = cb; h->write_action_ = h->write_schedule(); return (cancellation(h, &IOSystem::Handle::write_cancel)); } <commit_msg>Reword a comment.<commit_after>#include <sys/errno.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/uio.h> #include <errno.h> #include <limits.h> #include <signal.h> #include <unistd.h> #include <common/buffer.h> #include <common/limits.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/io_system.h> #define IO_READ_BUFFER_SIZE 65536 IOSystem::Handle::Handle(int fd, Channel *owner) : log_("/io/system/handle"), fd_(fd), owner_(owner), close_callback_(NULL), close_action_(NULL), read_amount_(0), read_buffer_(), read_callback_(NULL), read_action_(NULL), write_buffer_(), write_callback_(NULL), write_action_(NULL) { } IOSystem::Handle::~Handle() { ASSERT(fd_ == -1); ASSERT(close_action_ == NULL); ASSERT(close_callback_ == NULL); ASSERT(read_action_ == NULL); ASSERT(read_callback_ == NULL); ASSERT(write_action_ == NULL); ASSERT(write_callback_ == NULL); } void IOSystem::Handle::close_callback(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(fd_ != -1); int rv = ::close(fd_); if (rv == -1) { switch (errno) { case EAGAIN: close_action_ = close_schedule(); break; default: close_callback_->event(Event(Event::Error, errno)); Action *a = EventSystem::instance()->schedule(close_callback_); close_action_ = a; close_callback_ = NULL; break; } return; } fd_ = -1; close_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(close_callback_); close_action_ = a; close_callback_ = NULL; } void IOSystem::Handle::close_cancel(void) { ASSERT(close_action_ != NULL); close_action_->cancel(); close_action_ = NULL; if (close_callback_ != NULL) { delete close_callback_; close_callback_ = NULL; } } Action * IOSystem::Handle::close_schedule(void) { ASSERT(close_action_ == NULL); Callback *cb = callback(this, &IOSystem::Handle::close_callback); Action *a = EventSystem::instance()->schedule(cb); return (a); } void IOSystem::Handle::read_callback(Event e) { read_action_->cancel(); read_action_ = NULL; switch (e.type_) { case Event::EOS: case Event::Done: break; case Event::Error: { DEBUG(log_) << "Poll returned error: " << e; read_callback_->event(e); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; return; } default: HALT(log_) << "Unexpected event: " << e; } size_t rlen; if (read_amount_ == 0) rlen = IO_READ_BUFFER_SIZE; else { rlen = read_amount_ - read_buffer_.length(); ASSERT(rlen != 0); if (rlen > IO_READ_BUFFER_SIZE) rlen = IO_READ_BUFFER_SIZE; } /* * A bit of discussion is warranted on this: * * In tack, IOV_MAX BufferSegments are allocated and read in to with * readv(2), and then the lengths are adjusted and the ones that are * empty are freed. It's also possible to set the expected lengths * first (and only allocate * roundup(rlen, BUFFER_SEGMENT_SIZE) / BUFFER_SEGMENT_SIZE * BufferSegments, though really IOV_MAX (or some chosen number) seems * a bit better since most of our reads right now are read_amount_==0) * and put them into a Buffer and trim the leftovers, which is a bit * nicer. * * Since our read_amount_ is usually 0, though, we're kind of at the * mercy chance (well, not really) as to how much data we will read, * which means a sizable amount of thrashing of memory; allocating and * freeing BufferSegments. * * By comparison, stack space is cheap in userland and allocating 64K * of it here is pretty painless. Reading to it is fast and then * copying only what we need into BufferSegments isn't very costly. * Indeed, since readv can't sparsely-populate each data pointer, it * has to do some data shuffling, already. Benchmarking would be a * good idea, but it seems like there are arguments both ways. Of * course, tack is very fast and this code path hasn't been thrashed * half so much. When tack is adjusted to use the IO system and Pipes * in the future, if performance degradation is noticeable, perhaps * it will worth it to switch. For now, absence any idea of the real * read sizes in the wild, doing nothing and not thrashing memory is * decidedly more appealing. */ uint8_t data[IO_READ_BUFFER_SIZE]; ssize_t len = ::read(fd_, data, sizeof data); if (len == -1) { switch (errno) { case EAGAIN: read_action_ = read_schedule(); break; default: read_callback_->event(Event(Event::Error, errno, read_buffer_)); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; read_buffer_.clear(); read_amount_ = 0; break; } return; } /* * XXX * If we get a short read from readv and detected EOS from EventPoll is * that good enough, instead? We can keep reading until we get a 0, sure, * but if things other than network conditions influence whether reads * would block (and whether non-blocking reads return), there could be * more data waiting, and so we shouldn't just use a short read as an * indicator? */ if (len == 0) { read_callback_->event(Event(Event::EOS, 0, read_buffer_)); Action *a = EventSystem::instance()->schedule(read_callback_); read_action_ = a; read_callback_ = NULL; read_buffer_.clear(); read_amount_ = 0; return; } read_buffer_.append(data, len); read_action_ = read_schedule(); } void IOSystem::Handle::read_cancel(void) { ASSERT(read_action_ != NULL); read_action_->cancel(); read_action_ = NULL; if (read_callback_ != NULL) { delete read_callback_; read_callback_ = NULL; } } Action * IOSystem::Handle::read_schedule(void) { ASSERT(read_action_ == NULL); if (!read_buffer_.empty() && read_buffer_.length() >= read_amount_) { if (read_amount_ == 0) read_amount_ = read_buffer_.length(); read_callback_->event(Event(Event::Done, 0, Buffer(read_buffer_, read_amount_))); Action *a = EventSystem::instance()->schedule(read_callback_); read_callback_ = NULL; read_buffer_.skip(read_amount_); read_amount_ = 0; return (a); } EventCallback *cb = callback(this, &IOSystem::Handle::read_callback); Action *a = EventSystem::instance()->poll(EventPoll::Readable, fd_, cb); return (a); } void IOSystem::Handle::write_callback(Event e) { write_action_->cancel(); write_action_ = NULL; switch (e.type_) { case Event::Done: break; case Event::Error: { DEBUG(log_) << "Poll returned error: " << e; write_callback_->event(e); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; return; } default: HALT(log_) << "Unexpected event: " << e; } /* XXX This doesn't handle UDP nicely. Right? */ /* XXX If a UDP packet is > IOV_MAX segments, this will break it. */ struct iovec iov[IOV_MAX]; size_t iovcnt = write_buffer_.fill_iovec(iov, IOV_MAX); ssize_t len = ::writev(fd_, iov, iovcnt); if (len == -1) { switch (errno) { case EAGAIN: write_action_ = write_schedule(); break; default: write_callback_->event(Event(Event::Error, errno)); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; break; } return; } write_buffer_.skip(len); if (write_buffer_.empty()) { write_callback_->event(Event(Event::Done, 0)); Action *a = EventSystem::instance()->schedule(write_callback_); write_action_ = a; write_callback_ = NULL; return; } write_action_ = write_schedule(); } void IOSystem::Handle::write_cancel(void) { ASSERT(write_action_ != NULL); write_action_->cancel(); write_action_ = NULL; if (write_callback_ != NULL) { delete write_callback_; write_callback_ = NULL; } } Action * IOSystem::Handle::write_schedule(void) { ASSERT(write_action_ == NULL); EventCallback *cb = callback(this, &IOSystem::Handle::write_callback); Action *a = EventSystem::instance()->poll(EventPoll::Writable, fd_, cb); return (a); } IOSystem::IOSystem(void) : log_("/io/system"), handle_map_() { /* * Prepare system to handle IO. */ INFO(log_) << "Starting IO system."; /* * Disable SIGPIPE. * * Because errors are returned asynchronously and may occur at any time, * there may be a pending write to a file descriptor which has * previously thrown an error. There are changes that could be made to * the scheduler to work around this, but they are not desirable. */ if (::signal(SIGPIPE, SIG_IGN) == SIG_ERR) HALT(log_) << "Could not disable SIGPIPE."; /* * Up the file descriptor limit. * * Probably this should be configurable, but there's no harm on modern * systems and for the performance-critical applications using the IO * system, more file descriptors is better. */ struct rlimit rlim; int rv = ::getrlimit(RLIMIT_NOFILE, &rlim); if (rv == 0) { if (rlim.rlim_cur < rlim.rlim_max) { rlim.rlim_cur = rlim.rlim_max; rv = ::setrlimit(RLIMIT_NOFILE, &rlim); if (rv == -1) { INFO(log_) << "Unable to increase file descriptor limit."; } } } else { INFO(log_) << "Unable to get file descriptor limit."; } } IOSystem::~IOSystem() { ASSERT(handle_map_.empty()); } void IOSystem::attach(int fd, Channel *owner) { ASSERT(handle_map_.find(handle_key_t(fd, owner)) == handle_map_.end()); handle_map_[handle_key_t(fd, owner)] = new IOSystem::Handle(fd, owner); } void IOSystem::detach(int fd, Channel *owner) { handle_map_t::iterator it; IOSystem::Handle *h; it = handle_map_.find(handle_key_t(fd, owner)); ASSERT(it != handle_map_.end()); h = it->second; ASSERT(h != NULL); ASSERT(h->owner_ == owner); handle_map_.erase(it); delete h; } Action * IOSystem::close(int fd, Channel *owner, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->close_callback_ == NULL); ASSERT(h->close_action_ == NULL); ASSERT(h->read_callback_ == NULL); ASSERT(h->read_action_ == NULL); ASSERT(h->write_callback_ == NULL); ASSERT(h->write_action_ == NULL); ASSERT(h->fd_ != -1); h->close_callback_ = cb; h->close_action_ = h->close_schedule(); return (cancellation(h, &IOSystem::Handle::close_cancel)); } Action * IOSystem::read(int fd, Channel *owner, size_t amount, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->read_callback_ == NULL); ASSERT(h->read_action_ == NULL); h->read_amount_ = amount; h->read_callback_ = cb; h->read_action_ = h->read_schedule(); return (cancellation(h, &IOSystem::Handle::read_cancel)); } Action * IOSystem::write(int fd, Channel *owner, Buffer *buffer, EventCallback *cb) { IOSystem::Handle *h; h = handle_map_[handle_key_t(fd, owner)]; ASSERT(h != NULL); ASSERT(h->write_callback_ == NULL); ASSERT(h->write_action_ == NULL); ASSERT(h->write_buffer_.empty()); ASSERT(!buffer->empty()); h->write_buffer_.append(buffer); buffer->clear(); h->write_callback_ = cb; h->write_action_ = h->write_schedule(); return (cancellation(h, &IOSystem::Handle::write_cancel)); } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DATABASE_HH_ #define DATABASE_HH_ #include "core/sstring.hh" #include "core/shared_ptr.hh" #include "net/byteorder.hh" #include "utils/UUID.hh" #include "db_clock.hh" #include "gc_clock.hh" #include <functional> #include <boost/any.hpp> #include <cstdint> #include <boost/variant.hpp> #include <unordered_map> #include <map> #include <set> #include <vector> #include <iostream> #include <boost/functional/hash.hpp> #include <experimental/optional> #include <string.h> #include "types.hh" #include "tuple.hh" #include "core/future.hh" #include "cql3/column_specification.hh" #include <limits> #include <cstddef> #include "schema.hh" using partition_key_type = tuple_type<>; using clustering_key_type = tuple_type<>; using clustering_prefix_type = tuple_prefix; using partition_key = bytes; using clustering_key = bytes; using clustering_prefix = clustering_prefix_type::value_type; namespace api { using timestamp_type = int64_t; timestamp_type constexpr missing_timestamp = std::numeric_limits<timestamp_type>::min(); timestamp_type constexpr min_timestamp = std::numeric_limits<timestamp_type>::min() + 1; timestamp_type constexpr max_timestamp = std::numeric_limits<timestamp_type>::max(); } /** * Represents deletion operation. Can be commuted with other tombstones via apply() method. * Can be empty. * */ struct tombstone final { api::timestamp_type timestamp; gc_clock::time_point ttl; tombstone(api::timestamp_type timestamp, gc_clock::time_point ttl) : timestamp(timestamp) , ttl(ttl) { } tombstone() : tombstone(api::missing_timestamp, {}) { } int compare(const tombstone& t) const { if (timestamp < t.timestamp) { return -1; } else if (timestamp > t.timestamp) { return 1; } else if (ttl < t.ttl) { return -1; } else if (ttl > t.ttl) { return 1; } else { return 0; } } bool operator<(const tombstone& t) const { return compare(t) < 0; } bool operator<=(const tombstone& t) const { return compare(t) <= 0; } bool operator>(const tombstone& t) const { return compare(t) > 0; } bool operator>=(const tombstone& t) const { return compare(t) >= 0; } bool operator==(const tombstone& t) const { return compare(t) == 0; } bool operator!=(const tombstone& t) const { return compare(t) != 0; } explicit operator bool() const { return timestamp != api::missing_timestamp; } void apply(const tombstone& t) { if (*this < t) { *this = t; } } friend std::ostream& operator<<(std::ostream& out, const tombstone& t) { return out << "{timestamp=" << t.timestamp << ", ttl=" << t.ttl.time_since_epoch().count() << "}"; } }; using ttl_opt = std::experimental::optional<gc_clock::time_point>; struct atomic_cell final { struct dead { gc_clock::time_point ttl; }; struct live { ttl_opt ttl; bytes value; }; api::timestamp_type timestamp; boost::variant<dead, live> value; bool is_live() const { return value.which() == 1; } // Call only when is_live() == true const live& as_live() const { return boost::get<live>(value); } // Call only when is_live() == false const dead& as_dead() const { return boost::get<dead>(value); } }; using row = std::map<column_id, boost::any>; struct deletable_row final { tombstone t; row cells; }; using row_tombstone_set = std::map<bytes, tombstone, serialized_compare>; class mutation_partition final { private: tombstone _tombstone; row _static_row; std::map<clustering_key, deletable_row, key_compare> _rows; row_tombstone_set _row_tombstones; public: mutation_partition(schema_ptr s) : _rows(key_compare(s->clustering_key_type)) , _row_tombstones(serialized_compare(s->clustering_key_prefix_type)) { } void apply(tombstone t) { _tombstone.apply(t); } void apply_delete(schema_ptr schema, const clustering_prefix& prefix, tombstone t) { if (prefix.empty()) { apply(t); } else if (prefix.size() == schema->clustering_key.size()) { _rows[serialize_value(*schema->clustering_key_type, prefix)].t.apply(t); } else { apply_row_tombstone(schema, {serialize_value(*schema->clustering_key_prefix_type, prefix), t}); } } void apply_row_tombstone(schema_ptr schema, bytes prefix, tombstone t) { apply_row_tombstone(schema, {std::move(prefix), std::move(t)}); } void apply_row_tombstone(schema_ptr schema, std::pair<bytes, tombstone> row_tombstone) { auto& prefix = row_tombstone.first; auto i = _row_tombstones.lower_bound(prefix); if (i == _row_tombstones.end() || !schema->clustering_key_prefix_type->equal(prefix, i->first) || row_tombstone.second > i->second) { _row_tombstones.insert(i, std::move(row_tombstone)); } } void apply(schema_ptr schema, mutation_partition&& p); row& static_row() { return _static_row; } row& clustered_row(const clustering_key& key) { return _rows[key].cells; } row& clustered_row(clustering_key&& key) { return _rows[std::move(key)].cells; } row* find_row(const clustering_key& key) { auto i = _rows.find(key); if (i == _rows.end()) { return nullptr; } return &i->second.cells; } }; class mutation final { public: schema_ptr schema; partition_key key; mutation_partition p; public: mutation(partition_key key_, schema_ptr schema_) : schema(std::move(schema_)) , key(std::move(key_)) , p(schema) { } mutation(mutation&&) = default; mutation(const mutation&) = delete; void set_static_cell(const column_definition& def, boost::any value) { p.static_row()[def.id] = std::move(value); } void set_clustered_cell(const clustering_prefix& prefix, const column_definition& def, boost::any value) { auto& row = p.clustered_row(serialize_value(*schema->clustering_key_type, prefix)); row[def.id] = std::move(value); } void set_clustered_cell(const clustering_key& key, const column_definition& def, boost::any value) { auto& row = p.clustered_row(key); row[def.id] = std::move(value); } }; struct column_family { column_family(schema_ptr schema); mutation_partition& find_or_create_partition(const bytes& key); row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key); mutation_partition* find_partition(const bytes& key); row* find_row(const bytes& partition_key, const bytes& clustering_key); schema_ptr _schema; // partition key -> partition std::map<bytes, mutation_partition, key_compare> partitions; void apply(mutation&& m); }; class keyspace { public: std::unordered_map<sstring, column_family> column_families; static future<keyspace> populate(sstring datadir); schema_ptr find_schema(sstring cf_name); column_family* find_column_family(sstring cf_name); }; class database { public: std::unordered_map<sstring, keyspace> keyspaces; static future<database> populate(sstring datadir); keyspace* find_keyspace(sstring name); }; #endif /* DATABASE_HH_ */ <commit_msg>db: Add mutation_partition::tombstone_for_row()<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DATABASE_HH_ #define DATABASE_HH_ #include "core/sstring.hh" #include "core/shared_ptr.hh" #include "net/byteorder.hh" #include "utils/UUID.hh" #include "db_clock.hh" #include "gc_clock.hh" #include <functional> #include <boost/any.hpp> #include <cstdint> #include <boost/variant.hpp> #include <unordered_map> #include <map> #include <set> #include <vector> #include <iostream> #include <boost/functional/hash.hpp> #include <experimental/optional> #include <string.h> #include "types.hh" #include "tuple.hh" #include "core/future.hh" #include "cql3/column_specification.hh" #include <limits> #include <cstddef> #include "schema.hh" using partition_key_type = tuple_type<>; using clustering_key_type = tuple_type<>; using clustering_prefix_type = tuple_prefix; using partition_key = bytes; using clustering_key = bytes; using clustering_prefix = clustering_prefix_type::value_type; namespace api { using timestamp_type = int64_t; timestamp_type constexpr missing_timestamp = std::numeric_limits<timestamp_type>::min(); timestamp_type constexpr min_timestamp = std::numeric_limits<timestamp_type>::min() + 1; timestamp_type constexpr max_timestamp = std::numeric_limits<timestamp_type>::max(); } /** * Represents deletion operation. Can be commuted with other tombstones via apply() method. * Can be empty. * */ struct tombstone final { api::timestamp_type timestamp; gc_clock::time_point ttl; tombstone(api::timestamp_type timestamp, gc_clock::time_point ttl) : timestamp(timestamp) , ttl(ttl) { } tombstone() : tombstone(api::missing_timestamp, {}) { } int compare(const tombstone& t) const { if (timestamp < t.timestamp) { return -1; } else if (timestamp > t.timestamp) { return 1; } else if (ttl < t.ttl) { return -1; } else if (ttl > t.ttl) { return 1; } else { return 0; } } bool operator<(const tombstone& t) const { return compare(t) < 0; } bool operator<=(const tombstone& t) const { return compare(t) <= 0; } bool operator>(const tombstone& t) const { return compare(t) > 0; } bool operator>=(const tombstone& t) const { return compare(t) >= 0; } bool operator==(const tombstone& t) const { return compare(t) == 0; } bool operator!=(const tombstone& t) const { return compare(t) != 0; } explicit operator bool() const { return timestamp != api::missing_timestamp; } void apply(const tombstone& t) { if (*this < t) { *this = t; } } friend std::ostream& operator<<(std::ostream& out, const tombstone& t) { return out << "{timestamp=" << t.timestamp << ", ttl=" << t.ttl.time_since_epoch().count() << "}"; } }; using ttl_opt = std::experimental::optional<gc_clock::time_point>; struct atomic_cell final { struct dead { gc_clock::time_point ttl; }; struct live { ttl_opt ttl; bytes value; }; api::timestamp_type timestamp; boost::variant<dead, live> value; bool is_live() const { return value.which() == 1; } // Call only when is_live() == true const live& as_live() const { return boost::get<live>(value); } // Call only when is_live() == false const dead& as_dead() const { return boost::get<dead>(value); } }; using row = std::map<column_id, boost::any>; struct deletable_row final { tombstone t; row cells; }; using row_tombstone_set = std::map<bytes, tombstone, serialized_compare>; class mutation_partition final { private: tombstone _tombstone; row _static_row; std::map<clustering_key, deletable_row, key_compare> _rows; row_tombstone_set _row_tombstones; public: mutation_partition(schema_ptr s) : _rows(key_compare(s->clustering_key_type)) , _row_tombstones(serialized_compare(s->clustering_key_prefix_type)) { } void apply(tombstone t) { _tombstone.apply(t); } void apply_delete(schema_ptr schema, const clustering_prefix& prefix, tombstone t) { if (prefix.empty()) { apply(t); } else if (prefix.size() == schema->clustering_key.size()) { _rows[serialize_value(*schema->clustering_key_type, prefix)].t.apply(t); } else { apply_row_tombstone(schema, {serialize_value(*schema->clustering_key_prefix_type, prefix), t}); } } void apply_row_tombstone(schema_ptr schema, bytes prefix, tombstone t) { apply_row_tombstone(schema, {std::move(prefix), std::move(t)}); } void apply_row_tombstone(schema_ptr schema, std::pair<bytes, tombstone> row_tombstone) { auto& prefix = row_tombstone.first; auto i = _row_tombstones.lower_bound(prefix); if (i == _row_tombstones.end() || !schema->clustering_key_prefix_type->equal(prefix, i->first) || row_tombstone.second > i->second) { _row_tombstones.insert(i, std::move(row_tombstone)); } } void apply(schema_ptr schema, mutation_partition&& p); row& static_row() { return _static_row; } row& clustered_row(const clustering_key& key) { return _rows[key].cells; } row& clustered_row(clustering_key&& key) { return _rows[std::move(key)].cells; } row* find_row(const clustering_key& key) { auto i = _rows.find(key); if (i == _rows.end()) { return nullptr; } return &i->second.cells; } /** * Returns the base tombstone for all cells of given clustering row. Such tombstone * holds all information necessary to decide whether cells in a row are deleted or not, * in addition to any information inside individual cells. */ tombstone tombstone_for_row(schema_ptr schema, const clustering_key& key) { tombstone t = _tombstone; auto i = _row_tombstones.lower_bound(key); if (i != _row_tombstones.end() && schema->clustering_key_prefix_type->is_prefix_of(i->first, key)) { t.apply(i->second); } auto j = _rows.find(key); if (j != _rows.end()) { t.apply(j->second.t); } return t; } }; class mutation final { public: schema_ptr schema; partition_key key; mutation_partition p; public: mutation(partition_key key_, schema_ptr schema_) : schema(std::move(schema_)) , key(std::move(key_)) , p(schema) { } mutation(mutation&&) = default; mutation(const mutation&) = delete; void set_static_cell(const column_definition& def, boost::any value) { p.static_row()[def.id] = std::move(value); } void set_clustered_cell(const clustering_prefix& prefix, const column_definition& def, boost::any value) { auto& row = p.clustered_row(serialize_value(*schema->clustering_key_type, prefix)); row[def.id] = std::move(value); } void set_clustered_cell(const clustering_key& key, const column_definition& def, boost::any value) { auto& row = p.clustered_row(key); row[def.id] = std::move(value); } }; struct column_family { column_family(schema_ptr schema); mutation_partition& find_or_create_partition(const bytes& key); row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key); mutation_partition* find_partition(const bytes& key); row* find_row(const bytes& partition_key, const bytes& clustering_key); schema_ptr _schema; // partition key -> partition std::map<bytes, mutation_partition, key_compare> partitions; void apply(mutation&& m); }; class keyspace { public: std::unordered_map<sstring, column_family> column_families; static future<keyspace> populate(sstring datadir); schema_ptr find_schema(sstring cf_name); column_family* find_column_family(sstring cf_name); }; class database { public: std::unordered_map<sstring, keyspace> keyspaces; static future<database> populate(sstring datadir); keyspace* find_keyspace(sstring name); }; #endif /* DATABASE_HH_ */ <|endoftext|>
<commit_before>#include "model.h" #include "model_io.h" #include "modelwidget.h" #include "figurepainter.h" #include "recognition.h" #include "layouting.h" #include <QPainter> #include <QMouseEvent> #include <QInputDialog> #include <QMessageBox> #include <QWheelEvent> #include <QGesture> #include <QDebug> #include <QTimer> #include <iostream> Ui::ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent), mouseAction(MouseAction::None), _gridStep(0), _showTrack(true), _showRecognitionResult(true), _storeTracks(false) { setFocusPolicy(Qt::FocusPolicy::StrongFocus); grabGesture(Qt::PinchGesture); } void drawTrack(QPainter &painter, Scaler &scaler, const Track &track) { QPen oldPen = painter.pen(); std::vector<double> speeds = calculateRelativeSpeeds(track); for (size_t i = 0; i + 1 < track.size(); i++) { double k = speeds[i] * 510; QColor color; if (k <= 255) color = QColor(255, k, 0); else color = QColor(255 - (k - 255), 255, 0); QPen pen = oldPen; pen.setColor(color); painter.setPen(pen); painter.drawLine(scaler(track[i]), scaler(track[i + 1])); } painter.setPen(oldPen); } int Ui::ModelWidget::gridStep() { return _gridStep; } void Ui::ModelWidget::setGridStep(int newGridStep) { if (newGridStep < 0) { throw std::runtime_error("Grid step should be >= 0"); } _gridStep = newGridStep; update(); } double Ui::ModelWidget::scaleFactor() { return scaler.scaleFactor; } void Ui::ModelWidget::setScaleFactor(double newScaleFactor) { if (!(newScaleFactor >= 0.01)) { // >= instead of < for NaNs throw std::runtime_error("Scale factor should be >= 0.01"); } scaler.scaleFactor = newScaleFactor; emit scaleFactorChanged(); update(); } bool Ui::ModelWidget::showTrack() { return _showTrack; } void Ui::ModelWidget::setShowTrack(bool newShowTrack) { _showTrack = newShowTrack; } bool Ui::ModelWidget::showRecognitionResult() { return _showRecognitionResult; } void Ui::ModelWidget::setShowRecognitionResult(bool newShowRecognitionResult) { _showRecognitionResult = newShowRecognitionResult; } bool Ui::ModelWidget::storeTracks() { return _storeTracks; } void Ui::ModelWidget::setStoreTracks(bool newStoreTracks) { _storeTracks = newStoreTracks; } void Ui::ModelWidget::setModel(Model model) { commitedModel = std::move(model); previousModels.clear(); redoModels.clear(); emit canUndoChanged(); emit canRedoChanged(); extraTracks = std::vector<Track>(); } Model &Ui::ModelWidget::getModel() { return commitedModel; } void Ui::ModelWidget::addModelExtraTrack(Track track) { extraTracks.push_back(std::move(track)); } bool Ui::ModelWidget::canUndo() { return !previousModels.empty(); } void Ui::ModelWidget::undo() { if (!canUndo()) { throw std::runtime_error("Cannot undo"); } redoModels.push_front(std::move(commitedModel)); commitedModel = std::move(previousModels.back()); previousModels.pop_back(); if (!canUndo()) { emit canUndoChanged(); } emit canRedoChanged(); update(); } bool Ui::ModelWidget::canRedo() { return !redoModels.empty(); } void Ui::ModelWidget::redo() { if (!canRedo()) { throw std::runtime_error("Cannot redo"); } previousModels.push_back(std::move(commitedModel)); commitedModel = std::move(redoModels.front()); redoModels.pop_front(); if (!canRedo()) { canRedoChanged(); } canUndoChanged(); update(); } double roundDownToMultiple(double x, double multiple) { return floor(x / multiple) * multiple; } void Ui::ModelWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.fillRect(QRect(QPoint(), size()), Qt::white); QFont font; font.setPointSizeF(10 * scaler.scaleFactor); painter.setFont(font); QPen pen(Qt::black); pen.setWidthF(scaler.scaleFactor); painter.setPen(pen); FigurePainter fpainter(painter, scaler); if (gridStep() > 0) { int step = gridStep(); // Calculating visible area Point p1 = scaler(QPointF(0, 0)); Point p2 = scaler(QPointF(width(), height())); if (p1.x > p2.x) { std::swap(p1.x, p2.x); } if (p1.y > p2.y) { std::swap(p1.y, p2.y); } // Finding starting point for the grid p1.x = roundDownToMultiple(p1.x, step); p1.y = roundDownToMultiple(p1.y, step); // Drawing QPen pen(QColor(192, 192, 192, 255)); pen.setStyle(Qt::DashLine); painter.setPen(pen); for (int x = p1.x; x <= p2.x; x += step) { painter.drawLine(scaler(Point(x, p1.y)), scaler(Point(x, p2.y))); } for (int y = p1.y; y <= p2.y; y += step) { painter.drawLine(scaler(Point(p1.x, y)), scaler(Point(p2.x, y))); } } Model copiedModel; Model &modelToDraw = (lastTrack.empty() || !showRecognitionResult()) ? commitedModel : (copiedModel = commitedModel); PFigure modified = showRecognitionResult() ? recognize(lastTrack, modelToDraw) : nullptr; for (PFigure fig : modelToDraw) { if (fig == modified) { pen.setColor(Qt::magenta); } else if (fig == modelToDraw.selectedFigure) { pen.setColor(Qt::blue); } else { pen.setColor(Qt::black); } painter.setPen(pen); fig->visit(fpainter); } pen.setColor(QColor(255, 0, 0, 16)); pen.setWidth(3 * scaler.scaleFactor); painter.setPen(pen); if (showTrack()) { drawTrack(painter, scaler, lastTrack); for (const Track &track : visibleTracks) { drawTrack(painter, scaler, track); } } for (const Track &track : extraTracks) { drawTrack(painter, scaler, track); } } void Ui::ModelWidget::mousePressEvent(QMouseEvent *event) { lastTrack = Track(); if (event->modifiers().testFlag(Qt::ShiftModifier) || event->buttons().testFlag(Qt::MiddleButton)) { mouseAction = MouseAction::ViewpointMove; viewpointMoveStart = event->pos(); viewpointMoveOldScaler = scaler; setCursor(Qt::ClosedHandCursor); } else { mouseAction = MouseAction::TrackActive; trackTimer.start(); lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed())); } update(); } void Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) { if (mouseAction == MouseAction::ViewpointMove) { scaler = viewpointMoveOldScaler; scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos()); update(); } else if (mouseAction == MouseAction::TrackActive) { lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed())); if (showTrack() || showRecognitionResult()) { update(); } } else { event->ignore(); } } void Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) { if (mouseAction == MouseAction::None) { event->ignore(); return; } if (mouseAction == MouseAction::ViewpointMove) { mouseAction = MouseAction::None; setCursor(Qt::ArrowCursor); scaler = viewpointMoveOldScaler; scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos()); update(); return; } assert(mouseAction == MouseAction::TrackActive); mouseAction = MouseAction::None; lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed())); if (storeTracks()) { QFile file(QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss") + ".track"); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::critical(this, "Error while saving track", "Unable to open file for writing"); } else { std::stringstream stream; stream << lastTrack; std::string data = stream.str(); if (file.write(data.data(), data.length()) != data.length()) { QMessageBox::critical(this, "Error while saving track", "Unable to write to opened file"); } } } Model previousModel = commitedModel; PFigure modifiedFigure = recognize(lastTrack, commitedModel); if (_gridStep > 0 && modifiedFigure) { GridAlignLayouter layouter(_gridStep); layouter.updateLayout(commitedModel, modifiedFigure); commitedModel.recalculate(); } visibleTracks.push_back(lastTrack); auto iterator = --visibleTracks.end(); QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, [this, iterator, timer]() { visibleTracks.erase(iterator); delete timer; update(); }); timer->setInterval(1500); timer->setSingleShot(true); timer->start(); lastTrack = Track(); if (modifiedFigure) { previousModels.push_back(previousModel); redoModels.clear(); emit canUndoChanged(); emit canRedoChanged(); } update(); } void Ui::ModelWidget::keyReleaseEvent(QKeyEvent *event) { event->ignore(); if (event->key() == Qt::Key_Escape && mouseAction == MouseAction::TrackActive) { event->accept(); lastTrack = Track(); mouseAction = MouseAction::None; update(); } if (event->key() == Qt::Key_Delete) { if (commitedModel.selectedFigure) { event->accept(); previousModels.push_back(commitedModel); redoModels.clear(); for (auto it = commitedModel.begin(); it != commitedModel.end(); it++) { if (*it == commitedModel.selectedFigure) { commitedModel.removeFigure(it); break; } } emit canUndoChanged(); emit canRedoChanged(); update(); } } } void Ui::ModelWidget::mouseDoubleClickEvent(QMouseEvent *event) { event->ignore(); auto &figure = commitedModel.selectedFigure; if (!figure) { return; } Point eventPos = scaler(event->pos()); bool hit = false; hit |= figure->isInsideOrOnBorder(eventPos); hit |= figure->getApproximateDistanceToBorder(eventPos) <= figureSelectGap(); if (!hit) { return; } event->accept(); bool ok; QString newLabel = QInputDialog::getMultiLineText(this, "Figure label", "Specify new figure label", QString::fromStdString(figure->label()), &ok); if (ok) { previousModels.push_back(commitedModel); redoModels.clear(); figure->setLabel(newLabel.toStdString()); emit canUndoChanged(); emit canRedoChanged(); update(); } } void Ui::ModelWidget::wheelEvent(QWheelEvent *event) { event->ignore(); if (event->modifiers().testFlag(Qt::ControlModifier)) { event->accept(); double scrolled = event->angleDelta().y() / 8; double factor = 1.0 + 0.2 * (scrolled / 15); // 20% per each 15 degrees (standard step) factor = std::max(factor, 0.1); scaler.scaleWithFixedPoint(scaler(event->pos()), factor); update(); } } bool Ui::ModelWidget::event(QEvent *event) { if (event->type() == QEvent::Gesture) { QGestureEvent *gevent = static_cast<QGestureEvent*>(event); QPinchGesture *gesture = static_cast<QPinchGesture*>(gevent->gesture(Qt::PinchGesture)); if (gesture) { gevent->accept(gesture); lastTrack = Track(); mouseAction = MouseAction::None; scaler.zeroPoint = scaler.zeroPoint + scaler(gesture->lastCenterPoint()) - scaler(gesture->centerPoint()); scaler.scaleWithFixedPoint(scaler(gesture->centerPoint()), gesture->scaleFactor()); emit scaleFactorChanged(); update(); return true; } } return QWidget::event(event); } <commit_msg>modelwidget: track is transparent now<commit_after>#include "model.h" #include "model_io.h" #include "modelwidget.h" #include "figurepainter.h" #include "recognition.h" #include "layouting.h" #include <QPainter> #include <QMouseEvent> #include <QInputDialog> #include <QMessageBox> #include <QWheelEvent> #include <QGesture> #include <QDebug> #include <QTimer> #include <iostream> Ui::ModelWidget::ModelWidget(QWidget *parent) : QWidget(parent), mouseAction(MouseAction::None), _gridStep(0), _showTrack(true), _showRecognitionResult(true), _storeTracks(false) { setFocusPolicy(Qt::FocusPolicy::StrongFocus); grabGesture(Qt::PinchGesture); } void drawTrack(QPainter &painter, Scaler &scaler, const Track &track) { QPen oldPen = painter.pen(); std::vector<double> speeds = calculateRelativeSpeeds(track); for (size_t i = 0; i + 1 < track.size(); i++) { double k = speeds[i] * 510; QColor color; if (k <= 255) color = QColor(255, k, 0, 127); else color = QColor(255 - (k - 255), 255, 0, 127); QPen pen = oldPen; pen.setColor(color); painter.setPen(pen); painter.drawLine(scaler(track[i]), scaler(track[i + 1])); } painter.setPen(oldPen); } int Ui::ModelWidget::gridStep() { return _gridStep; } void Ui::ModelWidget::setGridStep(int newGridStep) { if (newGridStep < 0) { throw std::runtime_error("Grid step should be >= 0"); } _gridStep = newGridStep; update(); } double Ui::ModelWidget::scaleFactor() { return scaler.scaleFactor; } void Ui::ModelWidget::setScaleFactor(double newScaleFactor) { if (!(newScaleFactor >= 0.01)) { // >= instead of < for NaNs throw std::runtime_error("Scale factor should be >= 0.01"); } scaler.scaleFactor = newScaleFactor; emit scaleFactorChanged(); update(); } bool Ui::ModelWidget::showTrack() { return _showTrack; } void Ui::ModelWidget::setShowTrack(bool newShowTrack) { _showTrack = newShowTrack; } bool Ui::ModelWidget::showRecognitionResult() { return _showRecognitionResult; } void Ui::ModelWidget::setShowRecognitionResult(bool newShowRecognitionResult) { _showRecognitionResult = newShowRecognitionResult; } bool Ui::ModelWidget::storeTracks() { return _storeTracks; } void Ui::ModelWidget::setStoreTracks(bool newStoreTracks) { _storeTracks = newStoreTracks; } void Ui::ModelWidget::setModel(Model model) { commitedModel = std::move(model); previousModels.clear(); redoModels.clear(); emit canUndoChanged(); emit canRedoChanged(); extraTracks = std::vector<Track>(); } Model &Ui::ModelWidget::getModel() { return commitedModel; } void Ui::ModelWidget::addModelExtraTrack(Track track) { extraTracks.push_back(std::move(track)); } bool Ui::ModelWidget::canUndo() { return !previousModels.empty(); } void Ui::ModelWidget::undo() { if (!canUndo()) { throw std::runtime_error("Cannot undo"); } redoModels.push_front(std::move(commitedModel)); commitedModel = std::move(previousModels.back()); previousModels.pop_back(); if (!canUndo()) { emit canUndoChanged(); } emit canRedoChanged(); update(); } bool Ui::ModelWidget::canRedo() { return !redoModels.empty(); } void Ui::ModelWidget::redo() { if (!canRedo()) { throw std::runtime_error("Cannot redo"); } previousModels.push_back(std::move(commitedModel)); commitedModel = std::move(redoModels.front()); redoModels.pop_front(); if (!canRedo()) { canRedoChanged(); } canUndoChanged(); update(); } double roundDownToMultiple(double x, double multiple) { return floor(x / multiple) * multiple; } void Ui::ModelWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.fillRect(QRect(QPoint(), size()), Qt::white); QFont font; font.setPointSizeF(10 * scaler.scaleFactor); painter.setFont(font); QPen pen(Qt::black); pen.setWidthF(scaler.scaleFactor); painter.setPen(pen); FigurePainter fpainter(painter, scaler); if (gridStep() > 0) { int step = gridStep(); // Calculating visible area Point p1 = scaler(QPointF(0, 0)); Point p2 = scaler(QPointF(width(), height())); if (p1.x > p2.x) { std::swap(p1.x, p2.x); } if (p1.y > p2.y) { std::swap(p1.y, p2.y); } // Finding starting point for the grid p1.x = roundDownToMultiple(p1.x, step); p1.y = roundDownToMultiple(p1.y, step); // Drawing QPen pen(QColor(192, 192, 192, 255)); pen.setStyle(Qt::DashLine); painter.setPen(pen); for (int x = p1.x; x <= p2.x; x += step) { painter.drawLine(scaler(Point(x, p1.y)), scaler(Point(x, p2.y))); } for (int y = p1.y; y <= p2.y; y += step) { painter.drawLine(scaler(Point(p1.x, y)), scaler(Point(p2.x, y))); } } Model copiedModel; Model &modelToDraw = (lastTrack.empty() || !showRecognitionResult()) ? commitedModel : (copiedModel = commitedModel); PFigure modified = showRecognitionResult() ? recognize(lastTrack, modelToDraw) : nullptr; for (PFigure fig : modelToDraw) { if (fig == modified) { pen.setColor(Qt::magenta); } else if (fig == modelToDraw.selectedFigure) { pen.setColor(Qt::blue); } else { pen.setColor(Qt::black); } painter.setPen(pen); fig->visit(fpainter); } pen.setColor(QColor(255, 0, 0, 16)); pen.setWidth(3 * scaler.scaleFactor); painter.setPen(pen); if (showTrack()) { drawTrack(painter, scaler, lastTrack); for (const Track &track : visibleTracks) { drawTrack(painter, scaler, track); } } for (const Track &track : extraTracks) { drawTrack(painter, scaler, track); } } void Ui::ModelWidget::mousePressEvent(QMouseEvent *event) { lastTrack = Track(); if (event->modifiers().testFlag(Qt::ShiftModifier) || event->buttons().testFlag(Qt::MiddleButton)) { mouseAction = MouseAction::ViewpointMove; viewpointMoveStart = event->pos(); viewpointMoveOldScaler = scaler; setCursor(Qt::ClosedHandCursor); } else { mouseAction = MouseAction::TrackActive; trackTimer.start(); lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed())); } update(); } void Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) { if (mouseAction == MouseAction::ViewpointMove) { scaler = viewpointMoveOldScaler; scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos()); update(); } else if (mouseAction == MouseAction::TrackActive) { lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed())); if (showTrack() || showRecognitionResult()) { update(); } } else { event->ignore(); } } void Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) { if (mouseAction == MouseAction::None) { event->ignore(); return; } if (mouseAction == MouseAction::ViewpointMove) { mouseAction = MouseAction::None; setCursor(Qt::ArrowCursor); scaler = viewpointMoveOldScaler; scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos()); update(); return; } assert(mouseAction == MouseAction::TrackActive); mouseAction = MouseAction::None; lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed())); if (storeTracks()) { QFile file(QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss") + ".track"); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::critical(this, "Error while saving track", "Unable to open file for writing"); } else { std::stringstream stream; stream << lastTrack; std::string data = stream.str(); if (file.write(data.data(), data.length()) != data.length()) { QMessageBox::critical(this, "Error while saving track", "Unable to write to opened file"); } } } Model previousModel = commitedModel; PFigure modifiedFigure = recognize(lastTrack, commitedModel); if (_gridStep > 0 && modifiedFigure) { GridAlignLayouter layouter(_gridStep); layouter.updateLayout(commitedModel, modifiedFigure); commitedModel.recalculate(); } visibleTracks.push_back(lastTrack); auto iterator = --visibleTracks.end(); QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, [this, iterator, timer]() { visibleTracks.erase(iterator); delete timer; update(); }); timer->setInterval(1500); timer->setSingleShot(true); timer->start(); lastTrack = Track(); if (modifiedFigure) { previousModels.push_back(previousModel); redoModels.clear(); emit canUndoChanged(); emit canRedoChanged(); } update(); } void Ui::ModelWidget::keyReleaseEvent(QKeyEvent *event) { event->ignore(); if (event->key() == Qt::Key_Escape && mouseAction == MouseAction::TrackActive) { event->accept(); lastTrack = Track(); mouseAction = MouseAction::None; update(); } if (event->key() == Qt::Key_Delete) { if (commitedModel.selectedFigure) { event->accept(); previousModels.push_back(commitedModel); redoModels.clear(); for (auto it = commitedModel.begin(); it != commitedModel.end(); it++) { if (*it == commitedModel.selectedFigure) { commitedModel.removeFigure(it); break; } } emit canUndoChanged(); emit canRedoChanged(); update(); } } } void Ui::ModelWidget::mouseDoubleClickEvent(QMouseEvent *event) { event->ignore(); auto &figure = commitedModel.selectedFigure; if (!figure) { return; } Point eventPos = scaler(event->pos()); bool hit = false; hit |= figure->isInsideOrOnBorder(eventPos); hit |= figure->getApproximateDistanceToBorder(eventPos) <= figureSelectGap(); if (!hit) { return; } event->accept(); bool ok; QString newLabel = QInputDialog::getMultiLineText(this, "Figure label", "Specify new figure label", QString::fromStdString(figure->label()), &ok); if (ok) { previousModels.push_back(commitedModel); redoModels.clear(); figure->setLabel(newLabel.toStdString()); emit canUndoChanged(); emit canRedoChanged(); update(); } } void Ui::ModelWidget::wheelEvent(QWheelEvent *event) { event->ignore(); if (event->modifiers().testFlag(Qt::ControlModifier)) { event->accept(); double scrolled = event->angleDelta().y() / 8; double factor = 1.0 + 0.2 * (scrolled / 15); // 20% per each 15 degrees (standard step) factor = std::max(factor, 0.1); scaler.scaleWithFixedPoint(scaler(event->pos()), factor); update(); } } bool Ui::ModelWidget::event(QEvent *event) { if (event->type() == QEvent::Gesture) { QGestureEvent *gevent = static_cast<QGestureEvent*>(event); QPinchGesture *gesture = static_cast<QPinchGesture*>(gevent->gesture(Qt::PinchGesture)); if (gesture) { gevent->accept(gesture); lastTrack = Track(); mouseAction = MouseAction::None; scaler.zeroPoint = scaler.zeroPoint + scaler(gesture->lastCenterPoint()) - scaler(gesture->centerPoint()); scaler.scaleWithFixedPoint(scaler(gesture->centerPoint()), gesture->scaleFactor()); emit scaleFactorChanged(); update(); return true; } } return QWidget::event(event); } <|endoftext|>
<commit_before>/******************************************************************************* * This file is part of "Patrick's Programming Library", Version 7 (PPL7). * Web: http://www.pfp.de/ppl/ * ******************************************************************************* * Copyright (c) 2018, Patrick Fedick <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AND 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 <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <locale.h> #include <ppl6.h> #include <ppl7.h> #include "ppl7-ppl6compat.h" #include <gtest/gtest.h> #include "ppl7-tests.h" namespace { // The fixture for testing class Foo. class PPL6CompatAssocArrayTest : public ::testing::Test { protected: PPL6CompatAssocArrayTest() { if (setlocale(LC_CTYPE,DEFAULT_LOCALE)==NULL) { printf ("setlocale fehlgeschlagen\n"); throw std::exception(); } } virtual ~PPL6CompatAssocArrayTest() { } }; TEST_F(PPL6CompatAssocArrayTest, 6to7ExportImport) { ppl6::CBinary bin("Ein Binary-Object mit reinem ASCII-Text"); ppl6::CWString w6(L"This as a wide string äöü"); ppl6::CAssocArray a6; a6.Set("key1","Dieser Wert geht über\nmehrere Zeilen"); a6.Set("key2","value6"); a6.Set("ebene1/ebene2/key1","value42"); a6.Set("time",ppl6::CDateTime("03.12.2018 08:39:00.123456")); a6.Set("bytearray",bin); ppl6::CArray ar6("red green blue yellow black white"," "); a6.Set("array1",ar6); a6.Set("widestring",w6); int requiredsize=0; ASSERT_EQ(1,a6.ExportBinary(NULL,0,&requiredsize)); ASSERT_EQ((int)337,requiredsize); void *buffer=malloc(requiredsize+1); ASSERT_TRUE(buffer!=NULL); int realsize=0; ASSERT_EQ(1,a6.ExportBinary(buffer,requiredsize,&realsize)); ppl7::AssocArray a7; ASSERT_NO_THROW({ try { a7.importBinary(buffer,realsize); } catch (const ppl7::Exception &exp) { exp.print(); throw; } }); free(buffer); EXPECT_EQ(ppl7::String("Dieser Wert geht über\nmehrere Zeilen"),a7.get("key1").toString()); EXPECT_EQ(ppl7::WideString(L"This as a wide string äöü"),a7.get("widestring").toWideString()); EXPECT_EQ(ppl7::DateTime("03.12.2018 08:39:00.123456"),a7.get("time").toDateTime()); EXPECT_EQ(ppl7::String("value42"),a7.get("ebene1/ebene2/key1").toString()); EXPECT_EQ(ppl7::ByteArray(ppl7::String("Ein Binary-Object mit reinem ASCII-Text")),a7.get("bytearray").toByteArray()); //a7.list(); } } <commit_msg>compat tests<commit_after>/******************************************************************************* * This file is part of "Patrick's Programming Library", Version 7 (PPL7). * Web: http://www.pfp.de/ppl/ * ******************************************************************************* * Copyright (c) 2018, Patrick Fedick <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AND 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 <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <locale.h> #include <ppl6.h> #include <ppl7.h> #include "ppl7-ppl6compat.h" #include <gtest/gtest.h> #include "ppl7-tests.h" namespace { // The fixture for testing class Foo. class PPL6CompatAssocArrayTest : public ::testing::Test { protected: PPL6CompatAssocArrayTest() { if (setlocale(LC_CTYPE,DEFAULT_LOCALE)==NULL) { printf ("setlocale fehlgeschlagen\n"); throw std::exception(); } } virtual ~PPL6CompatAssocArrayTest() { } }; TEST_F(PPL6CompatAssocArrayTest, 6to7ExportImport) { ppl6::CBinary bin("Ein Binary-Object mit reinem ASCII-Text"); ppl6::CWString w6(L"This as a wide string äöü"); ppl6::CAssocArray a6; a6.Set("key1","Dieser Wert geht über\nmehrere Zeilen"); a6.Set("key2","value6"); a6.Set("ebene1/ebene2/key1","value42"); a6.Set("time",ppl6::CDateTime("03.12.2018 08:39:00.123456")); a6.Set("bytearray",bin); ppl6::CArray ar6("red green blue yellow black white"," "); a6.Set("array1",ar6); a6.Set("widestring",w6); int requiredsize=0; ASSERT_EQ(1,a6.ExportBinary(NULL,0,&requiredsize)); ASSERT_EQ((int)337,requiredsize); void *buffer=malloc(requiredsize+1); ASSERT_TRUE(buffer!=NULL); int realsize=0; ASSERT_EQ(1,a6.ExportBinary(buffer,requiredsize,&realsize)); //ppl7::HexDump(buffer,realsize); ppl7::AssocArray a7; ASSERT_NO_THROW({ try { a7.importBinary(buffer,realsize); } catch (const ppl7::Exception &exp) { exp.print(); throw; } }); free(buffer); EXPECT_EQ(ppl7::String("Dieser Wert geht über\nmehrere Zeilen"),a7.get("key1").toString()); EXPECT_EQ(ppl7::WideString(L"This as a wide string äöü"),a7.get("widestring").toWideString()); EXPECT_EQ(ppl7::DateTime("03.12.2018 08:39:00.123456"),a7.get("time").toDateTime()); EXPECT_EQ(ppl7::String("value42"),a7.get("ebene1/ebene2/key1").toString()); EXPECT_EQ(ppl7::ByteArray(ppl7::String("Ein Binary-Object mit reinem ASCII-Text")),a7.get("bytearray").toByteArray()); //a7.list(); } TEST_F(PPL6CompatAssocArrayTest, 7to6ExportImport) { ppl7::ByteArray bin(ppl7::String("Ein Binary-Object mit reinem ASCII-Text")); ppl7::WideString w7(L"This as a wide string äöü"); ppl7::AssocArray a7; a7.set("key1","Dieser Wert geht über\nmehrere Zeilen"); a7.set("key2","value6"); a7.set("ebene1/ebene2/key1","value42"); a7.set("time",ppl7::DateTime("03.12.2018 08:39:00.123456")); a7.set("bytearray",bin); //ppl7::Array ar7("red green blue yellow black white"," "); //a7.set("array1",ar7); a7.set("widestring",w7); //a7.list(); size_t requiredsize=0; a7.exportBinary(NULL,0,&requiredsize); EXPECT_EQ((int)337,requiredsize); void *buffer=malloc(requiredsize+1); ASSERT_TRUE(buffer!=NULL); size_t realsize=0; a7.exportBinary(buffer,requiredsize,&realsize); //ppl7::HexDump(buffer,realsize); ppl6::CAssocArray a6; EXPECT_EQ(1,a6.ImportBinary(buffer,realsize)); ppl6::PrintError(); free(buffer); a6.List(); #ifdef TODO EXPECT_EQ(ppl6::CString("Dieser Wert geht über\nmehrere Zeilen"),a6.get("key1").toString()); EXPECT_EQ(ppl6::CWString(L"This as a wide string äöü"),a6.get("widestring").toWideString()); EXPECT_EQ(ppl6::CDateTime("03.12.2018 08:39:00.123456"),a6.get("time").toDateTime()); EXPECT_EQ(ppl6::CString("value42"),a6.get("ebene1/ebene2/key1").toString()); EXPECT_EQ(ppl6::ByteArray(ppl7::String("Ein Binary-Object mit reinem ASCII-Text")),a6.get("bytearray").toByteArray()); //a7.list(); #endif } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "tests/unittests/test_suite.h" #include "tests/cefclient/client_switches.h" #include "base/command_line.h" #include "base/logging.h" #include "base/test/test_suite.h" #if defined(OS_MACOSX) #include "base/debug/stack_trace.h" #include "base/files/file_path.h" #include "base/i18n/icu_util.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/test/test_timeouts.h" #endif CommandLine* CefTestSuite::commandline_ = NULL; CefTestSuite::CefTestSuite(int argc, char** argv) : TestSuite(argc, argv) { } // static void CefTestSuite::InitCommandLine(int argc, const char* const* argv) { if (commandline_) { // If this is intentional, Reset() must be called first. If we are using // the shared build mode, we have to share a single object across multiple // shared libraries. return; } commandline_ = new CommandLine(CommandLine::NO_PROGRAM); #if defined(OS_WIN) commandline_->ParseFromString(::GetCommandLineW()); #elif defined(OS_POSIX) commandline_->InitFromArgv(argc, argv); #endif } // static void CefTestSuite::GetSettings(CefSettings& settings) { #if defined(OS_WIN) settings.multi_threaded_message_loop = commandline_->HasSwitch(cefclient::kMultiThreadedMessageLoop); #endif CefString(&settings.cache_path) = commandline_->GetSwitchValueASCII(cefclient::kCachePath); // Always expose the V8 gc() function to give tests finer-grained control over // memory management. std::string javascript_flags = "--expose-gc"; // Value of kJavascriptFlags switch. std::string other_javascript_flags = commandline_->GetSwitchValueASCII("js-flags"); if (!other_javascript_flags.empty()) javascript_flags += " " + other_javascript_flags; CefString(&settings.javascript_flags) = javascript_flags; // Necessary for V8Test.OnUncaughtException tests. settings.uncaught_exception_stack_size = 10; settings.remote_debugging_port = 12345; } // static bool CefTestSuite::GetCachePath(std::string& path) { DCHECK(commandline_); if (commandline_->HasSwitch(cefclient::kCachePath)) { // Set the cache_path value. path = commandline_->GetSwitchValueASCII(cefclient::kCachePath); return true; } return false; } #if defined(OS_MACOSX) void CefTestSuite::Initialize() { // The below code is copied from base/test/test_suite.cc to avoid calling // RegisterMockCrApp() on Mac. base::FilePath exe; PathService::Get(base::FILE_EXE, &exe); // Initialize logging. logging::LoggingSettings log_settings; log_settings.log_file = exe.ReplaceExtension(FILE_PATH_LITERAL("log")).value().c_str(); log_settings.logging_dest = logging::LOG_TO_ALL; log_settings.lock_log = logging::LOCK_LOG_FILE; log_settings.delete_old = logging::DELETE_OLD_LOG_FILE; log_settings.dcheck_state = logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS; logging::InitLogging(log_settings); // We want process and thread IDs because we may have multiple processes. // Note: temporarily enabled timestamps in an effort to catch bug 6361. logging::SetLogItems(true, true, true, true); CHECK(base::debug::EnableInProcessStackDumping()); // In some cases, we do not want to see standard error dialogs. if (!base::debug::BeingDebugged() && !CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) { SuppressErrorDialogs(); base::debug::SetSuppressDebugUI(true); logging::SetLogAssertHandler(UnitTestAssertHandler); } icu_util::Initialize(); CatchMaybeTests(); ResetCommandLine(); TestTimeouts::Initialize(); } #endif // defined(OS_MACOSX) <commit_msg>Mac: Fix compile error<commit_after>// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "tests/unittests/test_suite.h" #include "tests/cefclient/client_switches.h" #include "base/command_line.h" #include "base/logging.h" #include "base/test/test_suite.h" #if defined(OS_MACOSX) #include "base/debug/stack_trace.h" #include "base/files/file_path.h" #include "base/i18n/icu_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #endif CommandLine* CefTestSuite::commandline_ = NULL; CefTestSuite::CefTestSuite(int argc, char** argv) : TestSuite(argc, argv) { } // static void CefTestSuite::InitCommandLine(int argc, const char* const* argv) { if (commandline_) { // If this is intentional, Reset() must be called first. If we are using // the shared build mode, we have to share a single object across multiple // shared libraries. return; } commandline_ = new CommandLine(CommandLine::NO_PROGRAM); #if defined(OS_WIN) commandline_->ParseFromString(::GetCommandLineW()); #elif defined(OS_POSIX) commandline_->InitFromArgv(argc, argv); #endif } // static void CefTestSuite::GetSettings(CefSettings& settings) { #if defined(OS_WIN) settings.multi_threaded_message_loop = commandline_->HasSwitch(cefclient::kMultiThreadedMessageLoop); #endif CefString(&settings.cache_path) = commandline_->GetSwitchValueASCII(cefclient::kCachePath); // Always expose the V8 gc() function to give tests finer-grained control over // memory management. std::string javascript_flags = "--expose-gc"; // Value of kJavascriptFlags switch. std::string other_javascript_flags = commandline_->GetSwitchValueASCII("js-flags"); if (!other_javascript_flags.empty()) javascript_flags += " " + other_javascript_flags; CefString(&settings.javascript_flags) = javascript_flags; // Necessary for V8Test.OnUncaughtException tests. settings.uncaught_exception_stack_size = 10; settings.remote_debugging_port = 12345; } // static bool CefTestSuite::GetCachePath(std::string& path) { DCHECK(commandline_); if (commandline_->HasSwitch(cefclient::kCachePath)) { // Set the cache_path value. path = commandline_->GetSwitchValueASCII(cefclient::kCachePath); return true; } return false; } #if defined(OS_MACOSX) void CefTestSuite::Initialize() { // The below code is copied from base/test/test_suite.cc to avoid calling // RegisterMockCrApp() on Mac. base::FilePath exe; PathService::Get(base::FILE_EXE, &exe); // Initialize logging. logging::LoggingSettings log_settings; log_settings.log_file = exe.ReplaceExtension(FILE_PATH_LITERAL("log")).value().c_str(); log_settings.logging_dest = logging::LOG_TO_ALL; log_settings.lock_log = logging::LOCK_LOG_FILE; log_settings.delete_old = logging::DELETE_OLD_LOG_FILE; log_settings.dcheck_state = logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS; logging::InitLogging(log_settings); // We want process and thread IDs because we may have multiple processes. // Note: temporarily enabled timestamps in an effort to catch bug 6361. logging::SetLogItems(true, true, true, true); CHECK(base::debug::EnableInProcessStackDumping()); // In some cases, we do not want to see standard error dialogs. if (!base::debug::BeingDebugged() && !CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) { SuppressErrorDialogs(); base::debug::SetSuppressDebugUI(true); logging::SetLogAssertHandler(UnitTestAssertHandler); } icu_util::Initialize(); CatchMaybeTests(); ResetCommandLine(); TestTimeouts::Initialize(); } #endif // defined(OS_MACOSX) <|endoftext|>
<commit_before>#include <glm/setup.hpp> #define GLM_SWIZZLE GLM_SWIZZLE_XYZW #include <glm/glm.hpp> #include <glm/gtc/type_precision.hpp> #include <gli/gli.hpp> #include <gli/gtx/loader_tga.hpp> #include <gli/gtx/loader_dds.hpp> #include "bug.hpp" #include "core.hpp" #include <vector> //#include <boost/format.hpp> bool test_image_wip() { //gli::wip::image<glm::u8vec3, gli::wip::plain> Image; //gli::wip::image<glm::u8vec3, gli::wip::plain>::mipmap Mipmap = Image[0]; //glm::vec2 Texcoord(0); //Image[0](Texcoord); //gli::wip::plain<glm::u8vec3> Surface; //gli::wip::fetch(Surface); //gli::wip::fetch(Image); return true; } bool test_image_export() { gli::image Image = gli::import_as("../test.tga"); gli::image ImageMipmaped = gli::generateMipmaps(Image, 0); gli::export_as(ImageMipmaped, 0, "../test0.tga"); gli::export_as(ImageMipmaped, 1, "../test1.tga"); gli::export_as(ImageMipmaped, 2, "../test2.tga"); gli::export_as(ImageMipmaped, 3, "../test3.tga"); return true; } bool test_image_export_dds() { { gli::image Image = gli::importFile<gli::TGA>("../test_rgb8.tga"); assert(!Image.empty()); gli::exportFile<gli::TGA>(Image, "../test_tga2tgaEXT.tga"); } { gli::image Image = gli::importFile<gli::TGA>("../test_rgb8.tga"); assert(!Image.empty()); gli::exportFile<gli::DDS>(Image, "../test_tga2ddsEXT.dds"); } { gli::image Image = gli::importFile<gli::DDS>("../test_rgb8.dds"); assert(!Image.empty()); gli::exportFile<gli::DDS>(Image, "../test_dds2tgaEXT.tga"); } { gli::image Image = gli::importFile<gli::DDS>("../test_rgb8.dds"); assert(!Image.empty()); gli::exportFile<gli::DDS>(Image, "../test_dds2ddsEXT.dds"); } { gli::image Image = gli::importFile<gli::DDS>("../test_dxt1.dds"); assert(!Image.empty()); gli::exportFile<gli::DDS>(Image, "../test_dxt2dxtEXT.dds"); } //////////////////////// { gli::image Image = gli::import_as("../test_rgb8.tga"); assert(!Image.empty()); gli::export_as(Image, "../test_tga2tga.tga"); } { gli::image Image = gli::import_as("../test_rgb8.tga"); assert(!Image.empty()); gli::export_as(Image, "../test_tga2dds.dds"); } { gli::image Image = gli::import_as("../test_rgb8.dds"); assert(!Image.empty()); gli::export_as(Image, "../test_dds2tga.tga"); } { gli::image Image = gli::import_as("../test_rgb8.dds"); assert(!Image.empty()); gli::export_as(Image, "../test_dds2dds.dds"); } { gli::image Image = gli::import_as("../test_dxt1.dds"); assert(!Image.empty()); gli::export_as(Image, "../test_dxt2dxt.dds"); } return true; } bool test_image_fetch() { gli::image Image = gli::import_as("../test.tga"); if(!Image.empty()) { gli::image::dimensions_type Size = Image[0].dimensions(); glm::u8vec3 TexelA = gli::textureLod<glm::u8vec3>(Image, glm::vec2(0.0f), 0); glm::u8vec3 TexelB = gli::textureLod<glm::u8vec3>(Image, glm::vec2(0.5f), 0); glm::u8vec3 TexelC = gli::texelFetch<glm::u8vec3>(Image, glm::ivec2(7, 7), 0); glm::u8vec3 TexelD = gli::texelFetch<glm::u8vec3>(Image, glm::ivec2(7, 0), 0); glm::u8vec3 TexelE = gli::texelFetch<glm::u8vec3>(Image, glm::ivec2(0, 7), 0); } return true; } bool test_image_gradient() { { gli::image Image = gli::radial(glm::uvec2(256), glm::vec2(0.25f), 128.0f, glm::vec2(0.5f)); gli::export_as(Image, "../gradient_radial.tga"); } { gli::image Image = gli::linear(glm::uvec2(256), glm::vec2(0.25f), glm::vec2(0.75f)); gli::export_as(Image, "../gradient_linear.tga"); } return true; } int main() { glm::vec4 v1(1, 2, 3, 4); glm::vec4 v2; glm::vec4 v3; glm::vec4 v4; v2.wyxz = v1.zyxw; v3 = v1.xzyw; v4.xzyw = v1; test_image_wip(); test_image_fetch(); test_image_gradient(); test_image_export_dds(); //test_image_export(); //// Set image //gli::wip::image<glm::u8vec3> Texture = gli::wip::import_as(TEXTURE_DIFFUSE); //for(gli::wip::image<glm::u8vec3>::level_type Level = 0; Level < Texture.levels(); ++Level) //{ // glTexImage2D( // GL_TEXTURE_2D, // GLint(Level), // GL_RGB, // GLsizei(Image[Level]->size().x), // GLsizei(Image[Level]->size().y), // 0, // GL_BGR, // GL_UNSIGNED_BYTE, // Image[Level]->data()); //} return 0; } <commit_msg>Fixed test data<commit_after>#include <glm/setup.hpp> #define GLM_SWIZZLE GLM_SWIZZLE_XYZW #include <glm/glm.hpp> #include <glm/gtc/type_precision.hpp> #include <gli/gli.hpp> #include <gli/gtx/loader_tga.hpp> #include <gli/gtx/loader_dds.hpp> #include "bug.hpp" #include "core.hpp" #include <vector> //#include <boost/format.hpp> bool test_image_wip() { //gli::wip::image<glm::u8vec3, gli::wip::plain> Image; //gli::wip::image<glm::u8vec3, gli::wip::plain>::mipmap Mipmap = Image[0]; //glm::vec2 Texcoord(0); //Image[0](Texcoord); //gli::wip::plain<glm::u8vec3> Surface; //gli::wip::fetch(Surface); //gli::wip::fetch(Image); return true; } bool test_image_export() { gli::image Image = gli::import_as("../test_rgb8.tga"); gli::image ImageMipmaped = gli::generateMipmaps(Image, 0); gli::export_as(ImageMipmaped, 0, "../test0.tga"); gli::export_as(ImageMipmaped, 1, "../test1.tga"); gli::export_as(ImageMipmaped, 2, "../test2.tga"); gli::export_as(ImageMipmaped, 3, "../test3.tga"); return true; } bool test_image_export_dds() { { gli::image Image = gli::importFile<gli::TGA>("../test_rgb8.tga"); assert(!Image.empty()); gli::exportFile<gli::TGA>(Image, "../test_tga2tgaEXT.tga"); } { gli::image Image = gli::importFile<gli::TGA>("../test_rgb8.tga"); assert(!Image.empty()); gli::exportFile<gli::DDS>(Image, "../test_tga2ddsEXT.dds"); } { gli::image Image = gli::importFile<gli::DDS>("../test_rgb8.dds"); assert(!Image.empty()); gli::exportFile<gli::DDS>(Image, "../test_dds2tgaEXT.tga"); } { gli::image Image = gli::importFile<gli::DDS>("../test_rgb8.dds"); assert(!Image.empty()); gli::exportFile<gli::DDS>(Image, "../test_dds2ddsEXT.dds"); } { gli::image Image = gli::importFile<gli::DDS>("../test_dxt1.dds"); assert(!Image.empty()); gli::exportFile<gli::DDS>(Image, "../test_dxt2dxtEXT.dds"); } //////////////////////// { gli::image Image = gli::import_as("../test_rgb8.tga"); assert(!Image.empty()); gli::export_as(Image, "../test_tga2tga.tga"); } { gli::image Image = gli::import_as("../test_rgb8.tga"); assert(!Image.empty()); gli::export_as(Image, "../test_tga2dds.dds"); } { gli::image Image = gli::import_as("../test_rgb8.dds"); assert(!Image.empty()); gli::export_as(Image, "../test_dds2tga.tga"); } { gli::image Image = gli::import_as("../test_rgb8.dds"); assert(!Image.empty()); gli::export_as(Image, "../test_dds2dds.dds"); } { gli::image Image = gli::import_as("../test_dxt1.dds"); assert(!Image.empty()); gli::export_as(Image, "../test_dxt2dxt.dds"); } return true; } bool test_image_fetch() { gli::image Image = gli::import_as("../test.tga"); if(!Image.empty()) { gli::image::dimensions_type Size = Image[0].dimensions(); glm::u8vec3 TexelA = gli::textureLod<glm::u8vec3>(Image, glm::vec2(0.0f), 0); glm::u8vec3 TexelB = gli::textureLod<glm::u8vec3>(Image, glm::vec2(0.5f), 0); glm::u8vec3 TexelC = gli::texelFetch<glm::u8vec3>(Image, glm::ivec2(7, 7), 0); glm::u8vec3 TexelD = gli::texelFetch<glm::u8vec3>(Image, glm::ivec2(7, 0), 0); glm::u8vec3 TexelE = gli::texelFetch<glm::u8vec3>(Image, glm::ivec2(0, 7), 0); } return true; } bool test_image_gradient() { { gli::image Image = gli::radial(glm::uvec2(256), glm::vec2(0.25f), 128.0f, glm::vec2(0.5f)); gli::export_as(Image, "../gradient_radial.tga"); } { gli::image Image = gli::linear(glm::uvec2(256), glm::vec2(0.25f), glm::vec2(0.75f)); gli::export_as(Image, "../gradient_linear.tga"); } return true; } int main() { glm::vec4 v1(1, 2, 3, 4); glm::vec4 v2; glm::vec4 v3; glm::vec4 v4; v2.wyxz = v1.zyxw; v3 = v1.xzyw; v4.xzyw = v1; test_image_wip(); test_image_fetch(); test_image_gradient(); test_image_export_dds(); //test_image_export(); //// Set image //gli::wip::image<glm::u8vec3> Texture = gli::wip::import_as(TEXTURE_DIFFUSE); //for(gli::wip::image<glm::u8vec3>::level_type Level = 0; Level < Texture.levels(); ++Level) //{ // glTexImage2D( // GL_TEXTURE_2D, // GLint(Level), // GL_RGB, // GLsizei(Image[Level]->size().x), // GLsizei(Image[Level]->size().y), // 0, // GL_BGR, // GL_UNSIGNED_BYTE, // Image[Level]->data()); //} return 0; } <|endoftext|>
<commit_before>//===-- dfsan.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 part of DataFlowSanitizer. // // DataFlowSanitizer runtime. This file defines the public interface to // DataFlowSanitizer as well as the definition of certain runtime functions // called automatically by the compiler (specifically the instrumentation pass // in llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp). // // The public interface is defined in include/sanitizer/dfsan_interface.h whose // functions are prefixed dfsan_ while the compiler interface functions are // prefixed __dfsan_. //===----------------------------------------------------------------------===// #include "sanitizer/dfsan_interface.h" #include "sanitizer_common/sanitizer_atomic.h" #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_libc.h" #include "dfsan/dfsan.h" using namespace __dfsan; typedef atomic_uint16_t atomic_dfsan_label; static const dfsan_label kInitializingLabel = -1; static const uptr kNumLabels = 1 << (sizeof(dfsan_label) * 8); static atomic_dfsan_label __dfsan_last_label; static dfsan_label_info __dfsan_label_info[kNumLabels]; SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_retval_tls; SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_arg_tls[64]; // On Linux/x86_64, memory is laid out as follows: // // +--------------------+ 0x800000000000 (top of memory) // | application memory | // +--------------------+ 0x700000008000 (kAppAddr) // | | // | unused | // | | // +--------------------+ 0x200200000000 (kUnusedAddr) // | union table | // +--------------------+ 0x200000000000 (kUnionTableAddr) // | shadow memory | // +--------------------+ 0x000000010000 (kShadowAddr) // | reserved by kernel | // +--------------------+ 0x000000000000 // // To derive a shadow memory address from an application memory address, // bits 44-46 are cleared to bring the address into the range // [0x000000008000,0x100000000000). Then the address is shifted left by 1 to // account for the double byte representation of shadow labels and move the // address into the shadow memory range. See the function shadow_for below. typedef atomic_dfsan_label dfsan_union_table_t[kNumLabels][kNumLabels]; static const uptr kShadowAddr = 0x10000; static const uptr kUnionTableAddr = 0x200000000000; static const uptr kUnusedAddr = kUnionTableAddr + sizeof(dfsan_union_table_t); static const uptr kAppAddr = 0x700000008000; static atomic_dfsan_label *union_table(dfsan_label l1, dfsan_label l2) { return &(*(dfsan_union_table_t *) kUnionTableAddr)[l1][l2]; } // Resolves the union of two unequal labels. Nonequality is a precondition for // this function (the instrumentation pass inlines the equality test). extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label __dfsan_union(dfsan_label l1, dfsan_label l2) { DCHECK_NE(l1, l2); if (l1 == 0) return l2; if (l2 == 0) return l1; if (l1 > l2) Swap(l1, l2); atomic_dfsan_label *table_ent = union_table(l1, l2); // We need to deal with the case where two threads concurrently request // a union of the same pair of labels. If the table entry is uninitialized, // (i.e. 0) use a compare-exchange to set the entry to kInitializingLabel // (i.e. -1) to mark that we are initializing it. dfsan_label label = 0; if (atomic_compare_exchange_strong(table_ent, &label, kInitializingLabel, memory_order_acquire)) { // Check whether l2 subsumes l1. We don't need to check whether l1 // subsumes l2 because we are guaranteed here that l1 < l2, and (at least // in the cases we are interested in) a label may only subsume labels // created earlier (i.e. with a lower numerical value). if (__dfsan_label_info[l2].l1 == l1 || __dfsan_label_info[l2].l2 == l1) { label = l2; } else { label = atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1; CHECK_NE(label, kInitializingLabel); __dfsan_label_info[label].l1 = l1; __dfsan_label_info[label].l2 = l2; } atomic_store(table_ent, label, memory_order_release); } else if (label == kInitializingLabel) { // Another thread is initializing the entry. Wait until it is finished. do { internal_sched_yield(); label = atomic_load(table_ent, memory_order_acquire); } while (label == kInitializingLabel); } return label; } extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label __dfsan_union_load(const dfsan_label *ls, size_t n) { dfsan_label label = ls[0]; for (size_t i = 1; i != n; ++i) { dfsan_label next_label = ls[i]; if (label != next_label) label = __dfsan_union(label, next_label); } return label; } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_unimplemented(char *fname) { Report("WARNING: DataFlowSanitizer: call to uninstrumented function %s\n", fname); } // Like __dfsan_union, but for use from the client or custom functions. Hence // the equality comparison is done here before calling __dfsan_union. SANITIZER_INTERFACE_ATTRIBUTE dfsan_label dfsan_union(dfsan_label l1, dfsan_label l2) { if (l1 == l2) return l1; return __dfsan_union(l1, l2); } SANITIZER_INTERFACE_ATTRIBUTE dfsan_label dfsan_create_label(const char *desc, void *userdata) { dfsan_label label = atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1; CHECK_NE(label, kInitializingLabel); __dfsan_label_info[label].l1 = __dfsan_label_info[label].l2 = 0; __dfsan_label_info[label].desc = desc; __dfsan_label_info[label].userdata = userdata; return label; } SANITIZER_INTERFACE_ATTRIBUTE void dfsan_set_label(dfsan_label label, void *addr, size_t size) { for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp) *labelp = label; } SANITIZER_INTERFACE_ATTRIBUTE void dfsan_add_label(dfsan_label label, void *addr, size_t size) { for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp) if (*labelp != label) *labelp = __dfsan_union(*labelp, label); } // Unlike the other dfsan interface functions the behavior of this function // depends on the label of one of its arguments. Hence it is implemented as a // custom function. extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label __dfsw_dfsan_get_label(long data, dfsan_label data_label, dfsan_label *ret_label) { *ret_label = 0; return data_label; } SANITIZER_INTERFACE_ATTRIBUTE dfsan_label dfsan_read_label(const void *addr, size_t size) { if (size == 0) return 0; return __dfsan_union_load(shadow_for(addr), size); } SANITIZER_INTERFACE_ATTRIBUTE const struct dfsan_label_info *dfsan_get_label_info(dfsan_label label) { return &__dfsan_label_info[label]; } int dfsan_has_label(dfsan_label label, dfsan_label elem) { if (label == elem) return true; const dfsan_label_info *info = dfsan_get_label_info(label); if (info->l1 != 0) { return dfsan_has_label(info->l1, elem) || dfsan_has_label(info->l2, elem); } else { return false; } } dfsan_label dfsan_has_label_with_desc(dfsan_label label, const char *desc) { const dfsan_label_info *info = dfsan_get_label_info(label); if (info->l1 != 0) { return dfsan_has_label_with_desc(info->l1, desc) || dfsan_has_label_with_desc(info->l2, desc); } else { return internal_strcmp(desc, info->desc) == 0; } } #ifdef DFSAN_NOLIBC extern "C" void dfsan_init() { #else static void dfsan_init(int argc, char **argv, char **envp) { #endif MmapFixedNoReserve(kShadowAddr, kUnusedAddr - kShadowAddr); // Protect the region of memory we don't use, to preserve the one-to-one // mapping from application to shadow memory. But if ASLR is disabled, Linux // will load our executable in the middle of our unused region. This mostly // works so long as the program doesn't use too much memory. We support this // case by disabling memory protection when ASLR is disabled. uptr init_addr = (uptr)&dfsan_init; if (!(init_addr >= kUnusedAddr && init_addr < kAppAddr)) Mprotect(kUnusedAddr, kAppAddr - kUnusedAddr); } #ifndef DFSAN_NOLIBC __attribute__((section(".preinit_array"), used)) static void (*dfsan_init_ptr)(int, char **, char **) = dfsan_init; #endif <commit_msg>[dfsan] New __dfsan_set_label runtime function.<commit_after>//===-- dfsan.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 part of DataFlowSanitizer. // // DataFlowSanitizer runtime. This file defines the public interface to // DataFlowSanitizer as well as the definition of certain runtime functions // called automatically by the compiler (specifically the instrumentation pass // in llvm/lib/Transforms/Instrumentation/DataFlowSanitizer.cpp). // // The public interface is defined in include/sanitizer/dfsan_interface.h whose // functions are prefixed dfsan_ while the compiler interface functions are // prefixed __dfsan_. //===----------------------------------------------------------------------===// #include "sanitizer/dfsan_interface.h" #include "sanitizer_common/sanitizer_atomic.h" #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_libc.h" #include "dfsan/dfsan.h" using namespace __dfsan; typedef atomic_uint16_t atomic_dfsan_label; static const dfsan_label kInitializingLabel = -1; static const uptr kNumLabels = 1 << (sizeof(dfsan_label) * 8); static atomic_dfsan_label __dfsan_last_label; static dfsan_label_info __dfsan_label_info[kNumLabels]; SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_retval_tls; SANITIZER_INTERFACE_ATTRIBUTE THREADLOCAL dfsan_label __dfsan_arg_tls[64]; // On Linux/x86_64, memory is laid out as follows: // // +--------------------+ 0x800000000000 (top of memory) // | application memory | // +--------------------+ 0x700000008000 (kAppAddr) // | | // | unused | // | | // +--------------------+ 0x200200000000 (kUnusedAddr) // | union table | // +--------------------+ 0x200000000000 (kUnionTableAddr) // | shadow memory | // +--------------------+ 0x000000010000 (kShadowAddr) // | reserved by kernel | // +--------------------+ 0x000000000000 // // To derive a shadow memory address from an application memory address, // bits 44-46 are cleared to bring the address into the range // [0x000000008000,0x100000000000). Then the address is shifted left by 1 to // account for the double byte representation of shadow labels and move the // address into the shadow memory range. See the function shadow_for below. typedef atomic_dfsan_label dfsan_union_table_t[kNumLabels][kNumLabels]; static const uptr kShadowAddr = 0x10000; static const uptr kUnionTableAddr = 0x200000000000; static const uptr kUnusedAddr = kUnionTableAddr + sizeof(dfsan_union_table_t); static const uptr kAppAddr = 0x700000008000; static atomic_dfsan_label *union_table(dfsan_label l1, dfsan_label l2) { return &(*(dfsan_union_table_t *) kUnionTableAddr)[l1][l2]; } // Resolves the union of two unequal labels. Nonequality is a precondition for // this function (the instrumentation pass inlines the equality test). extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label __dfsan_union(dfsan_label l1, dfsan_label l2) { DCHECK_NE(l1, l2); if (l1 == 0) return l2; if (l2 == 0) return l1; if (l1 > l2) Swap(l1, l2); atomic_dfsan_label *table_ent = union_table(l1, l2); // We need to deal with the case where two threads concurrently request // a union of the same pair of labels. If the table entry is uninitialized, // (i.e. 0) use a compare-exchange to set the entry to kInitializingLabel // (i.e. -1) to mark that we are initializing it. dfsan_label label = 0; if (atomic_compare_exchange_strong(table_ent, &label, kInitializingLabel, memory_order_acquire)) { // Check whether l2 subsumes l1. We don't need to check whether l1 // subsumes l2 because we are guaranteed here that l1 < l2, and (at least // in the cases we are interested in) a label may only subsume labels // created earlier (i.e. with a lower numerical value). if (__dfsan_label_info[l2].l1 == l1 || __dfsan_label_info[l2].l2 == l1) { label = l2; } else { label = atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1; CHECK_NE(label, kInitializingLabel); __dfsan_label_info[label].l1 = l1; __dfsan_label_info[label].l2 = l2; } atomic_store(table_ent, label, memory_order_release); } else if (label == kInitializingLabel) { // Another thread is initializing the entry. Wait until it is finished. do { internal_sched_yield(); label = atomic_load(table_ent, memory_order_acquire); } while (label == kInitializingLabel); } return label; } extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label __dfsan_union_load(const dfsan_label *ls, size_t n) { dfsan_label label = ls[0]; for (size_t i = 1; i != n; ++i) { dfsan_label next_label = ls[i]; if (label != next_label) label = __dfsan_union(label, next_label); } return label; } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_unimplemented(char *fname) { Report("WARNING: DataFlowSanitizer: call to uninstrumented function %s\n", fname); } // Like __dfsan_union, but for use from the client or custom functions. Hence // the equality comparison is done here before calling __dfsan_union. SANITIZER_INTERFACE_ATTRIBUTE dfsan_label dfsan_union(dfsan_label l1, dfsan_label l2) { if (l1 == l2) return l1; return __dfsan_union(l1, l2); } SANITIZER_INTERFACE_ATTRIBUTE dfsan_label dfsan_create_label(const char *desc, void *userdata) { dfsan_label label = atomic_fetch_add(&__dfsan_last_label, 1, memory_order_relaxed) + 1; CHECK_NE(label, kInitializingLabel); __dfsan_label_info[label].l1 = __dfsan_label_info[label].l2 = 0; __dfsan_label_info[label].desc = desc; __dfsan_label_info[label].userdata = userdata; return label; } extern "C" SANITIZER_INTERFACE_ATTRIBUTE void __dfsan_set_label(dfsan_label label, void *addr, size_t size) { for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp) *labelp = label; } SANITIZER_INTERFACE_ATTRIBUTE void dfsan_set_label(dfsan_label label, void *addr, size_t size) { __dfsan_set_label(label, addr, size); } SANITIZER_INTERFACE_ATTRIBUTE void dfsan_add_label(dfsan_label label, void *addr, size_t size) { for (dfsan_label *labelp = shadow_for(addr); size != 0; --size, ++labelp) if (*labelp != label) *labelp = __dfsan_union(*labelp, label); } // Unlike the other dfsan interface functions the behavior of this function // depends on the label of one of its arguments. Hence it is implemented as a // custom function. extern "C" SANITIZER_INTERFACE_ATTRIBUTE dfsan_label __dfsw_dfsan_get_label(long data, dfsan_label data_label, dfsan_label *ret_label) { *ret_label = 0; return data_label; } SANITIZER_INTERFACE_ATTRIBUTE dfsan_label dfsan_read_label(const void *addr, size_t size) { if (size == 0) return 0; return __dfsan_union_load(shadow_for(addr), size); } SANITIZER_INTERFACE_ATTRIBUTE const struct dfsan_label_info *dfsan_get_label_info(dfsan_label label) { return &__dfsan_label_info[label]; } int dfsan_has_label(dfsan_label label, dfsan_label elem) { if (label == elem) return true; const dfsan_label_info *info = dfsan_get_label_info(label); if (info->l1 != 0) { return dfsan_has_label(info->l1, elem) || dfsan_has_label(info->l2, elem); } else { return false; } } dfsan_label dfsan_has_label_with_desc(dfsan_label label, const char *desc) { const dfsan_label_info *info = dfsan_get_label_info(label); if (info->l1 != 0) { return dfsan_has_label_with_desc(info->l1, desc) || dfsan_has_label_with_desc(info->l2, desc); } else { return internal_strcmp(desc, info->desc) == 0; } } #ifdef DFSAN_NOLIBC extern "C" void dfsan_init() { #else static void dfsan_init(int argc, char **argv, char **envp) { #endif MmapFixedNoReserve(kShadowAddr, kUnusedAddr - kShadowAddr); // Protect the region of memory we don't use, to preserve the one-to-one // mapping from application to shadow memory. But if ASLR is disabled, Linux // will load our executable in the middle of our unused region. This mostly // works so long as the program doesn't use too much memory. We support this // case by disabling memory protection when ASLR is disabled. uptr init_addr = (uptr)&dfsan_init; if (!(init_addr >= kUnusedAddr && init_addr < kAppAddr)) Mprotect(kUnusedAddr, kAppAddr - kUnusedAddr); } #ifndef DFSAN_NOLIBC __attribute__((section(".preinit_array"), used)) static void (*dfsan_init_ptr)(int, char **, char **) = dfsan_init; #endif <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "core/math.h" using namespace narukami; TEST(math,rcp){ EXPECT_FLOAT_EQ(rcp(2.0f),0.5f); EXPECT_FLOAT_EQ(rcp(3.0f),1.0f/3.0f); EXPECT_FLOAT_EQ(rcp(5.0f),1.0f/5.0f); EXPECT_FLOAT_EQ(rcp(7.0f),1.0f/7.0f); } TEST(math,isnan){ float x=0.0f/0.0f; EXPECT_TRUE(isnan(x)); x=1.0f/0.0f; EXPECT_FALSE(isnan(x)); } TEST(math,isinf){ float x=0.0f/0.0f; EXPECT_FALSE(isinf(x)); x=1.0f/0.0f; EXPECT_TRUE(isinf(x)); } TEST(math,cast_i2f){ int x=1<<23; float y=cast_i2f(x); EXPECT_EQ(cast_f2i(y),x); } TEST(math,min){ float x=10; float y=20; float z=30; float w=5; EXPECT_FLOAT_EQ(min(x,y),10); EXPECT_FLOAT_EQ(min(x,y,z),10); EXPECT_FLOAT_EQ(min(x,y,z,w),5); } TEST(math,max){ float x=10; float y=20; float z=30; float w=5; EXPECT_FLOAT_EQ(max(x,y),20); EXPECT_FLOAT_EQ(max(x,y,z),30); EXPECT_FLOAT_EQ(max(x,y,z,w),30); } TEST(math,deg2rad){ float deg=180; float rad=deg2rad(deg); EXPECT_FLOAT_EQ(rad,3.1415927f); } TEST(math,rad2deg){ float rad=3.1415927f; float deg=rad2deg(rad); EXPECT_FLOAT_EQ(deg,180); } #include "core/vector.h" TEST(vector3f,add){ Vector3f v1(1,2,3); Vector3f v2(4,5,6); auto v3=v1+v2; EXPECT_EQ(v3,Vector3f(5,7,9)); } TEST(vector3f,sub){ Vector3f v1(1,2,3); Vector3f v2(4,5,6); auto v3=v1-v2; EXPECT_EQ(v3,Vector3f(-3,-3,-3)); } TEST(vector3f,mul){ Vector3f v1(1,2,3); Vector3f v2(4,5,6); auto v3=v1*v2; EXPECT_EQ(v3,Vector3f(4,10,18)); } TEST(vector3f,mul2){ Vector3f v1(1,2,3); float f=2; auto v2=v1*f; EXPECT_EQ(v2,Vector3f(2,4,6)); } TEST(vector3f,div){ Vector3f v1(1,2,3); float f=2; auto v2=v1/f; EXPECT_EQ(v2,Vector3f(0.5f,1.0f,1.5f)); } TEST(vector3f,equal){ Vector3f v1(1); Vector3f v2(2); Vector3f v3(2); EXPECT_TRUE(v1!=v3); EXPECT_TRUE(v2==v3); } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc,argv); auto ret = RUN_ALL_TESTS(); return ret; } <commit_msg>add test of div int zero<commit_after>#include "gtest/gtest.h" #include "core/math.h" using namespace narukami; TEST(math,rcp){ EXPECT_FLOAT_EQ(rcp(2.0f),0.5f); EXPECT_FLOAT_EQ(rcp(3.0f),1.0f/3.0f); EXPECT_FLOAT_EQ(rcp(5.0f),1.0f/5.0f); EXPECT_FLOAT_EQ(rcp(7.0f),1.0f/7.0f); } TEST(math,isnan){ float x=0.0f/0.0f; EXPECT_TRUE(isnan(x)); x=1.0f/0.0f; EXPECT_FALSE(isnan(x)); } TEST(math,isinf){ float x=0.0f/0.0f; EXPECT_FALSE(isinf(x)); x=1.0f/0.0f; EXPECT_TRUE(isinf(x)); } TEST(math,cast_i2f){ int x=1<<23; float y=cast_i2f(x); EXPECT_EQ(cast_f2i(y),x); } TEST(math,min){ float x=10; float y=20; float z=30; float w=5; EXPECT_FLOAT_EQ(min(x,y),10); EXPECT_FLOAT_EQ(min(x,y,z),10); EXPECT_FLOAT_EQ(min(x,y,z,w),5); } TEST(math,max){ float x=10; float y=20; float z=30; float w=5; EXPECT_FLOAT_EQ(max(x,y),20); EXPECT_FLOAT_EQ(max(x,y,z),30); EXPECT_FLOAT_EQ(max(x,y,z,w),30); } TEST(math,deg2rad){ float deg=180; float rad=deg2rad(deg); EXPECT_FLOAT_EQ(rad,3.1415927f); } TEST(math,rad2deg){ float rad=3.1415927f; float deg=rad2deg(rad); EXPECT_FLOAT_EQ(deg,180); } #include "core/vector.h" TEST(type,int_div_zero){ int a= 1/0; EXPECT_EQ(a,0); } TEST(vector3f,add){ Vector3f v1(1,2,3); Vector3f v2(4,5,6); auto v3=v1+v2; EXPECT_EQ(v3,Vector3f(5,7,9)); } TEST(vector3f,sub){ Vector3f v1(1,2,3); Vector3f v2(4,5,6); auto v3=v1-v2; EXPECT_EQ(v3,Vector3f(-3,-3,-3)); } TEST(vector3f,mul){ Vector3f v1(1,2,3); Vector3f v2(4,5,6); auto v3=v1*v2; EXPECT_EQ(v3,Vector3f(4,10,18)); } TEST(vector3f,mul2){ Vector3f v1(1,2,3); float f=2; auto v2=v1*f; EXPECT_EQ(v2,Vector3f(2,4,6)); } TEST(vector3f,div){ Vector3f v1(1,2,3); float f=2; auto v2=v1/f; EXPECT_EQ(v2,Vector3f(0.5f,1.0f,1.5f)); } TEST(vector3f,equal){ Vector3f v1(1); Vector3f v2(2); Vector3f v3(2); EXPECT_TRUE(v1!=v3); EXPECT_TRUE(v2==v3); } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc,argv); auto ret = RUN_ALL_TESTS(); return ret; } <|endoftext|>
<commit_before>#pragma once #include <type_traits> #include <utility> #include <memory> #include <string> #include <chrono> #include <uv.h> #include "request.hpp" #include "stream.hpp" #include "util.hpp" namespace uvw { namespace details { enum class UVTcpFlags: std::underlying_type_t<uv_tcp_flags> { IPV6ONLY = UV_TCP_IPV6ONLY }; } /** * @brief The TcpHandle handle. * * TCP handles are used to represent both TCP streams and servers.<br/> * By default, _IPv4_ is used as a template parameter. The handle already * supports _IPv6_ out-of-the-box by using `uvw::IPv6`. * * To create a `TcpHandle` through a `Loop`, arguments follow: * * * An optional integer value that indicates the flags used to initialize * the socket. * * See the official * [documentation](http://docs.libuv.org/en/v1.x/tcp.html#c.uv_tcp_init_ex) * for further details. */ class TcpHandle final: public StreamHandle<TcpHandle, uv_tcp_t> { public: using Time = std::chrono::duration<unsigned int>; using Bind = details::UVTcpFlags; using IPv4 = uvw::IPv4; using IPv6 = uvw::IPv6; explicit TcpHandle(ConstructorAccess ca, std::shared_ptr<Loop> ref, unsigned int f = {}) : StreamHandle{ca, std::move(ref)}, tag{f ? FLAGS : DEFAULT}, flags{f} {} /** * @brief Initializes the handle. No socket is created as of yet. * @return True in case of success, false otherwise. */ bool init() { return (tag == FLAGS) ? initialize(&uv_tcp_init_ex, flags) : initialize(&uv_tcp_init); } /** * @brief Opens an existing file descriptor or SOCKET as a TCP handle. * * The passed file descriptor or SOCKET is not checked for its type, but * it’s required that it represents a valid stream socket. * * @param socket A valid socket handle (either a file descriptor or a SOCKET). */ void open(OSSocketHandle socket) { invoke(&uv_tcp_open, get(), socket); } /** * @brief Enables/Disables Nagle’s algorithm. * @param value True to enable it, false otherwise. * @return True in case of success, false otherwise. */ bool noDelay(bool value = false) { return (0 == uv_tcp_nodelay(get(), value)); } /** * @brief Enables/Disables TCP keep-alive. * @param enable True to enable it, false otherwise. * @param time Initial delay in seconds (use * `std::chrono::duration<unsigned int>`). * @return True in case of success, false otherwise. */ bool keepAlive(bool enable = false, Time time = Time{0}) { return (0 == uv_tcp_keepalive(get(), enable, time.count())); } /** * @brief Enables/Disables simultaneous asynchronous accept requests. * * Enables/Disables simultaneous asynchronous accept requests that are * queued by the operating system when listening for new TCP * connections.<br/> * This setting is used to tune a TCP server for the desired performance. * Having simultaneous accepts can significantly improve the rate of * accepting connections (which is why it is enabled by default) but may * lead to uneven load distribution in multi-process setups. * * @param enable True to enable it, false otherwise. * @return True in case of success, false otherwise. */ bool simultaneousAccepts(bool enable = true) { return (0 == uv_tcp_simultaneous_accepts(get(), enable)); } /** * @brief Binds the handle to an address and port. * * A successful call to this function does not guarantee that the call to * `listen()` or `connect()` will work properly.<br/> * ErrorEvent events can be emitted because of either this function or the * ones mentioned above. * * Available flags are: * * * `TcpHandle::Bind::IPV6ONLY`: it disables dual-stack support and only * IPv6 is used. * * @param addr Initialized `sockaddr_in` or `sockaddr_in6` data structure. * @param opts Optional additional flags. */ void bind(const sockaddr &addr, Flags<Bind> opts = Flags<Bind>{}) { invoke(&uv_tcp_bind, get(), &addr, opts); } /** * @brief Binds the handle to an address and port. * * A successful call to this function does not guarantee that the call to * `listen()` or `connect()` will work properly.<br/> * ErrorEvent events can be emitted because of either this function or the * ones mentioned above. * * Available flags are: * * * `TcpHandle::Bind::IPV6ONLY`: it disables dual-stack support and only * IPv6 is used. * * @param ip The address to which to bind. * @param port The port to which to bind. * @param opts Optional additional flags. */ template<typename I = IPv4> void bind(std::string ip, unsigned int port, Flags<Bind> opts = Flags<Bind>{}) { typename details::IpTraits<I>::Type addr; details::IpTraits<I>::addrFunc(ip.data(), port, &addr); bind(reinterpret_cast<const sockaddr &>(addr), std::move(opts)); } /** * @brief Binds the handle to an address and port. * * A successful call to this function does not guarantee that the call to * `listen()` or `connect()` will work properly.<br/> * ErrorEvent events can be emitted because of either this function or the * ones mentioned above. * * Available flags are: * * * `TcpHandle::Bind::IPV6ONLY`: it disables dual-stack support and only * IPv6 is used. * * @param addr A valid instance of Addr. * @param opts Optional additional flags. */ template<typename I = IPv4> void bind(Addr addr, Flags<Bind> opts = Flags<Bind>{}) { bind<I>(std::move(addr.ip), addr.port, std::move(opts)); } /** * @brief Gets the current address to which the handle is bound. * @return A valid instance of Addr, an empty one in case of errors. */ template<typename I = IPv4> Addr sock() const noexcept { return details::address<I>(&uv_tcp_getsockname, get()); } /** * @brief Gets the address of the peer connected to the handle. * @return A valid instance of Addr, an empty one in case of errors. */ template<typename I = IPv4> Addr peer() const noexcept { return details::address<I>(&uv_tcp_getpeername, get()); } /** * @brief Establishes an IPv4 or IPv6 TCP connection. * * A ConnectEvent event is emitted when the connection has been * established.<br/> * An ErrorEvent event is emitted in case of errors during the connection. * * @param addr Initialized `sockaddr_in` or `sockaddr_in6` data structure. */ void connect(const sockaddr &addr) { auto listener = [ptr = shared_from_this()](const auto &event, const auto &) { ptr->publish(event); }; auto req = loop().resource<details::ConnectReq>(); req->once<ErrorEvent>(listener); req->once<ConnectEvent>(listener); req->connect(&uv_tcp_connect, get(), &addr); } /** * @brief Establishes an IPv4 or IPv6 TCP connection. * * A ConnectEvent event is emitted when the connection has been * established.<br/> * An ErrorEvent event is emitted in case of errors during the connection. * * @param ip The address to which to bind. * @param port The port to which to bind. */ template<typename I = IPv4> void connect(std::string ip, unsigned int port) { typename details::IpTraits<I>::Type addr; details::IpTraits<I>::addrFunc(ip.data(), port, &addr); connect(reinterpret_cast<const sockaddr &>(addr)); } /** * @brief Establishes an IPv4 or IPv6 TCP connection. * * A ConnectEvent event is emitted when the connection has been * established.<br/> * An ErrorEvent event is emitted in case of errors during the connection. * * @param addr A valid instance of Addr. */ template<typename I = IPv4> void connect(Addr addr) { connect<I>(std::move(addr.ip), addr.port); } private: enum { DEFAULT, FLAGS } tag; unsigned int flags; }; } <commit_msg>updated doc<commit_after>#pragma once #include <type_traits> #include <utility> #include <memory> #include <string> #include <chrono> #include <uv.h> #include "request.hpp" #include "stream.hpp" #include "util.hpp" namespace uvw { namespace details { enum class UVTcpFlags: std::underlying_type_t<uv_tcp_flags> { IPV6ONLY = UV_TCP_IPV6ONLY }; } /** * @brief The TcpHandle handle. * * TCP handles are used to represent both TCP streams and servers.<br/> * By default, _IPv4_ is used as a template parameter. The handle already * supports _IPv6_ out-of-the-box by using `uvw::IPv6`. * * To create a `TcpHandle` through a `Loop`, arguments follow: * * * An optional integer value that indicates the flags used to initialize * the socket. * * See the official * [documentation](http://docs.libuv.org/en/v1.x/tcp.html#c.uv_tcp_init_ex) * for further details. */ class TcpHandle final: public StreamHandle<TcpHandle, uv_tcp_t> { public: using Time = std::chrono::duration<unsigned int>; using Bind = details::UVTcpFlags; using IPv4 = uvw::IPv4; using IPv6 = uvw::IPv6; explicit TcpHandle(ConstructorAccess ca, std::shared_ptr<Loop> ref, unsigned int f = {}) : StreamHandle{ca, std::move(ref)}, tag{f ? FLAGS : DEFAULT}, flags{f} {} /** * @brief Initializes the handle. No socket is created as of yet. * @return True in case of success, false otherwise. */ bool init() { return (tag == FLAGS) ? initialize(&uv_tcp_init_ex, flags) : initialize(&uv_tcp_init); } /** * @brief Opens an existing file descriptor or SOCKET as a TCP handle. * * The passed file descriptor or SOCKET is not checked for its type, but * it’s required that it represents a valid stream socket. * * @param socket A valid socket handle (either a file descriptor or a SOCKET). */ void open(OSSocketHandle socket) { invoke(&uv_tcp_open, get(), socket); } /** * @brief Enables/Disables Nagle’s algorithm. * @param value True to enable it, false otherwise. * @return True in case of success, false otherwise. */ bool noDelay(bool value = false) { return (0 == uv_tcp_nodelay(get(), value)); } /** * @brief Enables/Disables TCP keep-alive. * @param enable True to enable it, false otherwise. * @param time Initial delay in seconds (use * `std::chrono::duration<unsigned int>`). * @return True in case of success, false otherwise. */ bool keepAlive(bool enable = false, Time time = Time{0}) { return (0 == uv_tcp_keepalive(get(), enable, time.count())); } /** * @brief Enables/Disables simultaneous asynchronous accept requests. * * Enables/Disables simultaneous asynchronous accept requests that are * queued by the operating system when listening for new TCP * connections.<br/> * This setting is used to tune a TCP server for the desired performance. * Having simultaneous accepts can significantly improve the rate of * accepting connections (which is why it is enabled by default) but may * lead to uneven load distribution in multi-process setups. * * @param enable True to enable it, false otherwise. * @return True in case of success, false otherwise. */ bool simultaneousAccepts(bool enable = true) { return (0 == uv_tcp_simultaneous_accepts(get(), enable)); } /** * @brief Binds the handle to an address and port. * * A successful call to this function does not guarantee that the call to * `listen()` or `connect()` will work properly.<br/> * ErrorEvent events can be emitted because of either this function or the * ones mentioned above. * * Available flags are: * * * `TcpHandle::Bind::IPV6ONLY`: it disables dual-stack support and only * IPv6 is used. * * @param addr Initialized `sockaddr_in` or `sockaddr_in6` data structure. * @param opts Optional additional flags. */ void bind(const sockaddr &addr, Flags<Bind> opts = Flags<Bind>{}) { invoke(&uv_tcp_bind, get(), &addr, opts); } /** * @brief Binds the handle to an address and port. * * A successful call to this function does not guarantee that the call to * `listen()` or `connect()` will work properly.<br/> * ErrorEvent events can be emitted because of either this function or the * ones mentioned above. * * Available flags are: * * * `TcpHandle::Bind::IPV6ONLY`: it disables dual-stack support and only * IPv6 is used. * * @param ip The address to which to bind. * @param port The port to which to bind. * @param opts Optional additional flags. */ template<typename I = IPv4> void bind(std::string ip, unsigned int port, Flags<Bind> opts = Flags<Bind>{}) { typename details::IpTraits<I>::Type addr; details::IpTraits<I>::addrFunc(ip.data(), port, &addr); bind(reinterpret_cast<const sockaddr &>(addr), std::move(opts)); } /** * @brief Binds the handle to an address and port. * * A successful call to this function does not guarantee that the call to * `listen()` or `connect()` will work properly.<br/> * ErrorEvent events can be emitted because of either this function or the * ones mentioned above. * * Available flags are: * * * `TcpHandle::Bind::IPV6ONLY`: it disables dual-stack support and only * IPv6 is used. * * @param addr A valid instance of Addr. * @param opts Optional additional flags. */ template<typename I = IPv4> void bind(Addr addr, Flags<Bind> opts = Flags<Bind>{}) { bind<I>(std::move(addr.ip), addr.port, std::move(opts)); } /** * @brief Gets the current address to which the handle is bound. * @return A valid instance of Addr, an empty one in case of errors. */ template<typename I = IPv4> Addr sock() const noexcept { return details::address<I>(&uv_tcp_getsockname, get()); } /** * @brief Gets the address of the peer connected to the handle. * @return A valid instance of Addr, an empty one in case of errors. */ template<typename I = IPv4> Addr peer() const noexcept { return details::address<I>(&uv_tcp_getpeername, get()); } /** * @brief Establishes an IPv4 or IPv6 TCP connection. * * On Windows if the addr is initialized to point to an unspecified address * (`0.0.0.0` or `::`) it will be changed to point to localhost. This is * done to match the behavior of Linux systems. * * A ConnectEvent event is emitted when the connection has been * established.<br/> * An ErrorEvent event is emitted in case of errors during the connection. * * @param addr Initialized `sockaddr_in` or `sockaddr_in6` data structure. */ void connect(const sockaddr &addr) { auto listener = [ptr = shared_from_this()](const auto &event, const auto &) { ptr->publish(event); }; auto req = loop().resource<details::ConnectReq>(); req->once<ErrorEvent>(listener); req->once<ConnectEvent>(listener); req->connect(&uv_tcp_connect, get(), &addr); } /** * @brief Establishes an IPv4 or IPv6 TCP connection. * * A ConnectEvent event is emitted when the connection has been * established.<br/> * An ErrorEvent event is emitted in case of errors during the connection. * * @param ip The address to which to bind. * @param port The port to which to bind. */ template<typename I = IPv4> void connect(std::string ip, unsigned int port) { typename details::IpTraits<I>::Type addr; details::IpTraits<I>::addrFunc(ip.data(), port, &addr); connect(reinterpret_cast<const sockaddr &>(addr)); } /** * @brief Establishes an IPv4 or IPv6 TCP connection. * * A ConnectEvent event is emitted when the connection has been * established.<br/> * An ErrorEvent event is emitted in case of errors during the connection. * * @param addr A valid instance of Addr. */ template<typename I = IPv4> void connect(Addr addr) { connect<I>(std::move(addr.ip), addr.port); } private: enum { DEFAULT, FLAGS } tag; unsigned int flags; }; } <|endoftext|>
<commit_before>// Filename: internalName.cxx // Created by: masad (15Jul04) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// #include "pandabase.h" #include "internalName.h" #include "datagram.h" #include "datagramIterator.h" #include "bamReader.h" #include "preparedGraphicsObjects.h" PT(InternalName) InternalName::_root; PT(InternalName) InternalName::_error; PT(InternalName) InternalName::_default; PT(InternalName) InternalName::_vertex; PT(InternalName) InternalName::_normal; PT(InternalName) InternalName::_tangent; PT(InternalName) InternalName::_binormal; PT(InternalName) InternalName::_texcoord; PT(InternalName) InternalName::_color; PT(InternalName) InternalName::_rotate; PT(InternalName) InternalName::_size; PT(InternalName) InternalName::_aspect_ratio; PT(InternalName) InternalName::_transform_blend; PT(InternalName) InternalName::_transform_weight; PT(InternalName) InternalName::_transform_index; PT(InternalName) InternalName::_index; PT(InternalName) InternalName::_world; PT(InternalName) InternalName::_camera; PT(InternalName) InternalName::_model; PT(InternalName) InternalName::_view; TypeHandle InternalName::_type_handle; TypeHandle InternalName::_texcoord_type_handle; //////////////////////////////////////////////////////////////////// // Function: InternalName::Constructor // Access: Private // Description: Use make() to make a new InternalName instance. //////////////////////////////////////////////////////////////////// InternalName:: InternalName(InternalName *parent, const string &basename) : _parent(parent), _basename(basename) { } //////////////////////////////////////////////////////////////////// // Function: InternalName::Destructor // Access: Published, Virtual // Description: //////////////////////////////////////////////////////////////////// InternalName:: ~InternalName() { #ifndef NDEBUG { // unref() should have removed us from our parent's table already. MutexHolder holder(_parent->_name_table_lock); NameTable::iterator ni = _parent->_name_table.find(_basename); nassertv(ni == _parent->_name_table.end()); } #endif } //////////////////////////////////////////////////////////////////// // Function: InternalName::unref // Access: Published // Description: This method overrides ReferenceCount::unref() to // clear the pointer from its parent's table when // its reference count goes to zero. //////////////////////////////////////////////////////////////////// bool InternalName:: unref() const { if (_parent == (const InternalName *)NULL) { // No parent; no problem. This is the root InternalName. // Actually, this probably shouldn't be destructing, but I guess // it might at application shutdown. return TypedWritableReferenceCount::unref(); } MutexHolder holder(_parent->_name_table_lock); if (ReferenceCount::unref()) { return true; } // The reference count has just reached zero. NameTable::iterator ni = _parent->_name_table.find(_basename); nassertr(ni != _parent->_name_table.end(), false); _parent->_name_table.erase(ni); return false; } //////////////////////////////////////////////////////////////////// // Function: InternalName::append // Access: Published // Description: Constructs a new InternalName based on this name, // with the indicated string following it. This is a // cheaper way to construct a hierarchical name than // InternalName::make(parent->get_name() + ".basename"). //////////////////////////////////////////////////////////////////// PT(InternalName) InternalName:: append(const string &name) { test_ref_count_integrity(); if (name.empty()) { return this; } size_t dot = name.rfind('.'); if (dot != string::npos) { return append(name.substr(0, dot))->append(name.substr(dot + 1)); } MutexHolder holder(_name_table_lock); NameTable::iterator ni = _name_table.find(name); if (ni != _name_table.end()) { return (*ni).second; } InternalName *internal_name = new InternalName(this, name); _name_table[name] = internal_name; return internal_name; } //////////////////////////////////////////////////////////////////// // Function: InternalName::get_name // Access: Published // Description: Returns the complete name represented by the // InternalName and all of its parents. //////////////////////////////////////////////////////////////////// string InternalName:: get_name() const { if (_parent == get_root()) { return _basename; } else if (_parent == (InternalName *)NULL) { return string(); } else { return _parent->get_name() + "." + _basename; } } //////////////////////////////////////////////////////////////////// // Function: InternalName::find_ancestor // Access: Published // Description: Returns the index of the ancestor with the indicated // basename, or -1 if no ancestor has that basename. // Returns 0 if this name has the basename. // // This index value may be passed to get_ancestor() or // get_net_basename() to retrieve more information about // the indicated name. //////////////////////////////////////////////////////////////////// int InternalName:: find_ancestor(const string &basename) const { test_ref_count_integrity(); if (_basename == basename) { return 0; } else if (_parent != (InternalName *)NULL) { int index = _parent->find_ancestor(basename); if (index >= 0) { return index + 1; } } return -1; } //////////////////////////////////////////////////////////////////// // Function: InternalName::get_ancestor // Access: Published // Description: Returns the ancestor with the indicated index number. // 0 is this name itself, 1 is the name's parent, 2 is // the parent's parent, and so on. If there are not // enough ancestors, returns the root InternalName. //////////////////////////////////////////////////////////////////// const InternalName *InternalName:: get_ancestor(int n) const { test_ref_count_integrity(); if (n == 0) { return this; } else if (_parent != (InternalName *)NULL) { return _parent->get_ancestor(n - 1); } else { return get_root(); } } //////////////////////////////////////////////////////////////////// // Function: InternalName::get_top // Access: Published // Description: Returns the oldest ancestor in the InternalName's // chain, not counting the root. This will be the first // name in the string, e.g. "texcoord.foo.bar" will // return the InternalName "texcoord". //////////////////////////////////////////////////////////////////// const InternalName *InternalName:: get_top() const { test_ref_count_integrity(); if (_parent != (InternalName *)NULL && _parent != get_root()) { return _parent->get_top(); } return this; } //////////////////////////////////////////////////////////////////// // Function: InternalName::get_net_basename // Access: Published // Description: Returns the basename of this name prefixed by the // indicated number of ancestors. 0 is this name's // basename, 1 is parent.basename, 2 is // grandparent.parent.basename, and so on. //////////////////////////////////////////////////////////////////// string InternalName:: get_net_basename(int n) const { if (n < 0) { return ""; } else if (n == 0) { return _basename; } else if (_parent != (InternalName *)NULL && _parent != get_root()) { return _parent->get_net_basename(n - 1) + "." + _basename; } else { return _basename; } } //////////////////////////////////////////////////////////////////// // Function: InternalName::output // Access: Published // Description: //////////////////////////////////////////////////////////////////// void InternalName:: output(ostream &out) const { if (_parent == get_root()) { out << _basename; } else if (_parent == (InternalName *)NULL) { out << "(root)"; } else { _parent->output(out); out << '.' << _basename; } } //////////////////////////////////////////////////////////////////// // Function: InternalName::register_with_read_factory // Access: Public, Static // Description: Factory method to generate a InternalName object //////////////////////////////////////////////////////////////////// void InternalName:: register_with_read_factory() { BamReader::get_factory()->register_factory(get_class_type(), make_from_bam); BamReader::get_factory()->register_factory(_texcoord_type_handle, make_texcoord_from_bam); } //////////////////////////////////////////////////////////////////// // Function: InternalName::finalize // Access: Public, Virtual // Description: Called by the BamReader to perform any final actions // needed for setting up the object after all objects // have been read and all pointers have been completed. //////////////////////////////////////////////////////////////////// void InternalName:: finalize(BamReader *) { // Unref the pointer that we explicitly reffed in make_from_bam(). unref(); // We should never get back to zero after unreffing our own count, // because we expect to have been stored in a pointer somewhere. If // we do get to zero, it's a memory leak; the way to avoid this is // to call unref_delete() above instead of unref(), but this is // dangerous to do from within a virtual function. nassertv(get_ref_count() != 0); } //////////////////////////////////////////////////////////////////// // Function: InternalName::make_from_bam // Access: Protected, Static // Description: This function is called by the BamReader's factory // when a new object of type InternalName is encountered // in the Bam file. It should create the InternalName // and extract its information from the file. //////////////////////////////////////////////////////////////////// TypedWritable *InternalName:: make_from_bam(const FactoryParams &params) { // The process of making a InternalName is slightly // different than making other Writable objects. // That is because all creation of InternalNames should // be done through the make() constructor. DatagramIterator scan; BamReader *manager; parse_params(params, scan, manager); // The name is the only thing written to the data stream. string name = scan.get_string(); // Make a new InternalName with that name (or get the previous one // if there is one already). PT(InternalName) me = make(name); // But now we have a problem, since we have to hold the reference // count and there's no way to return a TypedWritable while still // holding the reference count! We work around this by explicitly // upping the count, and also setting a finalize() callback to down // it later. me->ref(); manager->register_finalize(me); return me.p(); } //////////////////////////////////////////////////////////////////// // Function: InternalName::make_texcoord_from_bam // Access: Protected, Static // Description: This is a temporary method; it exists only to support // old bam files (4.11 through 4.17) generated before we // renamed this class from TexCoordName to InternalName. //////////////////////////////////////////////////////////////////// TypedWritable *InternalName:: make_texcoord_from_bam(const FactoryParams &params) { DatagramIterator scan; BamReader *manager; parse_params(params, scan, manager); string name = scan.get_string(); PT(InternalName) me; if (name == "default") { me = get_texcoord(); } else { me = get_texcoord_name(name); } me->ref(); manager->register_finalize(me); return me.p(); } //////////////////////////////////////////////////////////////////// // Function: InternalName::write_datagram // Access: Public // Description: Function to write the important information in // the particular object to a Datagram //////////////////////////////////////////////////////////////////// void InternalName:: write_datagram(BamWriter *manager, Datagram &me) { me.add_string(get_name()); } <commit_msg>fix crash at exit<commit_after>// Filename: internalName.cxx // Created by: masad (15Jul04) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// #include "pandabase.h" #include "internalName.h" #include "datagram.h" #include "datagramIterator.h" #include "bamReader.h" #include "preparedGraphicsObjects.h" PT(InternalName) InternalName::_root; PT(InternalName) InternalName::_error; PT(InternalName) InternalName::_default; PT(InternalName) InternalName::_vertex; PT(InternalName) InternalName::_normal; PT(InternalName) InternalName::_tangent; PT(InternalName) InternalName::_binormal; PT(InternalName) InternalName::_texcoord; PT(InternalName) InternalName::_color; PT(InternalName) InternalName::_rotate; PT(InternalName) InternalName::_size; PT(InternalName) InternalName::_aspect_ratio; PT(InternalName) InternalName::_transform_blend; PT(InternalName) InternalName::_transform_weight; PT(InternalName) InternalName::_transform_index; PT(InternalName) InternalName::_index; PT(InternalName) InternalName::_world; PT(InternalName) InternalName::_camera; PT(InternalName) InternalName::_model; PT(InternalName) InternalName::_view; TypeHandle InternalName::_type_handle; TypeHandle InternalName::_texcoord_type_handle; //////////////////////////////////////////////////////////////////// // Function: InternalName::Constructor // Access: Private // Description: Use make() to make a new InternalName instance. //////////////////////////////////////////////////////////////////// InternalName:: InternalName(InternalName *parent, const string &basename) : _parent(parent), _basename(basename) { } //////////////////////////////////////////////////////////////////// // Function: InternalName::Destructor // Access: Published, Virtual // Description: //////////////////////////////////////////////////////////////////// InternalName:: ~InternalName() { #ifndef NDEBUG if (_parent != (const InternalName *)NULL) { // unref() should have removed us from our parent's table already. MutexHolder holder(_parent->_name_table_lock); NameTable::iterator ni = _parent->_name_table.find(_basename); nassertv(ni == _parent->_name_table.end()); } #endif } //////////////////////////////////////////////////////////////////// // Function: InternalName::unref // Access: Published // Description: This method overrides ReferenceCount::unref() to // clear the pointer from its parent's table when // its reference count goes to zero. //////////////////////////////////////////////////////////////////// bool InternalName:: unref() const { if (_parent == (const InternalName *)NULL) { // No parent; no problem. This is the root InternalName. // Actually, this probably shouldn't be destructing, but I guess // it might at application shutdown. return TypedWritableReferenceCount::unref(); } MutexHolder holder(_parent->_name_table_lock); if (ReferenceCount::unref()) { return true; } // The reference count has just reached zero. NameTable::iterator ni = _parent->_name_table.find(_basename); nassertr(ni != _parent->_name_table.end(), false); _parent->_name_table.erase(ni); return false; } //////////////////////////////////////////////////////////////////// // Function: InternalName::append // Access: Published // Description: Constructs a new InternalName based on this name, // with the indicated string following it. This is a // cheaper way to construct a hierarchical name than // InternalName::make(parent->get_name() + ".basename"). //////////////////////////////////////////////////////////////////// PT(InternalName) InternalName:: append(const string &name) { test_ref_count_integrity(); if (name.empty()) { return this; } size_t dot = name.rfind('.'); if (dot != string::npos) { return append(name.substr(0, dot))->append(name.substr(dot + 1)); } MutexHolder holder(_name_table_lock); NameTable::iterator ni = _name_table.find(name); if (ni != _name_table.end()) { return (*ni).second; } InternalName *internal_name = new InternalName(this, name); _name_table[name] = internal_name; return internal_name; } //////////////////////////////////////////////////////////////////// // Function: InternalName::get_name // Access: Published // Description: Returns the complete name represented by the // InternalName and all of its parents. //////////////////////////////////////////////////////////////////// string InternalName:: get_name() const { if (_parent == get_root()) { return _basename; } else if (_parent == (InternalName *)NULL) { return string(); } else { return _parent->get_name() + "." + _basename; } } //////////////////////////////////////////////////////////////////// // Function: InternalName::find_ancestor // Access: Published // Description: Returns the index of the ancestor with the indicated // basename, or -1 if no ancestor has that basename. // Returns 0 if this name has the basename. // // This index value may be passed to get_ancestor() or // get_net_basename() to retrieve more information about // the indicated name. //////////////////////////////////////////////////////////////////// int InternalName:: find_ancestor(const string &basename) const { test_ref_count_integrity(); if (_basename == basename) { return 0; } else if (_parent != (InternalName *)NULL) { int index = _parent->find_ancestor(basename); if (index >= 0) { return index + 1; } } return -1; } //////////////////////////////////////////////////////////////////// // Function: InternalName::get_ancestor // Access: Published // Description: Returns the ancestor with the indicated index number. // 0 is this name itself, 1 is the name's parent, 2 is // the parent's parent, and so on. If there are not // enough ancestors, returns the root InternalName. //////////////////////////////////////////////////////////////////// const InternalName *InternalName:: get_ancestor(int n) const { test_ref_count_integrity(); if (n == 0) { return this; } else if (_parent != (InternalName *)NULL) { return _parent->get_ancestor(n - 1); } else { return get_root(); } } //////////////////////////////////////////////////////////////////// // Function: InternalName::get_top // Access: Published // Description: Returns the oldest ancestor in the InternalName's // chain, not counting the root. This will be the first // name in the string, e.g. "texcoord.foo.bar" will // return the InternalName "texcoord". //////////////////////////////////////////////////////////////////// const InternalName *InternalName:: get_top() const { test_ref_count_integrity(); if (_parent != (InternalName *)NULL && _parent != get_root()) { return _parent->get_top(); } return this; } //////////////////////////////////////////////////////////////////// // Function: InternalName::get_net_basename // Access: Published // Description: Returns the basename of this name prefixed by the // indicated number of ancestors. 0 is this name's // basename, 1 is parent.basename, 2 is // grandparent.parent.basename, and so on. //////////////////////////////////////////////////////////////////// string InternalName:: get_net_basename(int n) const { if (n < 0) { return ""; } else if (n == 0) { return _basename; } else if (_parent != (InternalName *)NULL && _parent != get_root()) { return _parent->get_net_basename(n - 1) + "." + _basename; } else { return _basename; } } //////////////////////////////////////////////////////////////////// // Function: InternalName::output // Access: Published // Description: //////////////////////////////////////////////////////////////////// void InternalName:: output(ostream &out) const { if (_parent == get_root()) { out << _basename; } else if (_parent == (InternalName *)NULL) { out << "(root)"; } else { _parent->output(out); out << '.' << _basename; } } //////////////////////////////////////////////////////////////////// // Function: InternalName::register_with_read_factory // Access: Public, Static // Description: Factory method to generate a InternalName object //////////////////////////////////////////////////////////////////// void InternalName:: register_with_read_factory() { BamReader::get_factory()->register_factory(get_class_type(), make_from_bam); BamReader::get_factory()->register_factory(_texcoord_type_handle, make_texcoord_from_bam); } //////////////////////////////////////////////////////////////////// // Function: InternalName::finalize // Access: Public, Virtual // Description: Called by the BamReader to perform any final actions // needed for setting up the object after all objects // have been read and all pointers have been completed. //////////////////////////////////////////////////////////////////// void InternalName:: finalize(BamReader *) { // Unref the pointer that we explicitly reffed in make_from_bam(). unref(); // We should never get back to zero after unreffing our own count, // because we expect to have been stored in a pointer somewhere. If // we do get to zero, it's a memory leak; the way to avoid this is // to call unref_delete() above instead of unref(), but this is // dangerous to do from within a virtual function. nassertv(get_ref_count() != 0); } //////////////////////////////////////////////////////////////////// // Function: InternalName::make_from_bam // Access: Protected, Static // Description: This function is called by the BamReader's factory // when a new object of type InternalName is encountered // in the Bam file. It should create the InternalName // and extract its information from the file. //////////////////////////////////////////////////////////////////// TypedWritable *InternalName:: make_from_bam(const FactoryParams &params) { // The process of making a InternalName is slightly // different than making other Writable objects. // That is because all creation of InternalNames should // be done through the make() constructor. DatagramIterator scan; BamReader *manager; parse_params(params, scan, manager); // The name is the only thing written to the data stream. string name = scan.get_string(); // Make a new InternalName with that name (or get the previous one // if there is one already). PT(InternalName) me = make(name); // But now we have a problem, since we have to hold the reference // count and there's no way to return a TypedWritable while still // holding the reference count! We work around this by explicitly // upping the count, and also setting a finalize() callback to down // it later. me->ref(); manager->register_finalize(me); return me.p(); } //////////////////////////////////////////////////////////////////// // Function: InternalName::make_texcoord_from_bam // Access: Protected, Static // Description: This is a temporary method; it exists only to support // old bam files (4.11 through 4.17) generated before we // renamed this class from TexCoordName to InternalName. //////////////////////////////////////////////////////////////////// TypedWritable *InternalName:: make_texcoord_from_bam(const FactoryParams &params) { DatagramIterator scan; BamReader *manager; parse_params(params, scan, manager); string name = scan.get_string(); PT(InternalName) me; if (name == "default") { me = get_texcoord(); } else { me = get_texcoord_name(name); } me->ref(); manager->register_finalize(me); return me.p(); } //////////////////////////////////////////////////////////////////// // Function: InternalName::write_datagram // Access: Public // Description: Function to write the important information in // the particular object to a Datagram //////////////////////////////////////////////////////////////////// void InternalName:: write_datagram(BamWriter *manager, Datagram &me) { me.add_string(get_name()); } <|endoftext|>
<commit_before>/* value_function_test.cpp -*- C++ -*- Rémi Attab ([email protected]), 27 Mar 2014 FreeBSD-style copyright and disclaimer apply Tests for ValueFunction. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #define REFLECT_USE_EXCEPTIONS 1 #include "reflect.h" #include "types/primitives.h" #include <boost/test/unit_test.hpp> using namespace std; using namespace reflect; /******************************************************************************/ /* FUNCTION */ /******************************************************************************/ void foo(unsigned& value, int other) { value += other; } BOOST_AUTO_TEST_CASE(fn) { auto valueFn = makeValueFunctionSafe(makeFunction(&foo)); unsigned value = 0; Value ret = (*valueFn)(Value(value), Value(10)); BOOST_CHECK(ret.isVoid()); BOOST_CHECK_EQUAL(value, 10); (*valueFn)(Value(value), Value(10)); BOOST_CHECK_EQUAL(value, 20); } /******************************************************************************/ /* LAMBDA */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(lambda) { unsigned value = 0; auto lambda = [&](unsigned x, unsigned&& z) { return value = x * x + std::move(z); }; auto valueFn = makeValueFunctionSafe(makeFunction(lambda)); Value ret = (*valueFn)(Value(10u), Value(10u)); BOOST_CHECK_EQUAL(value, 110); BOOST_CHECK_EQUAL(ret.get<unsigned>(), 110); } /******************************************************************************/ /* FUNCTOR */ /******************************************************************************/ struct Functor { Functor() : value(0) {} unsigned& operator() (unsigned i) { value += i; return value; } private: unsigned value; }; BOOST_AUTO_TEST_CASE(functor) { auto valueFn = makeValueFunctionSafe(makeFunction(Functor())); { Value ret = (*valueFn)(Value(10u)); BOOST_CHECK_EQUAL(ret.refType(), RefType::LValue); BOOST_CHECK(ret.isCastable<unsigned>()); BOOST_CHECK_EQUAL(ret.cast<unsigned>(), 10); } { Value ret = (*valueFn)(Value(10u)); BOOST_CHECK_EQUAL(ret.cast<unsigned>(), 20); } } /******************************************************************************/ /* MEMBER FUNCTION */ /******************************************************************************/ struct Foo { Foo() : value(0) {} unsigned& bar(unsigned i) { value += i; return value; } unsigned value; }; reflectClass(Foo) {} BOOST_AUTO_TEST_CASE(memberFn) { Foo foo; auto valueFn = makeValueFunctionSafe(makeFunction(&Foo::bar)); { Value ret = (*valueFn)(Value(foo), Value(10u)); BOOST_CHECK_EQUAL(ret.refType(), RefType::LValue); BOOST_CHECK(ret.isCastable<unsigned>()); BOOST_CHECK_EQUAL(ret.cast<unsigned>(), 10); BOOST_CHECK_EQUAL(foo.value, 10); } { Value ret = (*valueFn)(Value(foo), Value(10u)); BOOST_CHECK_EQUAL(ret.cast<unsigned>(), 20); BOOST_CHECK_EQUAL(foo.value, 20); } } /******************************************************************************/ /* CONSTNESS */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(constness) { auto fn = [] (unsigned& i, const unsigned& j) -> const unsigned& { i += j; return i; }; auto valueFn = makeValueFunctionSafe(makeFunction(fn)); { unsigned i = 0; Value ret = (*valueFn)(Value(i), Value(10u)); BOOST_CHECK(ret.isConst()); BOOST_CHECK_EQUAL(ret.refType(), RefType::LValue); BOOST_CHECK_EQUAL(i, 10); BOOST_CHECK_EQUAL(&ret.cast<const unsigned>(), &i); } } <commit_msg>value_function_test now tests the right things.<commit_after>/* value_function_test.cpp -*- C++ -*- Rémi Attab ([email protected]), 27 Mar 2014 FreeBSD-style copyright and disclaimer apply Tests for ValueFunction. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #define REFLECT_USE_EXCEPTIONS 1 #include "reflect.h" #include "types/primitives.h" #include <boost/test/unit_test.hpp> using namespace std; using namespace reflect; /******************************************************************************/ /* FUNCTION */ /******************************************************************************/ void foo(unsigned& value, int other) { value += other; } BOOST_AUTO_TEST_CASE(fn) { auto valueFn = makeValueFunctionSafe(&foo); unsigned value = 0; Value ret = (*valueFn)(Value(value), Value(10)); BOOST_CHECK(ret.isVoid()); BOOST_CHECK_EQUAL(value, 10); (*valueFn)(Value(value), Value(10)); BOOST_CHECK_EQUAL(value, 20); } /******************************************************************************/ /* LAMBDA */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(lambda) { unsigned value = 0; auto lambda = [&](unsigned x, unsigned&& z) { return value = x * x + std::move(z); }; auto valueFn = makeValueFunctionSafe(lambda); Value ret = (*valueFn)(Value(10u), Value(10u)); BOOST_CHECK_EQUAL(value, 110); BOOST_CHECK_EQUAL(ret.get<unsigned>(), 110); } /******************************************************************************/ /* FUNCTOR */ /******************************************************************************/ struct Functor { Functor() : value(0) {} unsigned& operator() (unsigned i) { value += i; return value; } private: unsigned value; }; BOOST_AUTO_TEST_CASE(functor) { auto valueFn = makeValueFunctionSafe(Functor()); { Value ret = (*valueFn)(Value(10u)); BOOST_CHECK_EQUAL(ret.refType(), RefType::LValue); BOOST_CHECK(ret.isCastable<unsigned>()); BOOST_CHECK_EQUAL(ret.cast<unsigned>(), 10); } { Value ret = (*valueFn)(Value(10u)); BOOST_CHECK_EQUAL(ret.cast<unsigned>(), 20); } } /******************************************************************************/ /* MEMBER FUNCTION */ /******************************************************************************/ struct Foo { Foo() : value(0) {} unsigned& bar(unsigned i) { value += i; return value; } unsigned value; }; reflectClass(Foo) {} BOOST_AUTO_TEST_CASE(memberFn) { Foo foo; auto valueFn = makeValueFunctionSafe(&Foo::bar); { Value ret = (*valueFn)(Value(foo), Value(10u)); BOOST_CHECK_EQUAL(ret.refType(), RefType::LValue); BOOST_CHECK(ret.isCastable<unsigned>()); BOOST_CHECK_EQUAL(ret.cast<unsigned>(), 10); BOOST_CHECK_EQUAL(foo.value, 10); } { Value ret = (*valueFn)(Value(foo), Value(10u)); BOOST_CHECK_EQUAL(ret.cast<unsigned>(), 20); BOOST_CHECK_EQUAL(foo.value, 20); } } /******************************************************************************/ /* CONSTNESS */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(constness) { auto fn = [] (unsigned& i, const unsigned& j) -> const unsigned& { i += j; return i; }; auto valueFn = makeValueFunctionSafe(fn); { unsigned i = 0; Value ret = (*valueFn)(Value(i), Value(10u)); BOOST_CHECK(ret.isConst()); BOOST_CHECK_EQUAL(ret.refType(), RefType::LValue); BOOST_CHECK_EQUAL(i, 10); BOOST_CHECK_EQUAL(&ret.cast<const unsigned>(), &i); } } <|endoftext|>
<commit_before>/* Copyright 2017 Intel Corporation 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 <assert.h> #include <thread> #include <windows.h> #include "CommandLine.hpp" #include "PresentMon.hpp" namespace { enum { HOTKEY_ID = 0x80, WM_STOP_ETW_THREADS = WM_USER + 0, }; HWND g_hWnd = 0; bool g_originalScrollLockEnabled = false; std::thread g_EtwConsumingThread; bool g_StopEtwThreads = true; bool EtwThreadsRunning() { return g_EtwConsumingThread.joinable(); } void StartEtwThreads(CommandLineArgs const& args) { assert(!EtwThreadsRunning()); assert(EtwThreadsShouldQuit()); g_StopEtwThreads = false; g_EtwConsumingThread = std::thread(EtwConsumingThread, args); } void StopEtwThreads(CommandLineArgs* args) { assert(EtwThreadsRunning()); assert(g_StopEtwThreads == false); g_StopEtwThreads = true; g_EtwConsumingThread.join(); args->mRecordingCount++; } BOOL WINAPI ConsoleCtrlHandler( _In_ DWORD dwCtrlType ) { (void) dwCtrlType; PostStopRecording(); PostQuitProcess(); return TRUE; } LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { auto args = (CommandLineArgs*) GetWindowLongPtrW(hWnd, GWLP_USERDATA); switch (uMsg) { case WM_HOTKEY: if (wParam == HOTKEY_ID) { if (EtwThreadsRunning()) { StopEtwThreads(args); } else { StartEtwThreads(*args); } } break; case WM_STOP_ETW_THREADS: if (EtwThreadsRunning()) { StopEtwThreads(args); } break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } HWND CreateMessageQueue(CommandLineArgs& args) { WNDCLASSEXW Class = { sizeof(Class) }; Class.lpfnWndProc = WindowProc; Class.lpszClassName = L"PresentMon"; if (!RegisterClassExW(&Class)) { fprintf(stderr, "error: failed to register hotkey class.\n"); return 0; } HWND hWnd = CreateWindowExW(0, Class.lpszClassName, L"PresentMonWnd", 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, nullptr); if (!hWnd) { fprintf(stderr, "error: failed to create hotkey window.\n"); return 0; } if (args.mHotkeySupport) { if (!RegisterHotKey(hWnd, HOTKEY_ID, args.mHotkeyModifiers, args.mHotkeyVirtualKeyCode)) { fprintf(stderr, "error: failed to register hotkey.\n"); DestroyWindow(hWnd); return 0; } } SetWindowLongPtrW(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(&args)); return hWnd; } bool HaveAdministratorPrivileges() { enum { PRIVILEGE_UNKNOWN, PRIVILEGE_ELEVATED, PRIVILEGE_NOT_ELEVATED, } static privilege = PRIVILEGE_UNKNOWN; if (privilege == PRIVILEGE_UNKNOWN) { typedef BOOL(WINAPI *OpenProcessTokenProc)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); typedef BOOL(WINAPI *GetTokenInformationProc)(HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, DWORD *ReturnLength); HMODULE advapi = LoadLibraryA("advapi32"); if (advapi) { OpenProcessTokenProc OpenProcessToken = (OpenProcessTokenProc)GetProcAddress(advapi, "OpenProcessToken"); GetTokenInformationProc GetTokenInformation = (GetTokenInformationProc)GetProcAddress(advapi, "GetTokenInformation"); if (OpenProcessToken && GetTokenInformation) { HANDLE hToken = NULL; if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { /** BEGIN WORKAROUND: struct TOKEN_ELEVATION and enum value * TokenElevation are not defined in the vs2003 headers, so * we reproduce them here. **/ enum { WA_TokenElevation = 20 }; struct { DWORD TokenIsElevated; } token = {}; /** END WA **/ DWORD dwSize = 0; if (GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) WA_TokenElevation, &token, sizeof(token), &dwSize)) { privilege = token.TokenIsElevated ? PRIVILEGE_ELEVATED : PRIVILEGE_NOT_ELEVATED; } CloseHandle(hToken); } } FreeLibrary(advapi); } } return privilege == PRIVILEGE_ELEVATED; } bool SetPrivilege(HANDLE hToken, LPCSTR lpszPrivilege, bool bEnablePrivilege) { bool bPrivilegeSet = false; typedef BOOL(WINAPI *LookupPrivilegeValueAProc)(LPCSTR lpSystemName, LPCSTR lpName, PLUID lpLuid); typedef BOOL(WINAPI *AdjustTokenPrivilegesProc)(HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength); HMODULE advapi = LoadLibraryA("advapi32"); if (advapi) { LookupPrivilegeValueAProc LookupPrivilegeValueA = (LookupPrivilegeValueAProc)GetProcAddress(advapi, "LookupPrivilegeValueA"); AdjustTokenPrivilegesProc AdjustTokenPrivileges = (AdjustTokenPrivilegesProc)GetProcAddress(advapi, "AdjustTokenPrivileges"); if (LookupPrivilegeValueA && AdjustTokenPrivileges) { LUID luid; if (LookupPrivilegeValueA(NULL, lpszPrivilege, &luid)) { TOKEN_PRIVILEGES tp; tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = bEnablePrivilege ? SE_PRIVILEGE_ENABLED : 0; if (AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL)) { if (GetLastError() != ERROR_NOT_ALL_ASSIGNED) { bPrivilegeSet = true; } else { fprintf(stderr, "error: token does not have the specified privilege.\n"); } } else { fprintf(stderr, "error: failed to adjust token privileges (%u).\n", GetLastError()); } } else { fprintf(stderr, "error: failed to lookup privilege value (%u).\n", GetLastError()); } } FreeLibrary(advapi); } return bPrivilegeSet; } bool AdjustPrivileges() { // DWM processes run under a separate account. // We need permissions to get data about a process owned by another account. bool bPrivilegesSet = false; typedef BOOL(WINAPI *OpenProcessTokenProc)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); HMODULE advapi = LoadLibraryA("advapi32"); if (advapi) { OpenProcessTokenProc OpenProcessToken = (OpenProcessTokenProc)GetProcAddress(advapi, "OpenProcessToken"); if (OpenProcessToken) { HANDLE hToken = NULL; if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) { if (SetPrivilege(hToken, "SeDebugPrivilege", true)) { bPrivilegesSet = true; } else { fprintf(stderr, "error: failed to enable SeDebugPrivilege.\n"); } CloseHandle(hToken); } } FreeLibrary(advapi); } return bPrivilegesSet; } } bool EtwThreadsShouldQuit() { return g_StopEtwThreads; } void PostToggleRecording(CommandLineArgs const& args) { PostMessage(g_hWnd, WM_HOTKEY, HOTKEY_ID, args.mHotkeyModifiers & ~MOD_NOREPEAT); } void PostStopRecording() { PostMessage(g_hWnd, WM_STOP_ETW_THREADS, 0, 0); } void PostQuitProcess() { PostMessage(g_hWnd, WM_QUIT, 0, 0); } int main(int argc, char** argv) { // Parse command line arguments CommandLineArgs args; if (!ParseCommandLine(argc, argv, &args)) { return 1; } // Check required privilege if (!args.mEtlFileName && !HaveAdministratorPrivileges()) { if (args.mTryToElevate) { fprintf(stderr, "warning: process requires administrator privilege; attempting to elevate.\n"); if (!RestartAsAdministrator(argc, argv)) { return 1; } } else { fprintf(stderr, "error: process requires administrator privilege.\n"); } return 2; } // Adjust process privileges for real-time if (!args.mEtlFileName && !AdjustPrivileges()) { fprintf(stderr, "error: process requires special privileges.\n"); } int ret = 0; // Set console title to command line arguments SetConsoleTitle(argc, argv); // If the user wants to use the scroll lock key as an indicator of when // present mon is recording events, make sure it is disabled to start. if (args.mScrollLockIndicator) { g_originalScrollLockEnabled = EnableScrollLock(false); } // Create a message queue to handle WM_HOTKEY, WM_STOP_ETW_THREADS, and // WM_QUIT messages. HWND hWnd = CreateMessageQueue(args); if (hWnd == 0) { ret = 3; goto clean_up; } // Set CTRL handler to capture when the user tries to close the process by // closing the console window or CTRL-C or similar. The handler will // ignore this and instead post WM_QUIT to our message queue. // // We must set g_hWnd before setting the handler. g_hWnd = hWnd; SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); // If the user didn't specify -hotkey, simulate a hotkey press to start the // recording right away. if (!args.mHotkeySupport) { PostToggleRecording(args); } // Enter the main thread message loop. This thread will block waiting for // any messages, which will control the hotkey-toggling and process // shutdown. for (MSG message = {}; GetMessageW(&message, hWnd, 0, 0); ) { TranslateMessage(&message); DispatchMessageW(&message); } // Everything should be shutdown by now. assert(!EtwThreadsRunning()); clean_up: // Restore original scroll lock state if (args.mScrollLockIndicator) { EnableScrollLock(g_originalScrollLockEnabled); } return ret; } <commit_msg>Make not being able to adjust process priveileges a warning instead of an error since it's not fatal. Update comments to make it clear only some versions of Windows are impacted.<commit_after>/* Copyright 2017 Intel Corporation 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 <assert.h> #include <thread> #include <windows.h> #include "CommandLine.hpp" #include "PresentMon.hpp" namespace { enum { HOTKEY_ID = 0x80, WM_STOP_ETW_THREADS = WM_USER + 0, }; HWND g_hWnd = 0; bool g_originalScrollLockEnabled = false; std::thread g_EtwConsumingThread; bool g_StopEtwThreads = true; bool EtwThreadsRunning() { return g_EtwConsumingThread.joinable(); } void StartEtwThreads(CommandLineArgs const& args) { assert(!EtwThreadsRunning()); assert(EtwThreadsShouldQuit()); g_StopEtwThreads = false; g_EtwConsumingThread = std::thread(EtwConsumingThread, args); } void StopEtwThreads(CommandLineArgs* args) { assert(EtwThreadsRunning()); assert(g_StopEtwThreads == false); g_StopEtwThreads = true; g_EtwConsumingThread.join(); args->mRecordingCount++; } BOOL WINAPI ConsoleCtrlHandler( _In_ DWORD dwCtrlType ) { (void) dwCtrlType; PostStopRecording(); PostQuitProcess(); return TRUE; } LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { auto args = (CommandLineArgs*) GetWindowLongPtrW(hWnd, GWLP_USERDATA); switch (uMsg) { case WM_HOTKEY: if (wParam == HOTKEY_ID) { if (EtwThreadsRunning()) { StopEtwThreads(args); } else { StartEtwThreads(*args); } } break; case WM_STOP_ETW_THREADS: if (EtwThreadsRunning()) { StopEtwThreads(args); } break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } HWND CreateMessageQueue(CommandLineArgs& args) { WNDCLASSEXW Class = { sizeof(Class) }; Class.lpfnWndProc = WindowProc; Class.lpszClassName = L"PresentMon"; if (!RegisterClassExW(&Class)) { fprintf(stderr, "error: failed to register hotkey class.\n"); return 0; } HWND hWnd = CreateWindowExW(0, Class.lpszClassName, L"PresentMonWnd", 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, nullptr); if (!hWnd) { fprintf(stderr, "error: failed to create hotkey window.\n"); return 0; } if (args.mHotkeySupport) { if (!RegisterHotKey(hWnd, HOTKEY_ID, args.mHotkeyModifiers, args.mHotkeyVirtualKeyCode)) { fprintf(stderr, "error: failed to register hotkey.\n"); DestroyWindow(hWnd); return 0; } } SetWindowLongPtrW(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(&args)); return hWnd; } bool HaveAdministratorPrivileges() { enum { PRIVILEGE_UNKNOWN, PRIVILEGE_ELEVATED, PRIVILEGE_NOT_ELEVATED, } static privilege = PRIVILEGE_UNKNOWN; if (privilege == PRIVILEGE_UNKNOWN) { typedef BOOL(WINAPI *OpenProcessTokenProc)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); typedef BOOL(WINAPI *GetTokenInformationProc)(HANDLE TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, LPVOID TokenInformation, DWORD TokenInformationLength, DWORD *ReturnLength); HMODULE advapi = LoadLibraryA("advapi32"); if (advapi) { OpenProcessTokenProc OpenProcessToken = (OpenProcessTokenProc)GetProcAddress(advapi, "OpenProcessToken"); GetTokenInformationProc GetTokenInformation = (GetTokenInformationProc)GetProcAddress(advapi, "GetTokenInformation"); if (OpenProcessToken && GetTokenInformation) { HANDLE hToken = NULL; if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { /** BEGIN WORKAROUND: struct TOKEN_ELEVATION and enum value * TokenElevation are not defined in the vs2003 headers, so * we reproduce them here. **/ enum { WA_TokenElevation = 20 }; struct { DWORD TokenIsElevated; } token = {}; /** END WA **/ DWORD dwSize = 0; if (GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) WA_TokenElevation, &token, sizeof(token), &dwSize)) { privilege = token.TokenIsElevated ? PRIVILEGE_ELEVATED : PRIVILEGE_NOT_ELEVATED; } CloseHandle(hToken); } } FreeLibrary(advapi); } } return privilege == PRIVILEGE_ELEVATED; } bool SetPrivilege(HANDLE hToken, LPCSTR lpszPrivilege, bool bEnablePrivilege) { bool bPrivilegeSet = false; typedef BOOL(WINAPI *LookupPrivilegeValueAProc)(LPCSTR lpSystemName, LPCSTR lpName, PLUID lpLuid); typedef BOOL(WINAPI *AdjustTokenPrivilegesProc)(HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength); HMODULE advapi = LoadLibraryA("advapi32"); if (advapi) { LookupPrivilegeValueAProc LookupPrivilegeValueA = (LookupPrivilegeValueAProc)GetProcAddress(advapi, "LookupPrivilegeValueA"); AdjustTokenPrivilegesProc AdjustTokenPrivileges = (AdjustTokenPrivilegesProc)GetProcAddress(advapi, "AdjustTokenPrivileges"); if (LookupPrivilegeValueA && AdjustTokenPrivileges) { LUID luid; if (LookupPrivilegeValueA(NULL, lpszPrivilege, &luid)) { TOKEN_PRIVILEGES tp; tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = bEnablePrivilege ? SE_PRIVILEGE_ENABLED : 0; if (AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL)) { if (GetLastError() != ERROR_NOT_ALL_ASSIGNED) { bPrivilegeSet = true; } else { fprintf(stderr, "error: token does not have the specified privilege.\n"); } } else { fprintf(stderr, "error: failed to adjust token privileges (%u).\n", GetLastError()); } } else { fprintf(stderr, "error: failed to lookup privilege value (%u).\n", GetLastError()); } } FreeLibrary(advapi); } return bPrivilegeSet; } bool AdjustPrivileges() { // On some versions of Windows, DWM processes run under a separate account. // We need permissions to get data about a process owned by another account. bool bPrivilegesSet = false; typedef BOOL(WINAPI *OpenProcessTokenProc)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); HMODULE advapi = LoadLibraryA("advapi32"); if (advapi) { OpenProcessTokenProc OpenProcessToken = (OpenProcessTokenProc)GetProcAddress(advapi, "OpenProcessToken"); if (OpenProcessToken) { HANDLE hToken = NULL; if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) { if (SetPrivilege(hToken, "SeDebugPrivilege", true)) { bPrivilegesSet = true; } else { fprintf(stderr, "error: failed to enable SeDebugPrivilege.\n"); } CloseHandle(hToken); } } FreeLibrary(advapi); } return bPrivilegesSet; } } bool EtwThreadsShouldQuit() { return g_StopEtwThreads; } void PostToggleRecording(CommandLineArgs const& args) { PostMessage(g_hWnd, WM_HOTKEY, HOTKEY_ID, args.mHotkeyModifiers & ~MOD_NOREPEAT); } void PostStopRecording() { PostMessage(g_hWnd, WM_STOP_ETW_THREADS, 0, 0); } void PostQuitProcess() { PostMessage(g_hWnd, WM_QUIT, 0, 0); } int main(int argc, char** argv) { // Parse command line arguments CommandLineArgs args; if (!ParseCommandLine(argc, argv, &args)) { return 1; } // Check required privilege if (!args.mEtlFileName && !HaveAdministratorPrivileges()) { if (args.mTryToElevate) { fprintf(stderr, "warning: process requires administrator privilege; attempting to elevate.\n"); if (!RestartAsAdministrator(argc, argv)) { return 1; } } else { fprintf(stderr, "error: process requires administrator privilege.\n"); } return 2; } // Adjust process privileges for real-time if (!args.mEtlFileName && !AdjustPrivileges()) { fprintf(stderr, "warning: some processes may not show up because we don't have sufficient privileges.\n"); } int ret = 0; // Set console title to command line arguments SetConsoleTitle(argc, argv); // If the user wants to use the scroll lock key as an indicator of when // present mon is recording events, make sure it is disabled to start. if (args.mScrollLockIndicator) { g_originalScrollLockEnabled = EnableScrollLock(false); } // Create a message queue to handle WM_HOTKEY, WM_STOP_ETW_THREADS, and // WM_QUIT messages. HWND hWnd = CreateMessageQueue(args); if (hWnd == 0) { ret = 3; goto clean_up; } // Set CTRL handler to capture when the user tries to close the process by // closing the console window or CTRL-C or similar. The handler will // ignore this and instead post WM_QUIT to our message queue. // // We must set g_hWnd before setting the handler. g_hWnd = hWnd; SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); // If the user didn't specify -hotkey, simulate a hotkey press to start the // recording right away. if (!args.mHotkeySupport) { PostToggleRecording(args); } // Enter the main thread message loop. This thread will block waiting for // any messages, which will control the hotkey-toggling and process // shutdown. for (MSG message = {}; GetMessageW(&message, hWnd, 0, 0); ) { TranslateMessage(&message); DispatchMessageW(&message); } // Everything should be shutdown by now. assert(!EtwThreadsRunning()); clean_up: // Restore original scroll lock state if (args.mScrollLockIndicator) { EnableScrollLock(g_originalScrollLockEnabled); } return ret; } <|endoftext|>
<commit_before>// Copyright (C) 2010, Vaclav Haisman. All rights reserved. // // Redistribution and use in source and binary forms, with or without modifica- // tion, 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 ``AS IS'' AND ANY EXPRESSED 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 // APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- // DING, 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 <log4cplus/version.h> namespace log4cplus { #if ! defined (LOG4CPLUS_VERSION_STR_SUFFIX) #define LOG4CPLUS_VERSION_STR_SUFFIX "-RC5" #endif unsigned const version = LOG4CPLUS_VERSION; char const versionStr[] = LOG4CPLUS_VERSION_STR LOG4CPLUS_VERSION_STR_SUFFIX; } <commit_msg>version.cxx: Remove version suffix.<commit_after>// Copyright (C) 2010, Vaclav Haisman. All rights reserved. // // Redistribution and use in source and binary forms, with or without modifica- // tion, 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 ``AS IS'' AND ANY EXPRESSED 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 // APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- // DING, 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 <log4cplus/version.h> namespace log4cplus { #if ! defined (LOG4CPLUS_VERSION_STR_SUFFIX) #define LOG4CPLUS_VERSION_STR_SUFFIX "" #endif unsigned const version = LOG4CPLUS_VERSION; char const versionStr[] = LOG4CPLUS_VERSION_STR LOG4CPLUS_VERSION_STR_SUFFIX; } <|endoftext|>
<commit_before>/* Copyright (c) 2016-2016, Vasil Dimov 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 <iostream> #include <stdexcept> #include <string> #include <ipfs/client.h> int main(int, char**) { try { ipfs::Client client("localhost", 5001); /** [ipfs::Client::SwarmAddrs] */ ipfs::Json addresses; client.SwarmAddrs(&addresses); std::cout << "Known addresses of each peer:" << std::endl << addresses.dump(2).substr(0, 8192) << std::endl; /* An example output: Known addresses of each peer: { "Addrs": { "QmNRV7kyUxYaQ4KQxFXPYm8EfuzJbtGn1wSFenjXL6LD8y": [ "/ip4/127.0.0.1/tcp/4001", "/ip4/172.17.0.2/tcp/4001", "/ip4/5.9.33.222/tcp/1040", "/ip4/5.9.33.222/tcp/4001", "/ip6/::1/tcp/4001" ], "QmNYXVn17mHCA1cdTh2DF5KmD9RJ72QkJQ6Eo7HyAuMYqG": [ "/ip4/10.12.0.5/tcp/4001", "/ip4/104.131.144.16/tcp/4001", "/ip4/127.0.0.1/tcp/4001", "/ip6/::1/tcp/4001" ], ... } } */ /** [ipfs::Client::SwarmAddrs] */ /* Craft a string like /ip4/127.0.0.1/tcp/4001/ipfs/QmNRV7kyUxYaQ4KQxFXPYm8EfuzJbtGn1wSFenjXL6LD8y from { "Addrs": { "QmNRV7kyUxYaQ4KQxFXPYm8EfuzJbtGn1wSFenjXL6LD8y": [ "/ip4/127.0.0.1/tcp/4001", ... ] } } and also pick up an IPv4 address because the environment where these tests will be run may not support IPv6. */ std::string peer; for (ipfs::Json::iterator it = addresses["Addrs"].begin(); it != addresses["Addrs"].end(); ++it) { const ipfs::Json& addresses = it.value(); for (const std::string& address :addresses) { if (address.substr(0, 5) == "/ip4/") { peer = address + "/ipfs/" + it.key(); break; } } } if (peer.empty()) { throw std::runtime_error("Could not find a peer with IPv4 address."); } std::cout << "Connecting to " << peer << std::endl; /** [ipfs::Client::SwarmConnect] */ /* std::string peer = * "/ip4/104.131.131.81/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ" * for example */ client.SwarmConnect(peer); /** [ipfs::Client::SwarmConnect] */ std::cout << "Connected to " << peer << std::endl; /** [ipfs::Client::SwarmDisconnect] */ /* std::string peer = * "/ip4/104.131.131.81/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ" * for example */ client.SwarmDisconnect(peer); /** [ipfs::Client::SwarmDisconnect] */ std::cout << "Disconnected from " << peer << std::endl; /** [ipfs::Client::SwarmPeers] */ ipfs::Json peers; client.SwarmPeers(&peers); std::cout << "Peers:" << std::endl << peers.dump(2) << std::endl; /* An example output: Peers: { "Strings": [ "/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ", "/ip4/104.131.144.16/tcp/4001/ipfs/QmNYXVn17mHCA1cdTh2DF5KmD9RJ72QkJQ6Eo7HyAuMYqG", "/ip4/104.223.59.174/tcp/4001/ipfs/QmeWdgoZezpdHz1PX8Ly8AeDQahFkBNtHn6qKeNtWP1jB6", ... ] } */ /** [ipfs::Client::SwarmPeers] */ } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; } <commit_msg>Expect swarm connect & disconnect to occasionally fail<commit_after>/* Copyright (c) 2016-2016, Vasil Dimov 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 <iostream> #include <stdexcept> #include <string> #include <ipfs/client.h> int main(int, char**) { try { ipfs::Client client("localhost", 5001); /** [ipfs::Client::SwarmAddrs] */ ipfs::Json addresses; client.SwarmAddrs(&addresses); std::cout << "Known addresses of each peer:" << std::endl << addresses.dump(2).substr(0, 8192) << std::endl; /* An example output: Known addresses of each peer: { "Addrs": { "QmNRV7kyUxYaQ4KQxFXPYm8EfuzJbtGn1wSFenjXL6LD8y": [ "/ip4/127.0.0.1/tcp/4001", "/ip4/172.17.0.2/tcp/4001", "/ip4/5.9.33.222/tcp/1040", "/ip4/5.9.33.222/tcp/4001", "/ip6/::1/tcp/4001" ], "QmNYXVn17mHCA1cdTh2DF5KmD9RJ72QkJQ6Eo7HyAuMYqG": [ "/ip4/10.12.0.5/tcp/4001", "/ip4/104.131.144.16/tcp/4001", "/ip4/127.0.0.1/tcp/4001", "/ip6/::1/tcp/4001" ], ... } } */ /** [ipfs::Client::SwarmAddrs] */ /* Craft a string like /ip4/127.0.0.1/tcp/4001/ipfs/QmNRV7kyUxYaQ4KQxFXPYm8EfuzJbtGn1wSFenjXL6LD8y from { "Addrs": { "QmNRV7kyUxYaQ4KQxFXPYm8EfuzJbtGn1wSFenjXL6LD8y": [ "/ip4/127.0.0.1/tcp/4001", ... ] } } and also pick up an IPv4 address because the environment where these tests will be run may not support IPv6. */ std::string peer; for (ipfs::Json::iterator it = addresses["Addrs"].begin(); it != addresses["Addrs"].end(); ++it) { const ipfs::Json& addresses = it.value(); for (const std::string& address :addresses) { if (address.substr(0, 5) == "/ip4/") { peer = address + "/ipfs/" + it.key(); break; } } } if (peer.empty()) { throw std::runtime_error("Could not find a peer with IPv4 address."); } std::cout << "Connecting to " << peer << std::endl; try { /** [ipfs::Client::SwarmConnect] */ /* std::string peer = * "/ip4/104.131.131.81/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ" * for example */ client.SwarmConnect(peer); /** [ipfs::Client::SwarmConnect] */ std::cout << "Connected to " << peer << std::endl; /** [ipfs::Client::SwarmDisconnect] */ /* std::string peer = * "/ip4/104.131.131.81/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ" * for example */ client.SwarmDisconnect(peer); /** [ipfs::Client::SwarmDisconnect] */ std::cout << "Disconnected from " << peer << std::endl; } catch (const std::exception&) { /* Connect and disconnect occasionally fail due to circumstances beyond * the control of this test. */ } /** [ipfs::Client::SwarmPeers] */ ipfs::Json peers; client.SwarmPeers(&peers); std::cout << "Peers:" << std::endl << peers.dump(2) << std::endl; /* An example output: Peers: { "Strings": [ "/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ", "/ip4/104.131.144.16/tcp/4001/ipfs/QmNYXVn17mHCA1cdTh2DF5KmD9RJ72QkJQ6Eo7HyAuMYqG", "/ip4/104.223.59.174/tcp/4001/ipfs/QmeWdgoZezpdHz1PX8Ly8AeDQahFkBNtHn6qKeNtWP1jB6", ... ] } */ /** [ipfs::Client::SwarmPeers] */ } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include <apf.h> #include <PCU.h> #include <list> #include <set> #include <limits.h> #include "parma_graphDist.h" #include "parma_dijkstra.h" #include "parma_dcpart.h" #include "parma_meshaux.h" #include "parma_convert.h" #include "parma_commons.h" namespace { apf::MeshTag* initTag(apf::Mesh* m, const char* name, int initVal=0, int dim=0) { apf::MeshTag* t = m->createIntTag(name,1); apf::MeshEntity* e; apf::MeshIterator* it = m->begin(dim); while( (e = m->iterate(it)) ) m->setIntTag(e,t,&initVal); m->end(it); return t; } unsigned* getMaxDist(apf::Mesh* m, parma::dcComponents& c, apf::MeshTag* dt) { unsigned* rmax = new unsigned[c.size()]; for(unsigned i=0; i<c.size(); i++) { rmax[i] = 0; apf::MeshEntity* v; c.beginBdry(i); while( (v = c.iterateBdry()) ) { int d; m->getIntTag(v,dt,&d); unsigned du = TO_UINT(d); if( du > rmax[i] ) rmax[i] = du; } c.endBdry(); } return rmax; } void offset(apf::Mesh* m, parma::dcComponents& c, apf::MeshTag* dt, unsigned* rmax) { //If maxDistanceIncrease number of diffusion steps were ran there could be //at most an increase in the distance of maxDistanceIncrease. This can be //seen with the worst case of a mesh of a one element thick rectangle that //has N elements along it's length, where N = 2*maxDistanceIncrease. //Suppose that one element is assigned to part zero and N-1 elements //assigned to part one. Diffusion will only be able to migrate one element //per step from part one to zero. The max distance of part zero increases //by one each step. Thus in maxDistanceIncrease steps the distance can at //most increase by maxDistanceIncrease for a given component. const int maxDistanceIncrease = 1000; if (!c.size()) return; unsigned* rsum = new unsigned[c.size()]; rsum[0] = 0; for(unsigned i=1; i<c.size(); i++) rsum[i] = rsum[i-1] + rmax[i-1] + 1 + maxDistanceIncrease; for(unsigned i=1; i<c.size(); i++) PCU_Debug_Print("offset %u is %u\n", i, rsum[i]); // Go backwards so that the largest bdry vtx changes are made first // and won't be augmented in subsequent bdry traversals. for(unsigned i=c.size()-1; i>0; i--) { apf::MeshEntity* v; c.beginBdry(i); while( (v = c.iterateBdry()) ) { int d; m->getIntTag(v,dt,&d); int rsi = TO_INT(rsum[i]); if(d < rsi) { //not visited d+=rsi; m->setIntTag(v,dt,&d); } } c.endBdry(); } // Offset the interior vertices apf::MeshEntity* v; apf::MeshIterator* it = m->begin(0); while( (v = m->iterate(it)) ) { //skip if if( !c.has(v) ) continue; // not part of a component unsigned id = c.getId(v); //also skip if on a component boundary if( c.bdryHas(id,v) ) continue; int d; m->getIntTag(v,dt,&d); d += TO_INT(rsum[id]); m->setIntTag(v,dt,&d); } m->end(it); delete [] rsum; } class CompContains : public parma::DijkstraContains { public: CompContains(parma::dcComponents& comps, unsigned compid) : c(comps), id(compid) {} ~CompContains() {} // Without the onBdry check some boundary vertices would be excluded from // distancing. When there are multiple boundary and interior vertices // this is generally not a problem, but for cases where the component is a // single element the core vertex could be a boundary vertex that is not // assiged to the component as queried by getId(e). bool has(apf::MeshEntity* e) { bool onBdry = c.bdryHas(id,e); bool inComp = (c.has(e) && c.getId(e) == id); return ( inComp || onBdry ); } bool bdryHas(apf::MeshEntity* e) { return c.bdryHas(id,e); } private: parma::dcComponents& c; unsigned id; }; const char* distanceTagName() { return "parmaDistance"; } apf::MeshTag* createDistTag(apf::Mesh* m) { int initVal = INT_MAX; return initTag(m, distanceTagName(), initVal); } apf::MeshTag* computeDistance(apf::Mesh* m, parma::dcComponents& c) { apf::MeshTag* distT = createDistTag(m); for(unsigned i=0; i<c.size(); i++) { CompContains* contains = new CompContains(c,i); apf::MeshEntity* src = c.getCore(i); parma::dijkstra(m, contains, src, distT); delete contains; } return distT; } bool hasDistance(apf::Mesh* m, apf::MeshTag* dist) { apf::MeshEntity* e; apf::MeshIterator* it = m->begin(0); while( (e = m->iterate(it)) ) { int d; m->getIntTag(e,dist,&d); if( d == INT_MAX ) return false; } m->end(it); return true; } bool hasDistance(apf::Mesh* m) { apf::MeshTag* dist = parma::getDistTag(m); if( dist ) return true; else return false; } inline bool onMdlBdry(apf::Mesh* m, apf::MeshEntity* v) { const int dim = m->getDimension(); apf::ModelEntity* g = m->toModel(v); const int gdim = m->getModelType(g); return gdim < dim; } /** * @brief construct list of part boundary and geometric boundary * vertices to have their distance updated * @remark There are two side effects. Each vertex in the list: * (1) has the distance set to INT_MAX. Any vertices that are not visited * during the walks will have a INT_MAX distance which will bias diffusion * to migrate the bounded cavities before other cavities. */ void getBdryVtx(apf::Mesh* m, apf::MeshTag* dist, parma::DistanceQueue<parma::Less>& pq) { int dmax = INT_MAX; apf::MeshEntity* u; apf::MeshIterator* it = m->begin(0); while( (u = m->iterate(it)) ) { if( !m->isShared(u) && !onMdlBdry(m,u) ) continue; m->setIntTag(u,dist,&dmax); // (1) apf::Adjacent verts; getElmAdjVtx(m,u,verts); APF_ITERATE(apf::Adjacent, verts, v) { if( !m->isShared(*v) && !onMdlBdry(m,*v) ) { int vd; m->getIntTag(*v,dist,&vd); if( vd == INT_MAX ) continue; pq.push(*v,vd); } } } m->end(it); } class CompUpdateContains : public parma::DijkstraContains { public: CompUpdateContains() {} ~CompUpdateContains() {} bool has(apf::MeshEntity*) { return true; } //disable the non-manifold boundary detection mechanism bool bdryHas(apf::MeshEntity*) { return false; } }; apf::MeshTag* updateDistance(apf::Mesh* m) { PCU_Debug_Print("updateDistance\n"); apf::MeshTag* dist = parma::getDistTag(m); parma::DistanceQueue<parma::Less> pq(m); getBdryVtx(m,dist,pq); CompUpdateContains c; parma::dijkstra(m,&c,pq,dist); return dist; } } //end namespace namespace parma_ordering { typedef std::list<apf::MeshEntity*> queue; inline apf::MeshEntity* pop(queue& q) { apf::MeshEntity* e = q.front(); assert(e); q.pop_front(); return e; } int bfs(apf::Mesh* m, parma::DijkstraContains* c, apf::MeshEntity* src, apf::MeshTag* order, int num) { queue q; q.push_back(src); while( !q.empty() ) { apf::MeshEntity* v = pop(q); if( m->hasTag(v,order) ) continue; m->setIntTag(v,order,&num); num++; apf::Adjacent adjVtx; getEdgeAdjVtx(m,v,adjVtx); APF_ITERATE(apf::Adjacent, adjVtx, eItr) { apf::MeshEntity* u = *eItr; if( c->has(u) && ! m->hasTag(u,order) ) q.push_back(u); } } return num; } apf::MeshEntity* getMaxDistSeed(apf::Mesh* m, parma::dcComponents& c, apf::MeshTag* dt, apf::MeshTag* order, unsigned comp) { unsigned rmax = 0; apf::MeshEntity* emax = NULL; apf::MeshEntity* v; c.beginBdry(comp); while( (v = c.iterateBdry()) ) { int d; m->getIntTag(v,dt,&d); unsigned du = TO_UINT(d); // max distance unordered vertex if( du > rmax && !m->hasTag(v,order) ) { rmax = du; emax = v; } } c.endBdry(); return emax; } apf::MeshTag* reorder(apf::Mesh* m, parma::dcComponents& c, apf::MeshTag* dist) { apf::MeshTag* order = m->createIntTag("parma_ordering",1); int start = 0; for(unsigned i=0; i<c.size(); i++) { CompContains* contains = new CompContains(c,i); apf::MeshEntity* src = getMaxDistSeed(m,c,dist,order,i); assert(src); assert(!m->hasTag(src,order)); start = bfs(m, contains, src, order, start); delete contains; } assert(start == TO_INT(m->count(0))); int* sorted = new int[m->count(0)]; for(unsigned i=0; i<m->count(0); i++) sorted[i] = 0; apf::MeshIterator* it = m->begin(0); apf::MeshEntity* e; while( (e = m->iterate(it)) ) { int id; m->getIntTag(e,order,&id); assert(id < TO_INT(m->count(0))); sorted[id] = 1; } m->end(it); for(unsigned i=0; i<m->count(0); i++) assert(sorted[i]); delete [] sorted; return order; } } //end namespace namespace parma { apf::MeshTag* getDistTag(apf::Mesh* m) { return m->findTag(distanceTagName()); } apf::MeshTag* measureGraphDist(apf::Mesh* m) { apf::MeshTag* t = NULL; if( hasDistance(m) ) { t = updateDistance(m); } else { PCU_Debug_Print("computeDistance\n"); dcComponents c = dcComponents(m); t = computeDistance(m,c); if( PCU_Comm_Peers() > 1 && !c.numIso() ) if( !hasDistance(m,t) ) { parmaCommons::error("rank %d comp %u iso %u ... " "some vertices don't have distance computed\n", PCU_Comm_Self(), c.size(), c.numIso()); assert(false); } unsigned* rmax = getMaxDist(m,c,t); offset(m,c,t,rmax); delete [] rmax; } return t; } } apf::MeshTag* Parma_BfsReorder(apf::Mesh* m, int) { double t0 = PCU_Time(); assert( !hasDistance(m) ); parma::dcComponents c = parma::dcComponents(m); apf::MeshTag* dist = computeDistance(m,c); if( PCU_Comm_Peers() > 1 && !c.numIso() ) if( !hasDistance(m,dist) ) { parmaCommons::error("rank %d comp %u iso %u ... " "some vertices don't have distance computed\n", PCU_Comm_Self(), c.size(), c.numIso()); assert(false); } apf::MeshTag* order = parma_ordering::reorder(m,c,dist); m->destroyTag(dist); parmaCommons::printElapsedTime(__func__,PCU_Time()-t0); return order; } <commit_msg>add safety and debug checks<commit_after>#include <apf.h> #include <PCU.h> #include <list> #include <set> #include <limits.h> #include "parma_graphDist.h" #include "parma_dijkstra.h" #include "parma_dcpart.h" #include "parma_meshaux.h" #include "parma_convert.h" #include "parma_commons.h" namespace { apf::MeshTag* initTag(apf::Mesh* m, const char* name, int initVal=0, int dim=0) { apf::MeshTag* t = m->createIntTag(name,1); apf::MeshEntity* e; apf::MeshIterator* it = m->begin(dim); while( (e = m->iterate(it)) ) m->setIntTag(e,t,&initVal); m->end(it); return t; } unsigned* getMaxDist(apf::Mesh* m, parma::dcComponents& c, apf::MeshTag* dt) { unsigned* rmax = new unsigned[c.size()]; for(unsigned i=0; i<c.size(); i++) { rmax[i] = 0; apf::MeshEntity* v; c.beginBdry(i); while( (v = c.iterateBdry()) ) { int d; m->getIntTag(v,dt,&d); unsigned du = TO_UINT(d); if( du > rmax[i] ) rmax[i] = du; } c.endBdry(); } return rmax; } void offset(apf::Mesh* m, parma::dcComponents& c, apf::MeshTag* dt, unsigned* rmax) { //If maxDistanceIncrease number of diffusion steps were ran there could be //at most an increase in the distance of maxDistanceIncrease. This can be //seen with the worst case of a mesh of a one element thick rectangle that //has N elements along it's length, where N = 2*maxDistanceIncrease. //Suppose that one element is assigned to part zero and N-1 elements //assigned to part one. Diffusion will only be able to migrate one element //per step from part one to zero. The max distance of part zero increases //by one each step. Thus in maxDistanceIncrease steps the distance can at //most increase by maxDistanceIncrease for a given component. const int maxDistanceIncrease = 1000; if (!c.size()) return; unsigned* rsum = new unsigned[c.size()]; rsum[0] = 0; for(unsigned i=1; i<c.size(); i++) rsum[i] = rsum[i-1] + rmax[i-1] + 1 + maxDistanceIncrease; for(unsigned i=1; i<c.size(); i++) PCU_Debug_Print("offset %u is %u\n", i, rsum[i]); // Go backwards so that the largest bdry vtx changes are made first // and won't be augmented in subsequent bdry traversals. for(unsigned i=c.size()-1; i>0; i--) { apf::MeshEntity* v; c.beginBdry(i); while( (v = c.iterateBdry()) ) { int d; m->getIntTag(v,dt,&d); int rsi = TO_INT(rsum[i]); if(d < rsi) { //not visited d+=rsi; m->setIntTag(v,dt,&d); } } c.endBdry(); } // Offset the interior vertices apf::MeshEntity* v; apf::MeshIterator* it = m->begin(0); while( (v = m->iterate(it)) ) { //skip if if( !c.has(v) ) continue; // not part of a component unsigned id = c.getId(v); //also skip if on a component boundary if( c.bdryHas(id,v) ) continue; int d; m->getIntTag(v,dt,&d); d += TO_INT(rsum[id]); m->setIntTag(v,dt,&d); } m->end(it); delete [] rsum; } class CompContains : public parma::DijkstraContains { public: CompContains(parma::dcComponents& comps, unsigned compid) : c(comps), id(compid) {} ~CompContains() {} // Without the onBdry check some boundary vertices would be excluded from // distancing. When there are multiple boundary and interior vertices // this is generally not a problem, but for cases where the component is a // single element the core vertex could be a boundary vertex that is not // assiged to the component as queried by getId(e). bool has(apf::MeshEntity* e) { bool onBdry = c.bdryHas(id,e); bool inComp = (c.has(e) && c.getId(e) == id); return ( inComp || onBdry ); } bool bdryHas(apf::MeshEntity* e) { return c.bdryHas(id,e); } private: parma::dcComponents& c; unsigned id; }; const char* distanceTagName() { return "parmaDistance"; } apf::MeshTag* createDistTag(apf::Mesh* m) { int initVal = INT_MAX; return initTag(m, distanceTagName(), initVal); } apf::MeshTag* computeDistance(apf::Mesh* m, parma::dcComponents& c) { apf::MeshTag* distT = createDistTag(m); for(unsigned i=0; i<c.size(); i++) { CompContains* contains = new CompContains(c,i); apf::MeshEntity* src = c.getCore(i); parma::dijkstra(m, contains, src, distT); delete contains; } return distT; } bool hasDistance(apf::Mesh* m, apf::MeshTag* dist) { apf::MeshEntity* e; apf::MeshIterator* it = m->begin(0); while( (e = m->iterate(it)) ) { int d; m->getIntTag(e,dist,&d); if( d == INT_MAX ) return false; } m->end(it); return true; } bool hasDistance(apf::Mesh* m) { apf::MeshTag* dist = parma::getDistTag(m); if( dist ) return true; else return false; } inline bool onMdlBdry(apf::Mesh* m, apf::MeshEntity* v) { const int dim = m->getDimension(); apf::ModelEntity* g = m->toModel(v); const int gdim = m->getModelType(g); return gdim < dim; } /** * @brief construct list of part boundary and geometric boundary * vertices to have their distance updated * @remark There are two side effects. Each vertex in the list: * (1) has the distance set to INT_MAX. Any vertices that are not visited * during the walks will have a INT_MAX distance which will bias diffusion * to migrate the bounded cavities before other cavities. */ void getBdryVtx(apf::Mesh* m, apf::MeshTag* dist, parma::DistanceQueue<parma::Less>& pq) { int dmax = INT_MAX; apf::MeshEntity* u; apf::MeshIterator* it = m->begin(0); while( (u = m->iterate(it)) ) { if( !m->isShared(u) && !onMdlBdry(m,u) ) continue; m->setIntTag(u,dist,&dmax); // (1) apf::Adjacent verts; getElmAdjVtx(m,u,verts); APF_ITERATE(apf::Adjacent, verts, v) { if( !m->isShared(*v) && !onMdlBdry(m,*v) ) { int vd; m->getIntTag(*v,dist,&vd); if( vd == INT_MAX ) continue; pq.push(*v,vd); } } } m->end(it); } class CompUpdateContains : public parma::DijkstraContains { public: CompUpdateContains() {} ~CompUpdateContains() {} bool has(apf::MeshEntity*) { return true; } //disable the non-manifold boundary detection mechanism bool bdryHas(apf::MeshEntity*) { return false; } }; apf::MeshTag* updateDistance(apf::Mesh* m) { PCU_Debug_Print("updateDistance\n"); apf::MeshTag* dist = parma::getDistTag(m); parma::DistanceQueue<parma::Less> pq(m); getBdryVtx(m,dist,pq); CompUpdateContains c; parma::dijkstra(m,&c,pq,dist); return dist; } } //end namespace namespace parma_ordering { typedef std::list<apf::MeshEntity*> queue; inline apf::MeshEntity* pop(queue& q) { apf::MeshEntity* e = q.front(); assert(e); q.pop_front(); return e; } int bfs(apf::Mesh* m, parma::DijkstraContains* c, apf::MeshEntity* src, apf::MeshTag* order, int num) { queue q; q.push_back(src); while( !q.empty() ) { apf::MeshEntity* v = pop(q); if( m->hasTag(v,order) ) continue; m->setIntTag(v,order,&num); num++; apf::Adjacent adjVtx; getEdgeAdjVtx(m,v,adjVtx); APF_ITERATE(apf::Adjacent, adjVtx, eItr) { apf::MeshEntity* u = *eItr; if( c->has(u) && ! m->hasTag(u,order) ) q.push_back(u); } } return num; } apf::MeshEntity* getMaxDistSeed(apf::Mesh* m, parma::dcComponents& c, apf::MeshTag* dt, apf::MeshTag* order, unsigned comp) { unsigned rmax = 0; apf::MeshEntity* emax = NULL; apf::MeshEntity* v; int cnt=0; c.beginBdry(comp); while( (v = c.iterateBdry()) ) { cnt++; int d; m->getIntTag(v,dt,&d); unsigned du = TO_UINT(d); // max distance unordered vertex if( du > rmax && !m->hasTag(v,order) ) { rmax = du; emax = v; } } c.endBdry(); if( !emax ) { parmaCommons::error("%s comp %u no src vtx found bdry cnt %d\n", __func__, comp, cnt); } return emax; } apf::MeshTag* reorder(apf::Mesh* m, parma::dcComponents& c, apf::MeshTag* dist) { apf::MeshTag* order = m->createIntTag("parma_ordering",1); int start = 0; for(unsigned i=0; i<c.size(); i++) { CompContains* contains = new CompContains(c,i); apf::MeshEntity* src = getMaxDistSeed(m,c,dist,order,i); assert(src); assert(!m->hasTag(src,order)); start = bfs(m, contains, src, order, start); if(start == TO_INT(m->count(0))) { if( i != c.size()-1 ) parmaCommons::status("%d all vertices visited comp %u of %u\n", PCU_Comm_Self(), i, c.size()); break; } delete contains; } assert(start == TO_INT(m->count(0))); int* sorted = new int[m->count(0)]; for(unsigned i=0; i<m->count(0); i++) sorted[i] = 0; apf::MeshIterator* it = m->begin(0); apf::MeshEntity* e; while( (e = m->iterate(it)) ) { int id; m->getIntTag(e,order,&id); assert(id < TO_INT(m->count(0))); sorted[id] = 1; } m->end(it); for(unsigned i=0; i<m->count(0); i++) assert(sorted[i]); delete [] sorted; return order; } } //end namespace namespace parma { apf::MeshTag* getDistTag(apf::Mesh* m) { return m->findTag(distanceTagName()); } apf::MeshTag* measureGraphDist(apf::Mesh* m) { apf::MeshTag* t = NULL; if( hasDistance(m) ) { t = updateDistance(m); } else { PCU_Debug_Print("computeDistance\n"); dcComponents c = dcComponents(m); t = computeDistance(m,c); if( PCU_Comm_Peers() > 1 && !c.numIso() ) if( !hasDistance(m,t) ) { parmaCommons::error("rank %d comp %u iso %u ... " "some vertices don't have distance computed\n", PCU_Comm_Self(), c.size(), c.numIso()); assert(false); } unsigned* rmax = getMaxDist(m,c,t); offset(m,c,t,rmax); delete [] rmax; } return t; } } apf::MeshTag* Parma_BfsReorder(apf::Mesh* m, int) { double t0 = PCU_Time(); assert( !hasDistance(m) ); parma::dcComponents c = parma::dcComponents(m); apf::MeshTag* dist = computeDistance(m,c); if( PCU_Comm_Peers() > 1 && !c.numIso() ) if( !hasDistance(m,dist) ) { parmaCommons::error("rank %d comp %u iso %u ... " "some vertices don't have distance computed\n", PCU_Comm_Self(), c.size(), c.numIso()); assert(false); } apf::MeshTag* order = parma_ordering::reorder(m,c,dist); m->destroyTag(dist); parmaCommons::printElapsedTime(__func__,PCU_Time()-t0); return order; } <|endoftext|>
<commit_before>// Part of ssig -- Copyright (c) Christian Neumüller 2012--2013 // This file is subject to the terms of the BSD 2-Clause License. // See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause #include "ssig.hpp" #define BOOST_TEST_MODULE SsigTest #include <boost/test/unit_test.hpp> using namespace ssig; // Don't do this at home. BOOST_AUTO_TEST_SUITE(nullary_signals) namespace { unsigned g_numFooCalls = 0; unsigned long foo() { return ++g_numFooCalls; } void discard_test() { std::function<void()> f([](){ foo(); }); } void prepare() { g_numFooCalls = 0; } template<typename R> void checkNullaryFooConnection(Connection<R()>& c, Signal<R()>& s) { BOOST_CHECK(c.isConnected()); bool lambdaCalled = false; prepare(); Connection<R()> cl = s.connect([&lambdaCalled]()->R{ lambdaCalled = true; return R(); }); BOOST_CHECK(!s.empty()); BOOST_CHECK(c.isConnected()); unsigned numFooCalls = c.invokeSlot(); BOOST_CHECK_EQUAL(numFooCalls, 1); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(!lambdaCalled); numFooCalls = s(); BOOST_CHECK_EQUAL(numFooCalls, 2); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(lambdaCalled); cl.disconnect(); c.disconnect(); BOOST_CHECK(s.empty()); BOOST_CHECK_THROW(c.disconnect(), SsigError); } } BOOST_AUTO_TEST_CASE(signal_construction) { { Signal<double()> s; BOOST_CHECK(s.empty()); } { Signal<void()> s; BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_CASE(connecting_and_invoking_void) { unsigned test = 2; Signal<void()> s; s(); // void return type: should not throw s.connect([&test](){test += 4;}); BOOST_CHECK(!s.empty()); s.connect([&test](){test /= 2;}); s(); BOOST_CHECK_EQUAL(test, 2 / 2 + 4); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_basic) { prepare(); Signal<unsigned long()> s; s.connect(&foo); BOOST_CHECK(!s.empty()); s.connect(&foo); unsigned const numFooCalls = s(); BOOST_CHECK_EQUAL(numFooCalls, 2); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_illegal) { Signal<double()> s; BOOST_CHECK_THROW(s(), SsigError); } BOOST_AUTO_TEST_CASE(connection) { { Signal<short()> s; Connection<short()> c = s.connect(&foo); Connection<short()> c2 = c; Connection<short()> c3 = c2; c2.disconnect(); BOOST_CHECK(!c2.isConnected()); BOOST_CHECK(!c.isConnected()); BOOST_CHECK(!c3.isConnected()); BOOST_CHECK(s.empty()); Connection<short()> c4 = s.connect(&foo); checkNullaryFooConnection(c4, s); } { Signal<wchar_t()> s; Connection<wchar_t()> c(s, &foo); checkNullaryFooConnection(c, s); } } BOOST_AUTO_TEST_CASE(scoped_connection) { Signal<short()> s; { ScopedConnection<short()> c = s.connect(&foo); checkNullaryFooConnection(c, s); } BOOST_CHECK(s.empty()); { ScopedConnection<short()> c = s.connect(&foo); c.disconnect(); BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(unary_signals) namespace { unsigned g_numFooCalls = 0; unsigned long foo(int i) { return ++g_numFooCalls + i; } void prepare() { g_numFooCalls = 0; } template<typename R, typename A> void checkUnaryFooConnection(Connection<R(A)>& c, Signal<R(A)>& s) { static const A arg = 4; bool lambdaCalled = false; prepare(); Connection<R(A)> cl = s.connect([&lambdaCalled](A)->R{ lambdaCalled = true; return R(); }); BOOST_CHECK(!s.empty()); BOOST_CHECK(c.isConnected()); unsigned numFooCalls = c.invokeSlot(arg) - arg; BOOST_CHECK_EQUAL(numFooCalls, 1); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(!lambdaCalled); numFooCalls = s(arg) - arg; BOOST_CHECK_EQUAL(numFooCalls, 2); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(lambdaCalled); cl.disconnect(); c.disconnect(); BOOST_CHECK(s.empty()); BOOST_CHECK_THROW(c.disconnect(), SsigError); } } BOOST_AUTO_TEST_CASE(signal_construction_un) { { Signal<double(float)> s; BOOST_CHECK(s.empty()); } { Signal<void(int)> s; BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_CASE(connecting_and_invoking_void_un) { double test = 16; Signal<void(int)> s; s.connect([&test](int arg){test += 4 + arg;}); BOOST_CHECK(!s.empty()); s.connect([&test](int arg){test /= (2 + arg);}); static const int arg = 2; s(arg); BOOST_CHECK_EQUAL(test, 16 / (2 + arg) + (4 + arg)); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_basic_un) { prepare(); Signal<unsigned long(short)> s; s.connect(&foo); BOOST_CHECK(!s.empty()); s.connect(&foo); static const unsigned arg = 3; unsigned const numFooCalls = s(arg) - arg; BOOST_CHECK_EQUAL(numFooCalls, 2); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_illegal_un) { Signal<double(std::logic_error)> s; BOOST_CHECK_THROW(s(std::logic_error("")), SsigError); } static bool disconnect_arg(ConnectionBase* c) { c->disconnect(); return false; } static bool nop(ConnectionBase*) { return true; } BOOST_AUTO_TEST_CASE(disconnect_while_called) { Signal<bool(ConnectionBase*)> s; { auto c = s.connect(&disconnect_arg); s(&c); BOOST_CHECK(!c.isConnected()); BOOST_CHECK(s.empty()); } { ScopedConnection<bool(ConnectionBase*)> c1 = s.connect(&nop); auto c = s.connect(&disconnect_arg); ScopedConnection<bool(ConnectionBase*)> c2 = s.connect(&nop); s(&c); BOOST_CHECK(!c.isConnected()); } BOOST_CHECK(s.empty()); } BOOST_AUTO_TEST_CASE(disconnect_next_called) { Signal<bool(ConnectionBase*)> s; { auto c = s.connect(&nop); ScopedConnection<bool(ConnectionBase*)> c1 = s.connect(&disconnect_arg); BOOST_CHECK_EQUAL(s(&c), false); BOOST_CHECK(!c.isConnected()); } BOOST_CHECK(s.empty()); } static void checkList(std::forward_list<int> l) { BOOST_CHECK(!l.empty()); } BOOST_AUTO_TEST_CASE(move_vulnerability) { Signal<void(std::forward_list<int>)> s; s.connect(&checkList); s.connect(&checkList); std::forward_list<int> l(1); s(l); } BOOST_AUTO_TEST_CASE(connection_un) { { Signal<short(int)> s; Connection<short(int)> c = s.connect(&foo); checkUnaryFooConnection(c, s); } { Signal<wchar_t(short)> s; Connection<wchar_t(short)> c(s, &foo); checkUnaryFooConnection(c, s); } } BOOST_AUTO_TEST_CASE(scoped_connection_un) { Signal<short(long)> s; { ScopedConnection<short(long)> c = s.connect(&foo); checkUnaryFooConnection(c, s); } BOOST_CHECK(s.empty()); { ScopedConnection<short(long)> c = s.connect(&foo); c.disconnect(); BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(binary_signals) namespace { unsigned g_numFooCalls = 0; unsigned long foo(int i, int j) { return ++g_numFooCalls + i - j; } void prepare() { g_numFooCalls = 0; } template<typename R, typename A1, typename A2> void checkBinaryFooConnection(Connection<R(A1, A2)>& c, Signal<R(A1, A2)>& s) { static const A1 arg = 4; bool lambdaCalled = false; prepare(); Connection<R(A1, A2)> cl = s.connect([&lambdaCalled](A1, A2)->R{ lambdaCalled = true; return R(); }); BOOST_CHECK(!s.empty()); BOOST_CHECK(c.isConnected()); unsigned numFooCalls = c.invokeSlot(arg, arg); BOOST_CHECK_EQUAL(numFooCalls, 1); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(!lambdaCalled); numFooCalls = s(arg, arg); BOOST_CHECK_EQUAL(numFooCalls, 2); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(lambdaCalled); cl.disconnect(); c.disconnect(); BOOST_CHECK(s.empty()); BOOST_CHECK_THROW(c.disconnect(), SsigError); } } BOOST_AUTO_TEST_CASE(signal_construction_bin) { { Signal<double(float, wchar_t)> s; BOOST_CHECK(s.empty()); } { Signal<void(int, std::div_t)> s; BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_CASE(connecting_and_invoking_void_bin) { double test = 16; Signal<void(int, int)> s; s.connect([&test](int arg, int arg2){test += 4 + arg - arg2;}); BOOST_CHECK(!s.empty()); s.connect([&test](int arg, int arg2){test /= (2 + arg - arg2);}); static const int arg = 2; s(arg, arg); BOOST_CHECK_EQUAL(test, 16 / 2 + 4); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_basic_bin) { prepare(); Signal<unsigned long(short, int)> s; s.connect(&foo); BOOST_CHECK(!s.empty()); s.connect(&foo); static const int arg = 3; unsigned const numFooCalls = s(arg, -arg) - 2 * arg; BOOST_CHECK_EQUAL(numFooCalls, 2); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_illegal_un) { Signal<double(std::logic_error, void*)> s; BOOST_CHECK_THROW(s(std::logic_error(""), nullptr), SsigError); } BOOST_AUTO_TEST_CASE(connection_bin) { { Signal<short(int, int)> s; Connection<short(int, int)> c = s.connect(&foo); checkBinaryFooConnection(c, s); } { Signal<wchar_t(short, short)> s; Connection<wchar_t(short, short)> c(s, &foo); checkBinaryFooConnection(c, s); } } BOOST_AUTO_TEST_CASE(scoped_connection_bin) { struct Foo { int f(bool){return int();} }; typedef int (Foo::*fn)(bool); Signal<short(long, long)> s; { ScopedConnection<short(long, long)> c = s.connect(&foo); checkBinaryFooConnection(c, s); } BOOST_CHECK(s.empty()); { ScopedConnection<short(long, long)> c = s.connect(&foo); c.disconnect(); BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>test: Fix warnings.<commit_after>// Part of ssig -- Copyright (c) Christian Neumüller 2012--2013 // This file is subject to the terms of the BSD 2-Clause License. // See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause #include "ssig.hpp" #define BOOST_TEST_MODULE SsigTest #include <boost/test/unit_test.hpp> using namespace ssig; // Don't do this at home. BOOST_AUTO_TEST_SUITE(nullary_signals) namespace { unsigned g_numFooCalls = 0; unsigned foo() { return ++g_numFooCalls; } void discard_test() { std::function<void()> f([](){ foo(); }); } void prepare() { g_numFooCalls = 0; } template<typename R> void checkNullaryFooConnection(Connection<R()>& c, Signal<R()>& s) { BOOST_CHECK(c.isConnected()); bool lambdaCalled = false; prepare(); Connection<R()> cl = s.connect([&lambdaCalled]()->R{ lambdaCalled = true; return R(); }); BOOST_CHECK(!s.empty()); BOOST_CHECK(c.isConnected()); unsigned numFooCalls = c.invokeSlot(); BOOST_CHECK_EQUAL(numFooCalls, 1u); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(!lambdaCalled); numFooCalls = s(); BOOST_CHECK_EQUAL(numFooCalls, 2u); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(lambdaCalled); cl.disconnect(); c.disconnect(); BOOST_CHECK(s.empty()); BOOST_CHECK_THROW(c.disconnect(), SsigError); } } BOOST_AUTO_TEST_CASE(signal_construction) { { Signal<double()> s; BOOST_CHECK(s.empty()); } { Signal<void()> s; BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_CASE(connecting_and_invoking_void) { unsigned test = 2; Signal<void()> s; s(); // void return type: should not throw s.connect([&test](){test += 4;}); BOOST_CHECK(!s.empty()); s.connect([&test](){test /= 2;}); s(); BOOST_CHECK_EQUAL(test, 2u / 2u + 4u); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_basic) { prepare(); Signal<unsigned long()> s; s.connect(&foo); BOOST_CHECK(!s.empty()); s.connect(&foo); unsigned const numFooCalls = s(); BOOST_CHECK_EQUAL(numFooCalls, 2u); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_illegal) { Signal<double()> s; BOOST_CHECK_THROW(s(), SsigError); } BOOST_AUTO_TEST_CASE(connection) { { Signal<unsigned long()> s; Connection<unsigned long()> c = s.connect(&foo); Connection<unsigned long()> c2 = c; Connection<unsigned long()> c3 = c2; c2.disconnect(); BOOST_CHECK(!c2.isConnected()); BOOST_CHECK(!c.isConnected()); BOOST_CHECK(!c3.isConnected()); BOOST_CHECK(s.empty()); Connection<unsigned long()> c4 = s.connect(&foo); checkNullaryFooConnection(c4, s); } { Signal<unsigned long()> s; Connection<unsigned long()> c(s, &foo); checkNullaryFooConnection(c, s); } } BOOST_AUTO_TEST_CASE(scoped_connection) { Signal<unsigned long()> s; { ScopedConnection<unsigned long()> c = s.connect(&foo); checkNullaryFooConnection(c, s); } BOOST_CHECK(s.empty()); { ScopedConnection<unsigned long()> c = s.connect(&foo); c.disconnect(); BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(unary_signals) namespace { unsigned g_numFooCalls = 0; unsigned long foo(int i) { return ++g_numFooCalls + i; } void prepare() { g_numFooCalls = 0; } template<typename R, typename A> void checkUnaryFooConnection(Connection<R(A)>& c, Signal<R(A)>& s) { static const A arg = 4; bool lambdaCalled = false; prepare(); Connection<R(A)> cl = s.connect([&lambdaCalled](A)->R{ lambdaCalled = true; return R(); }); BOOST_CHECK(!s.empty()); BOOST_CHECK(c.isConnected()); unsigned numFooCalls = c.invokeSlot(arg) - arg; BOOST_CHECK_EQUAL(numFooCalls, 1u); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(!lambdaCalled); numFooCalls = s(arg) - arg; BOOST_CHECK_EQUAL(numFooCalls, 2u); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(lambdaCalled); cl.disconnect(); c.disconnect(); BOOST_CHECK(s.empty()); BOOST_CHECK_THROW(c.disconnect(), SsigError); } } BOOST_AUTO_TEST_CASE(signal_construction_un) { { Signal<double(float)> s; BOOST_CHECK(s.empty()); } { Signal<void(int)> s; BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_CASE(connecting_and_invoking_void_un) { double test = 16; Signal<void(int)> s; s.connect([&test](int arg){test += 4 + arg;}); BOOST_CHECK(!s.empty()); s.connect([&test](int arg){test /= (2 + arg);}); static const int arg = 2; s(arg); BOOST_CHECK_EQUAL(test, static_cast<double>(16 / (2 + arg) + (4 + arg))); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_basic_un) { prepare(); Signal<unsigned long(short)> s; s.connect(&foo); BOOST_CHECK(!s.empty()); s.connect(&foo); static const short arg = 3; unsigned const numFooCalls = s(arg) - arg; BOOST_CHECK_EQUAL(numFooCalls, 2u); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_illegal_un) { Signal<double(std::logic_error)> s; BOOST_CHECK_THROW(s(std::logic_error("")), SsigError); } static bool disconnect_arg(ConnectionBase* c) { c->disconnect(); return false; } static bool nop(ConnectionBase*) { return true; } BOOST_AUTO_TEST_CASE(disconnect_while_called) { Signal<bool(ConnectionBase*)> s; { auto c = s.connect(&disconnect_arg); s(&c); BOOST_CHECK(!c.isConnected()); BOOST_CHECK(s.empty()); } { ScopedConnection<bool(ConnectionBase*)> c1 = s.connect(&nop); auto c = s.connect(&disconnect_arg); ScopedConnection<bool(ConnectionBase*)> c2 = s.connect(&nop); s(&c); BOOST_CHECK(!c.isConnected()); } BOOST_CHECK(s.empty()); } BOOST_AUTO_TEST_CASE(disconnect_next_called) { Signal<bool(ConnectionBase*)> s; { auto c = s.connect(&nop); ScopedConnection<bool(ConnectionBase*)> c1 = s.connect(&disconnect_arg); BOOST_CHECK_EQUAL(s(&c), false); BOOST_CHECK(!c.isConnected()); } BOOST_CHECK(s.empty()); } static void checkList(std::forward_list<int> l) { BOOST_CHECK(!l.empty()); } BOOST_AUTO_TEST_CASE(move_vulnerability) { Signal<void(std::forward_list<int>)> s; s.connect(&checkList); s.connect(&checkList); std::forward_list<int> l(1); s(l); } BOOST_AUTO_TEST_CASE(connection_un) { { Signal<unsigned(int)> s; Connection<unsigned(int)> c = s.connect(&foo); checkUnaryFooConnection(c, s); } { Signal<unsigned(short)> s; Connection<unsigned(short)> c(s, &foo); checkUnaryFooConnection(c, s); } } BOOST_AUTO_TEST_CASE(scoped_connection_un) { Signal<unsigned(long)> s; { ScopedConnection<unsigned(long)> c = s.connect(&foo); checkUnaryFooConnection(c, s); } BOOST_CHECK(s.empty()); { ScopedConnection<unsigned(long)> c = s.connect(&foo); c.disconnect(); BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(binary_signals) namespace { unsigned g_numFooCalls = 0; unsigned long foo(int i, int j) { return ++g_numFooCalls + i - j; } void prepare() { g_numFooCalls = 0; } template<typename R, typename A1, typename A2> void checkBinaryFooConnection(Connection<R(A1, A2)>& c, Signal<R(A1, A2)>& s) { static const A1 arg = 4; bool lambdaCalled = false; prepare(); Connection<R(A1, A2)> cl = s.connect([&lambdaCalled](A1, A2)->R{ lambdaCalled = true; return R(); }); BOOST_CHECK(!s.empty()); BOOST_CHECK(c.isConnected()); unsigned long long numFooCalls = c.invokeSlot(arg, arg); BOOST_CHECK_EQUAL(numFooCalls, 1); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(!lambdaCalled); numFooCalls = s(arg, arg); BOOST_CHECK_EQUAL(numFooCalls, 2); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); BOOST_CHECK(lambdaCalled); cl.disconnect(); c.disconnect(); BOOST_CHECK(s.empty()); BOOST_CHECK_THROW(c.disconnect(), SsigError); } } BOOST_AUTO_TEST_CASE(signal_construction_bin) { { Signal<double(float, wchar_t)> s; BOOST_CHECK(s.empty()); } { Signal<void(int, std::div_t)> s; BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_CASE(connecting_and_invoking_void_bin) { double test = 16; Signal<void(int, int)> s; s.connect([&test](int arg, int arg2){test += 4 + arg - arg2;}); BOOST_CHECK(!s.empty()); s.connect([&test](int arg, int arg2){test /= (2 + arg - arg2);}); static const int arg = 2; s(arg, arg); BOOST_CHECK_EQUAL(test, 16 / 2 + 4); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_basic_bin) { prepare(); Signal<unsigned long(short, int)> s; s.connect(&foo); BOOST_CHECK(!s.empty()); s.connect(&foo); static const short arg = 3; unsigned const numFooCalls = s(arg, -arg) - 2 * arg; BOOST_CHECK_EQUAL(numFooCalls, 2u); BOOST_CHECK_EQUAL(numFooCalls, g_numFooCalls); } BOOST_AUTO_TEST_CASE(connecting_and_invoking_illegal_un) { Signal<double(std::logic_error, int)> s; BOOST_CHECK_THROW(s(std::logic_error(""), 0), SsigError); } BOOST_AUTO_TEST_CASE(connection_bin) { { Signal<unsigned long long (int, int)> s; Connection<unsigned long long (int, int)> c = s.connect(&foo); checkBinaryFooConnection(c, s); } { Signal<unsigned(short, short)> s; Connection<unsigned(short, short)> c(s, &foo); checkBinaryFooConnection(c, s); } } BOOST_AUTO_TEST_CASE(scoped_connection_bin) { struct Foo { int f(bool){return int();} }; typedef int (Foo::*fn)(bool); Signal<unsigned(long, long)> s; { ScopedConnection<unsigned(long, long)> c = s.connect(&foo); checkBinaryFooConnection(c, s); } BOOST_CHECK(s.empty()); { ScopedConnection<unsigned(long, long)> c = s.connect(&foo); c.disconnect(); BOOST_CHECK(s.empty()); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "cute.h" #include "ide_listener.h" #include "xml_listener.h" #include "cute_runner.h" #include "indexableSet.h" void testIndexableSetAccess() { IndexableSet<char> is{'b', 'e', 'e', 'r'}; ASSERT_EQUAL(3, is.size()); ASSERT_EQUAL('b', is[0]); ASSERT_EQUAL('e', is[1]); ASSERT_EQUAL('r', is[2]); } void testEmptyIndexableSet() { IndexableSet<int> is{}; ASSERT_EQUAL(0, is.size()); ASSERT(is.empty()); } void testIndexableSetInsert(){ IndexableSet<int> is{}; ASSERT_EQUAL(0,is.size()); is.insert(42); ASSERT_EQUAL(1,is.size()); ASSERT_EQUAL(42,is[0]); ASSERT_THROWS(is[1],std::out_of_range); } void testIndexableSetFrontBack() { IndexableSet<int> is{88, -10, 23, 6}; ASSERT_EQUAL(4, is.size()); ASSERT_EQUAL(-10, is.front()); ASSERT_EQUAL(88, is.back()); } void testIndexableSetNegativeIndexAccessFromBack() { IndexableSet<char> is{'b', 'e', 'e', 'r'}; ASSERT_EQUAL('r', is.at(-1)); ASSERT_EQUAL('e', is.at(-2)); ASSERT_EQUAL('b', is.at(-3)); } void testIndexableSetOverflowCapture() { IndexableSet<int> is{1, 2, 3, 4}; ASSERT_THROWS(is.at(4), std::out_of_range); ASSERT_THROWS(is.at(-5), std::out_of_range); IndexableSet<char> is2{}; ASSERT_THROWS(is2.at(0), std::out_of_range); ASSERT_THROWS(is2.at(-1), std::out_of_range); } void testIndexableSetCaselessCompare() { struct caselessCompare { bool operator ()(const std::string & left, const std::string & right) { return std::lexicographical_compare( left.begin(), left.end(), right.begin(), right.end(), [](const char l, const char r){ return std::tolower(l) < std::tolower(r); }); } }; IndexableSet<std::string,caselessCompare> cl_is {"H", "i", "I", "h"}; ASSERT_EQUAL(2, cl_is.size()); ASSERT_EQUAL("H", cl_is[0]); ASSERT_EQUAL("i", cl_is[1]); IndexableSet<std::string> is {"H", "i", "I", "h"}; ASSERT_EQUAL(4, is.size()); ASSERT_EQUAL("H", is[0]); ASSERT_EQUAL("I", is[1]); ASSERT_EQUAL("h", is[2]); ASSERT_EQUAL("i", is[3]); } void testRangeConstructor(){ const std::string str{"glass"}; IndexableSet<char> is(str.begin(), str.end()); std::string t(is.begin(),is.end()); ASSERT_EQUAL(4, is.size()); ASSERT_EQUAL('a', is.at(0)); ASSERT_EQUAL('g', is.at(1)); ASSERT_EQUAL('l', is.at(2)); ASSERT_EQUAL('s', is.at(3)); } void testCopyConstructor() { const IndexableSet<std::string> constSet { "g", "l", "s", "s", "s" }; IndexableSet<std::string> set { constSet }; ASSERT_EQUAL(constSet.size(), set.size()); ASSERT_EQUAL(constSet.at(1), set.at(1)); } void testMoveConstructor() { IndexableSet<std::string> setToMove { "w", "h", "i", "t", "e" }; IndexableSet<std::string> set { std::move(setToMove) }; ASSERT(setToMove.empty()); ASSERT_EQUAL(0, setToMove.size()); ASSERT_EQUAL(5, set.size()); } void runAllTests(int argc, char const *argv[]){ cute::suite s; s.push_back(CUTE(testIndexableSetAccess)); s.push_back(CUTE(testEmptyIndexableSet)); s.push_back(CUTE(testIndexableSetInsert)); s.push_back(CUTE(testIndexableSetFrontBack)); s.push_back(CUTE(testIndexableSetNegativeIndexAccessFromBack)); s.push_back(CUTE(testIndexableSetOverflowCapture)); s.push_back(CUTE(testIndexableSetCaselessCompare)); s.push_back(CUTE(testRangeConstructor)); s.push_back(CUTE(testCopyConstructor)); s.push_back(CUTE(testMoveConstructor)); cute::xml_file_opener xmlfile(argc,argv); cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out); cute::makeRunner(lis,argc,argv)(s, "AllTests"); } int main(int argc, char const *argv[]){ runAllTests(argc,argv); return 0; }<commit_msg>remove tests leading to undefined behaviour<commit_after>#include "cute.h" #include "ide_listener.h" #include "xml_listener.h" #include "cute_runner.h" #include "indexableSet.h" void testIndexableSetAccess() { IndexableSet<char> is{'b', 'e', 'e', 'r'}; ASSERT_EQUAL(3, is.size()); ASSERT_EQUAL('b', is[0]); ASSERT_EQUAL('e', is[1]); ASSERT_EQUAL('r', is[2]); } void testEmptyIndexableSet() { IndexableSet<int> is{}; ASSERT_EQUAL(0, is.size()); ASSERT(is.empty()); } void testIndexableSetInsert(){ IndexableSet<int> is{}; ASSERT_EQUAL(0,is.size()); is.insert(42); ASSERT_EQUAL(1,is.size()); ASSERT_EQUAL(42,is[0]); ASSERT_THROWS(is[1],std::out_of_range); } void testIndexableSetFrontBack() { IndexableSet<int> is{88, -10, 23, 6}; ASSERT_EQUAL(4, is.size()); ASSERT_EQUAL(-10, is.front()); ASSERT_EQUAL(88, is.back()); } void testIndexableSetNegativeIndexAccessFromBack() { IndexableSet<char> is{'b', 'e', 'e', 'r'}; ASSERT_EQUAL('r', is.at(-1)); ASSERT_EQUAL('e', is.at(-2)); ASSERT_EQUAL('b', is.at(-3)); } void testIndexableSetOverflowCapture() { IndexableSet<int> is{1, 2, 3, 4}; ASSERT_THROWS(is.at(4), std::out_of_range); ASSERT_THROWS(is.at(-5), std::out_of_range); IndexableSet<char> is2{}; ASSERT_THROWS(is2.at(0), std::out_of_range); ASSERT_THROWS(is2.at(-1), std::out_of_range); } void testIndexableSetCaselessCompare() { struct caselessCompare { bool operator ()(const std::string & left, const std::string & right) { return std::lexicographical_compare( left.begin(), left.end(), right.begin(), right.end(), [](const char l, const char r){ return std::tolower(l) < std::tolower(r); }); } }; IndexableSet<std::string,caselessCompare> cl_is {"H", "i", "I", "h"}; ASSERT_EQUAL(2, cl_is.size()); ASSERT_EQUAL("H", cl_is[0]); ASSERT_EQUAL("i", cl_is[1]); IndexableSet<std::string> is {"H", "i", "I", "h"}; ASSERT_EQUAL(4, is.size()); ASSERT_EQUAL("H", is[0]); ASSERT_EQUAL("I", is[1]); ASSERT_EQUAL("h", is[2]); ASSERT_EQUAL("i", is[3]); } void testRangeConstructor(){ const std::string str{"glass"}; IndexableSet<char> is(str.begin(), str.end()); std::string t(is.begin(),is.end()); ASSERT_EQUAL(4, is.size()); ASSERT_EQUAL('a', is.at(0)); ASSERT_EQUAL('g', is.at(1)); ASSERT_EQUAL('l', is.at(2)); ASSERT_EQUAL('s', is.at(3)); } void testCopyConstructor() { const IndexableSet<std::string> constSet { "g", "l", "s", "s", "s" }; IndexableSet<std::string> set { constSet }; ASSERT_EQUAL(constSet.size(), set.size()); ASSERT_EQUAL(constSet.at(1), set.at(1)); } void testMoveConstructor() { IndexableSet<std::string> setToMove { "w", "h", "i", "t", "e" }; IndexableSet<std::string> set { std::move(setToMove) }; ASSERT_EQUAL(5, set.size()); } void runAllTests(int argc, char const *argv[]){ cute::suite s; s.push_back(CUTE(testIndexableSetAccess)); s.push_back(CUTE(testEmptyIndexableSet)); s.push_back(CUTE(testIndexableSetInsert)); s.push_back(CUTE(testIndexableSetFrontBack)); s.push_back(CUTE(testIndexableSetNegativeIndexAccessFromBack)); s.push_back(CUTE(testIndexableSetOverflowCapture)); s.push_back(CUTE(testIndexableSetCaselessCompare)); s.push_back(CUTE(testRangeConstructor)); s.push_back(CUTE(testCopyConstructor)); s.push_back(CUTE(testMoveConstructor)); cute::xml_file_opener xmlfile(argc,argv); cute::xml_listener<cute::ide_listener<> > lis(xmlfile.out); cute::makeRunner(lis,argc,argv)(s, "AllTests"); } int main(int argc, char const *argv[]){ runAllTests(argc,argv); return 0; }<|endoftext|>
<commit_before>/** * \file wprastar.cc * * * * \author Seth Lemons * \date 2009-03-19 */ #include <assert.h> #include <math.h> #include <errno.h> #include <vector> #include <limits> #include "wprastar.h" #include "projection.h" #include "search.h" #include "state.h" using namespace std; wPRAStar::wPRAStarThread::wPRAStarThread(wPRAStar *p, vector<wPRAStarThread *> *threads, CompletionCounter* cc) : p(p), threads(threads), cc(cc), q_empty(true) { completed = false; pthread_mutex_init(&mutex, NULL); } wPRAStar::wPRAStarThread::~wPRAStarThread(void) { } void wPRAStar::wPRAStarThread::add(State* c, bool self_add){ if (self_add){ pthread_mutex_unlock(&mutex); State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } return; } pthread_mutex_lock(&mutex); if (completed){ cc->uncomplete(); completed = false; } q.push_back(c); q_empty = false; pthread_mutex_unlock(&mutex); } /** * Flush the queue */ void wPRAStar::wPRAStarThread::flush_queue(void) { // wait for either completion or more nodes to expand if (open.empty()) { pthread_mutex_lock(&mutex); } else if (pthread_mutex_trylock(&mutex) == EBUSY) { return; } if (q_empty) { if (!open.empty()) { pthread_mutex_unlock(&mutex); return; } completed = true; cc->complete(); // busy wait pthread_mutex_unlock(&mutex); while (q_empty && !cc->is_complete() && !p->is_done()) ; pthread_mutex_lock(&mutex); // we are done, just return if (cc->is_complete()) { assert(q_empty); pthread_mutex_unlock(&mutex); return; } } // got some stuff on the queue, lets do duplicate detection // and add stuff to the open list for (unsigned int i = 0; i < q.size(); i += 1) { State *c = q[i]; State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } } q.clear(); q_empty = true; pthread_mutex_unlock(&mutex); } State *wPRAStar::wPRAStarThread::take(void){ while (open.empty() || !q_empty) { flush_queue(); if (cc->is_complete()){ p->set_done(); return NULL; } } State *ret = NULL; if (!p->is_done()) ret = open.take(); return ret; } /** * Run the search thread. */ void wPRAStar::wPRAStarThread::run(void){ vector<State *> *children = NULL; while(!p->is_done()){ State *s = take(); if (s == NULL) continue; if (s->get_f_prime() >= p->bound.read()) { open.prune(); } if (p->weight * s->get_f() >= p->bound.read()) { continue; } if (s->is_goal()) { p->set_path(s->get_path()); } children = p->expand(s); for (unsigned int i = 0; i < children->size(); i += 1) { State *c = children->at(i); bool self_add = threads->at(p->project->project(c)%p->n_threads)->get_id() == this->get_id(); threads->at(p->project->project(c)%p->n_threads)->add(c, self_add); } } if (children) delete children; } /************************************************************/ wPRAStar::wPRAStar(unsigned int n_threads) : n_threads(n_threads), bound(fp_infinity), project(NULL), path(NULL){ done = false; } wPRAStar::wPRAStar(unsigned int n_threads, fp_type bound) : n_threads(n_threads), bound(bound), project(NULL), path(NULL){ done = false; } wPRAStar::~wPRAStar(void) { } void wPRAStar::set_done() { pthread_mutex_lock(&mutex); done = true; pthread_mutex_unlock(&mutex); } bool wPRAStar::is_done() { bool ret; pthread_mutex_lock(&mutex); ret = done; pthread_mutex_unlock(&mutex); return ret; } void wPRAStar::set_path(vector<State *> *p) { pthread_mutex_lock(&mutex); if (this->path == NULL || this->path->at(0)->get_g() > p->at(0)->get_g()){ this->path = p; bound.set(p->at(0)->get_g()); } pthread_mutex_unlock(&mutex); } bool wPRAStar::has_path() { bool ret; pthread_mutex_lock(&mutex); ret = (path != NULL); pthread_mutex_unlock(&mutex); return ret; } vector<State *> *wPRAStar::search(State *init) { pthread_mutex_init(&mutex, NULL); project = init->get_domain()->get_projection(); weight = init->get_domain()->get_heuristic()->get_weight(); CompletionCounter cc = CompletionCounter(n_threads); for (unsigned int i = 0; i < n_threads; i += 1) { wPRAStarThread *t = new wPRAStarThread(this, &threads, &cc); threads.push_back(t); } threads.at(project->project(init)%n_threads)->open.add(init); for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->start(); } for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->join(); delete *iter; } return path; } <commit_msg>possible fix to wPRA* issues<commit_after>/** * \file wprastar.cc * * * * \author Seth Lemons * \date 2009-03-19 */ #include <assert.h> #include <math.h> #include <errno.h> #include <vector> #include <limits> #include "wprastar.h" #include "projection.h" #include "search.h" #include "state.h" using namespace std; wPRAStar::wPRAStarThread::wPRAStarThread(wPRAStar *p, vector<wPRAStarThread *> *threads, CompletionCounter* cc) : p(p), threads(threads), cc(cc), q_empty(true) { completed = false; pthread_mutex_init(&mutex, NULL); } wPRAStar::wPRAStarThread::~wPRAStarThread(void) { } void wPRAStar::wPRAStarThread::add(State* c, bool self_add){ if (self_add){ pthread_mutex_unlock(&mutex); State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } //delete c; } else{ open.add(c); closed.add(c); } return; } pthread_mutex_lock(&mutex); if (completed){ cc->uncomplete(); completed = false; } q.push_back(c); q_empty = false; pthread_mutex_unlock(&mutex); } /** * Flush the queue */ void wPRAStar::wPRAStarThread::flush_queue(void) { // wait for either completion or more nodes to expand if (open.empty()) { pthread_mutex_lock(&mutex); } else if (pthread_mutex_trylock(&mutex) == EBUSY) { return; } if (q_empty) { if (!open.empty()) { pthread_mutex_unlock(&mutex); return; } completed = true; cc->complete(); // busy wait pthread_mutex_unlock(&mutex); while (q_empty && !cc->is_complete() && !p->is_done()) ; pthread_mutex_lock(&mutex); // we are done, just return if (cc->is_complete()) { assert(q_empty); pthread_mutex_unlock(&mutex); return; } } // got some stuff on the queue, lets do duplicate detection // and add stuff to the open list for (unsigned int i = 0; i < q.size(); i += 1) { State *c = q[i]; State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } //delete c; } else{ open.add(c); closed.add(c); } } q.clear(); q_empty = true; pthread_mutex_unlock(&mutex); } State *wPRAStar::wPRAStarThread::take(void){ while (open.empty() || !q_empty) { flush_queue(); if (cc->is_complete()){ p->set_done(); return NULL; } } State *ret = NULL; if (!p->is_done()) ret = open.take(); return ret; } /** * Run the search thread. */ void wPRAStar::wPRAStarThread::run(void){ vector<State *> *children = NULL; while(!p->is_done()){ State *s = take(); if (s == NULL) continue; if (s->get_f_prime() >= p->bound.read()) { open.prune(); } if (p->weight * s->get_f() >= p->bound.read()) { continue; } if (s->is_goal()) { p->set_path(s->get_path()); } children = p->expand(s); for (unsigned int i = 0; i < children->size(); i += 1) { State *c = children->at(i); bool self_add = threads->at(p->project->project(c)%p->n_threads)->get_id() == this->get_id(); threads->at(p->project->project(c)%p->n_threads)->add(c, self_add); } } if (children) delete children; } /************************************************************/ wPRAStar::wPRAStar(unsigned int n_threads) : n_threads(n_threads), bound(fp_infinity), project(NULL), path(NULL){ done = false; } wPRAStar::wPRAStar(unsigned int n_threads, fp_type bound) : n_threads(n_threads), bound(bound), project(NULL), path(NULL){ done = false; } wPRAStar::~wPRAStar(void) { } void wPRAStar::set_done() { pthread_mutex_lock(&mutex); done = true; pthread_mutex_unlock(&mutex); } bool wPRAStar::is_done() { bool ret; pthread_mutex_lock(&mutex); ret = done; pthread_mutex_unlock(&mutex); return ret; } void wPRAStar::set_path(vector<State *> *p) { pthread_mutex_lock(&mutex); if (this->path == NULL || this->path->at(0)->get_g() > p->at(0)->get_g()){ this->path = p; bound.set(p->at(0)->get_g()); } pthread_mutex_unlock(&mutex); } bool wPRAStar::has_path() { bool ret; pthread_mutex_lock(&mutex); ret = (path != NULL); pthread_mutex_unlock(&mutex); return ret; } vector<State *> *wPRAStar::search(State *init) { pthread_mutex_init(&mutex, NULL); project = init->get_domain()->get_projection(); weight = init->get_domain()->get_heuristic()->get_weight(); CompletionCounter cc = CompletionCounter(n_threads); for (unsigned int i = 0; i < n_threads; i += 1) { wPRAStarThread *t = new wPRAStarThread(this, &threads, &cc); threads.push_back(t); } threads.at(project->project(init)%n_threads)->open.add(init); for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->start(); } for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->join(); delete *iter; } return path; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under 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) //======================================================================= #include <iostream> #include <cstdio> #include "Compiler.hpp" #include "Target.hpp" #include "Utils.hpp" #include "DebugStopWatch.hpp" #include "Options.hpp" #include "StringPool.hpp" #include "FunctionTable.hpp" #include "SemanticalException.hpp" #include "AssemblyFileWriter.hpp" #include "parser/SpiritParser.hpp" #include "ast/SourceFile.hpp" //Annotators #include "DefaultValues.hpp" #include "ContextAnnotator.hpp" #include "FunctionsAnnotator.hpp" #include "VariablesAnnotator.hpp" //Checkers #include "StringChecker.hpp" #include "TypeChecker.hpp" //Visitors #include "DependenciesResolver.hpp" #include "OptimizationEngine.hpp" #include "TransformerEngine.hpp" #include "WarningsEngine.hpp" #include "DebugVisitor.hpp" //Three Address Code #include "tac/Program.hpp" #include "tac/Compiler.hpp" #include "tac/BasicBlockExtractor.hpp" #include "tac/TemporaryAllocator.hpp" #include "tac/LivenessAnalyzer.hpp" #include "tac/Optimizer.hpp" #include "tac/Printer.hpp" //Code generation #include "asm/IntelX86CodeGenerator.hpp" #ifdef DEBUG static const bool debug = true; #else static const bool debug = false; #endif #define TIMER_START(name) StopWatch name_timer; #define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;} using namespace eddic; void exec(const std::string& command); int Compiler::compile(const std::string& file) { std::cout << "Compile " << file << std::endl; if(TargetDetermined && Target64){ std::cout << "Warning : Looks like you're running a 64 bit system. This compiler only outputs 32 bits assembly." << std::endl; } StopWatch timer; int code = compileOnly(file); std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl; return code; } int Compiler::compileOnly(const std::string& file) { std::string output = options["output"].as<std::string>(); int code = 0; try { TIMER_START(parsing) parser::SpiritParser parser; //The program to build ast::SourceFile program; //Parse the file into the program bool parsing = parser.parse(file, program); TIMER_END(parsing) if(parsing){ //Symbol tables FunctionTable functionTable; StringPool pool; //Read dependencies includeDependencies(program, parser); //Apply some cleaning transformations clean(program); //Annotate the AST with more informations defineDefaultValues(program); //Fill the string pool checkStrings(program, pool); //Add some more informations to the AST defineContexts(program); defineVariables(program); defineFunctions(program, functionTable); //Transform the AST transform(program); //Static analysis checkTypes(program); //Check for warnings checkForWarnings(program, functionTable); //Optimize the AST optimize(program, functionTable, pool); tac::Program tacProgram; //Generate Three-Address-Code language tac::Compiler compiler; compiler.compile(program, pool, tacProgram); //Separate into basic blocks tac::BasicBlockExtractor extractor; extractor.extract(tacProgram); //Allocate storage for the temporaries that need to be stored tac::TemporaryAllocator allocator; allocator.allocate(tacProgram); tac::Optimizer optimizer; optimizer.optimize(tacProgram); //Compute liveness of variables tac::LivenessAnalyzer liveness; liveness.compute(tacProgram); //Generate assembly from TAC AssemblyFileWriter writer("output.asm"); as::IntelX86CodeGenerator generator(writer); generator.generate(tacProgram, pool); writer.write(); //If it's necessary, assemble and link the assembly if(!options.count("assembly")){ exec("as --32 -o output.o output.asm"); exec("ld -m elf_i386 output.o -o " + output); //Remove temporary files remove("output.asm"); remove("output.o"); } } } catch (const SemanticalException& e) { std::cout << e.what() << std::endl; code = 1; } return code; } void eddic::defineDefaultValues(ast::SourceFile& program){ DebugStopWatch<debug> timer("Annotate with default values"); DefaultValues values; values.fill(program); } void eddic::defineContexts(ast::SourceFile& program){ DebugStopWatch<debug> timer("Annotate contexts"); ContextAnnotator annotator; annotator.annotate(program); } void eddic::defineVariables(ast::SourceFile& program){ DebugStopWatch<debug> timer("Annotate variables"); VariablesAnnotator annotator; annotator.annotate(program); } void eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){ DebugStopWatch<debug> timer("Annotate functions"); FunctionsAnnotator annotator; annotator.annotate(program, functionTable); } void eddic::checkStrings(ast::SourceFile& program, StringPool& pool){ DebugStopWatch<debug> timer("Strings checking"); StringChecker checker; checker.check(program, pool); } void eddic::checkTypes(ast::SourceFile& program){ DebugStopWatch<debug> timer("Types checking"); TypeChecker checker; checker.check(program); } void eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){ DebugStopWatch<debug> timer("Check for warnings"); WarningsEngine engine; engine.check(program, table); } void eddic::clean(ast::SourceFile& program){ DebugStopWatch<debug> timer("Cleaning"); TransformerEngine engine; engine.clean(program); } void eddic::transform(ast::SourceFile& program){ DebugStopWatch<debug> timer("Transformation"); TransformerEngine engine; engine.transform(program); } void eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){ DebugStopWatch<debug> timer("Optimization"); OptimizationEngine engine; engine.optimize(program, functionTable, pool); } void eddic::includeDependencies(ast::SourceFile& sourceFile, parser::SpiritParser& parser){ DebugStopWatch<debug> timer("Resolve dependencies"); DependenciesResolver resolver(parser); resolver.resolve(sourceFile); } void exec(const std::string& command) { DebugStopWatch<debug> timer("Exec " + command); if(debug){ std::cout << "eddic : exec command : " << command << std::endl; } std::string result = execCommand(command); if(result.size() > 0){ std::cout << result << std::endl; } } void eddic::warn(const std::string& warning){ std::cout << "warning: " << warning << std::endl; } <commit_msg>By default, strip debugging symbols<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under 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) //======================================================================= #include <iostream> #include <cstdio> #include "Compiler.hpp" #include "Target.hpp" #include "Utils.hpp" #include "DebugStopWatch.hpp" #include "Options.hpp" #include "StringPool.hpp" #include "FunctionTable.hpp" #include "SemanticalException.hpp" #include "AssemblyFileWriter.hpp" #include "parser/SpiritParser.hpp" #include "ast/SourceFile.hpp" //Annotators #include "DefaultValues.hpp" #include "ContextAnnotator.hpp" #include "FunctionsAnnotator.hpp" #include "VariablesAnnotator.hpp" //Checkers #include "StringChecker.hpp" #include "TypeChecker.hpp" //Visitors #include "DependenciesResolver.hpp" #include "OptimizationEngine.hpp" #include "TransformerEngine.hpp" #include "WarningsEngine.hpp" #include "DebugVisitor.hpp" //Three Address Code #include "tac/Program.hpp" #include "tac/Compiler.hpp" #include "tac/BasicBlockExtractor.hpp" #include "tac/TemporaryAllocator.hpp" #include "tac/LivenessAnalyzer.hpp" #include "tac/Optimizer.hpp" #include "tac/Printer.hpp" //Code generation #include "asm/IntelX86CodeGenerator.hpp" #ifdef DEBUG static const bool debug = true; #else static const bool debug = false; #endif #define TIMER_START(name) StopWatch name_timer; #define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;} using namespace eddic; void exec(const std::string& command); int Compiler::compile(const std::string& file) { std::cout << "Compile " << file << std::endl; if(TargetDetermined && Target64){ std::cout << "Warning : Looks like you're running a 64 bit system. This compiler only outputs 32 bits assembly." << std::endl; } StopWatch timer; int code = compileOnly(file); std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl; return code; } int Compiler::compileOnly(const std::string& file) { std::string output = options["output"].as<std::string>(); int code = 0; try { TIMER_START(parsing) parser::SpiritParser parser; //The program to build ast::SourceFile program; //Parse the file into the program bool parsing = parser.parse(file, program); TIMER_END(parsing) if(parsing){ //Symbol tables FunctionTable functionTable; StringPool pool; //Read dependencies includeDependencies(program, parser); //Apply some cleaning transformations clean(program); //Annotate the AST with more informations defineDefaultValues(program); //Fill the string pool checkStrings(program, pool); //Add some more informations to the AST defineContexts(program); defineVariables(program); defineFunctions(program, functionTable); //Transform the AST transform(program); //Static analysis checkTypes(program); //Check for warnings checkForWarnings(program, functionTable); //Optimize the AST optimize(program, functionTable, pool); tac::Program tacProgram; //Generate Three-Address-Code language tac::Compiler compiler; compiler.compile(program, pool, tacProgram); //Separate into basic blocks tac::BasicBlockExtractor extractor; extractor.extract(tacProgram); //Allocate storage for the temporaries that need to be stored tac::TemporaryAllocator allocator; allocator.allocate(tacProgram); tac::Optimizer optimizer; optimizer.optimize(tacProgram); //Compute liveness of variables tac::LivenessAnalyzer liveness; liveness.compute(tacProgram); //Generate assembly from TAC AssemblyFileWriter writer("output.asm"); as::IntelX86CodeGenerator generator(writer); generator.generate(tacProgram, pool); writer.write(); //If it's necessary, assemble and link the assembly if(!options.count("assembly")){ exec("as --32 -o output.o output.asm"); exec("ld -S -m elf_i386 output.o -o " + output); //Remove temporary files remove("output.asm"); remove("output.o"); } } } catch (const SemanticalException& e) { std::cout << e.what() << std::endl; code = 1; } return code; } void eddic::defineDefaultValues(ast::SourceFile& program){ DebugStopWatch<debug> timer("Annotate with default values"); DefaultValues values; values.fill(program); } void eddic::defineContexts(ast::SourceFile& program){ DebugStopWatch<debug> timer("Annotate contexts"); ContextAnnotator annotator; annotator.annotate(program); } void eddic::defineVariables(ast::SourceFile& program){ DebugStopWatch<debug> timer("Annotate variables"); VariablesAnnotator annotator; annotator.annotate(program); } void eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){ DebugStopWatch<debug> timer("Annotate functions"); FunctionsAnnotator annotator; annotator.annotate(program, functionTable); } void eddic::checkStrings(ast::SourceFile& program, StringPool& pool){ DebugStopWatch<debug> timer("Strings checking"); StringChecker checker; checker.check(program, pool); } void eddic::checkTypes(ast::SourceFile& program){ DebugStopWatch<debug> timer("Types checking"); TypeChecker checker; checker.check(program); } void eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){ DebugStopWatch<debug> timer("Check for warnings"); WarningsEngine engine; engine.check(program, table); } void eddic::clean(ast::SourceFile& program){ DebugStopWatch<debug> timer("Cleaning"); TransformerEngine engine; engine.clean(program); } void eddic::transform(ast::SourceFile& program){ DebugStopWatch<debug> timer("Transformation"); TransformerEngine engine; engine.transform(program); } void eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){ DebugStopWatch<debug> timer("Optimization"); OptimizationEngine engine; engine.optimize(program, functionTable, pool); } void eddic::includeDependencies(ast::SourceFile& sourceFile, parser::SpiritParser& parser){ DebugStopWatch<debug> timer("Resolve dependencies"); DependenciesResolver resolver(parser); resolver.resolve(sourceFile); } void exec(const std::string& command) { DebugStopWatch<debug> timer("Exec " + command); if(debug){ std::cout << "eddic : exec command : " << command << std::endl; } std::string result = execCommand(command); if(result.size() > 0){ std::cout << result << std::endl; } } void eddic::warn(const std::string& warning){ std::cout << "warning: " << warning << std::endl; } <|endoftext|>
<commit_before>#include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "Camera.h" #include "util.h" #include "FlatCube.h" unsigned int FlatCube::flatCubeCounter = 0; /** * Shader IDs */ GLuint FlatCube::vertexShaderId = 0; GLuint FlatCube::fragmentShaderId = 0; GLuint FlatCube::programObject = 0; /** * Shader variables indexes */ GLint FlatCube::v_pos_index = 0; GLint FlatCube::v_color_index = 0; GLint FlatCube::model_matrix_index = 0; GLint FlatCube::view_matrix_index = 0; GLint FlatCube::projection_matrix_index = 0; /** * Flat cube vertices */ GLfloat FlatCube::vertices[] = { // Front face -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, // Back face 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, // Left face -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, // Right face 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, // Top face -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, // Bottom face -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, }; /** * Flat cube colors */ GLfloat FlatCube::colors[] = { // Front face 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, // Back face 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, // Left face 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, // Right face 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, // Top face 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, // Bottom face 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f }; FlatCube::FlatCube() : angle{0.0f} { if (flatCubeCounter == 0) { char vertex_shader[] = "#version 100 \n" "uniform mat4 model_m; " "uniform mat4 view_m; " "uniform mat4 proj_m; " "attribute vec3 v_pos; " "attribute vec3 v_color; " "varying vec3 f_color; " "void main(){ " " f_color = v_color; " " gl_Position = proj_m * view_m * model_m * vec4(v_pos,1.0); " "} "; char fragment_shader[] = "#version 100 \n" "precision mediump float; " "varying vec3 f_color; " "void main(){ " " gl_FragColor = vec4(f_color, 1.0); " "} "; vertexShaderId = loadShader(vertex_shader, GL_VERTEX_SHADER); fragmentShaderId = loadShader(fragment_shader, GL_FRAGMENT_SHADER); programObject = linkProgram(vertexShaderId, fragmentShaderId); v_pos_index = glGetAttribLocation(programObject, "v_pos"); v_color_index = glGetAttribLocation(programObject, "v_color"); model_matrix_index = glGetUniformLocation(programObject, "model_m"); view_matrix_index = glGetUniformLocation(programObject, "view_m"); projection_matrix_index = glGetUniformLocation(programObject, "proj_m"); } ++flatCubeCounter; } FlatCube::~FlatCube() { --flatCubeCounter; if (flatCubeCounter == 0) { glDeleteProgram(programObject); programObject = 0; glDeleteShader(vertexShaderId); vertexShaderId = 0; glDeleteShader(fragmentShaderId); fragmentShaderId = 0; v_pos_index = 0; v_color_index = 0; model_matrix_index = 0; view_matrix_index = 0; projection_matrix_index = 0; } } void FlatCube::update(unsigned int timeelapsed){ angle = PI/4.0f/1000.0f * timeelapsed; } void FlatCube::draw(){ glUseProgram(programObject); // Get and set transformation matrices //glm::mat4 model(1.0f); glm::mat4 model = glm::rotate( glm::mat4(1.0f), angle, glm::normalize(glm::vec3(0.0f,1.0f,0.0f))); glm::mat4 view = Camera::getCurrentCamera()->viewMatrix(); //glm::mat4 proj = glm::mat4(1.0f); glm::mat4 proj = glm::perspective(45.0f, 4.0f/3.0f, 0.1f, 100.0f); glUniformMatrix4fv(model_matrix_index, 1, GL_FALSE, glm::value_ptr(model)); glUniformMatrix4fv(view_matrix_index, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projection_matrix_index, 1, GL_FALSE, glm::value_ptr(proj)); // Set Vertex Attributes glVertexAttribPointer(v_pos_index, 3, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(v_color_index, 3, GL_FLOAT, GL_FALSE, 0, colors); glEnableVertexAttribArray(v_pos_index); glEnableVertexAttribArray(v_color_index); // Draw flat cube glDrawArrays(GL_TRIANGLES,0,36); } <commit_msg>Fix to use Camera projection matrix<commit_after>#include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "Camera.h" #include "util.h" #include "FlatCube.h" unsigned int FlatCube::flatCubeCounter = 0; /** * Shader IDs */ GLuint FlatCube::vertexShaderId = 0; GLuint FlatCube::fragmentShaderId = 0; GLuint FlatCube::programObject = 0; /** * Shader variables indexes */ GLint FlatCube::v_pos_index = 0; GLint FlatCube::v_color_index = 0; GLint FlatCube::model_matrix_index = 0; GLint FlatCube::view_matrix_index = 0; GLint FlatCube::projection_matrix_index = 0; /** * Flat cube vertices */ GLfloat FlatCube::vertices[] = { // Front face -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, // Back face 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, // Left face -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, // Right face 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, // Top face -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, // Bottom face -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, }; /** * Flat cube colors */ GLfloat FlatCube::colors[] = { // Front face 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, // Back face 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, // Left face 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, // Right face 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, 0.1f, 0.1f, 0.9f, // Top face 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, // Bottom face 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f, 0.9f, 0.1f, 0.9f }; FlatCube::FlatCube() : angle{0.0f} { if (flatCubeCounter == 0) { char vertex_shader[] = "#version 100 \n" "uniform mat4 model_m; " "uniform mat4 view_m; " "uniform mat4 proj_m; " "attribute vec3 v_pos; " "attribute vec3 v_color; " "varying vec3 f_color; " "void main(){ " " f_color = v_color; " " gl_Position = proj_m * view_m * model_m * vec4(v_pos,1.0); " "} "; char fragment_shader[] = "#version 100 \n" "precision mediump float; " "varying vec3 f_color; " "void main(){ " " gl_FragColor = vec4(f_color, 1.0); " "} "; vertexShaderId = loadShader(vertex_shader, GL_VERTEX_SHADER); fragmentShaderId = loadShader(fragment_shader, GL_FRAGMENT_SHADER); programObject = linkProgram(vertexShaderId, fragmentShaderId); v_pos_index = glGetAttribLocation(programObject, "v_pos"); v_color_index = glGetAttribLocation(programObject, "v_color"); model_matrix_index = glGetUniformLocation(programObject, "model_m"); view_matrix_index = glGetUniformLocation(programObject, "view_m"); projection_matrix_index = glGetUniformLocation(programObject, "proj_m"); } ++flatCubeCounter; } FlatCube::~FlatCube() { --flatCubeCounter; if (flatCubeCounter == 0) { glDeleteProgram(programObject); programObject = 0; glDeleteShader(vertexShaderId); vertexShaderId = 0; glDeleteShader(fragmentShaderId); fragmentShaderId = 0; v_pos_index = 0; v_color_index = 0; model_matrix_index = 0; view_matrix_index = 0; projection_matrix_index = 0; } } void FlatCube::update(unsigned int timeelapsed){ angle = PI/4.0f/1000.0f * timeelapsed; } void FlatCube::draw(){ glUseProgram(programObject); // Get and set transformation matrices glm::mat4 model = glm::rotate( glm::mat4(1.0f), angle, glm::normalize(glm::vec3(0.0f,1.0f,0.0f))); glm::mat4 view = Camera::getCurrentCamera()->viewMatrix(); glm::mat4 proj = Camera::getCurrentCamera()->projMatrix(); glUniformMatrix4fv(model_matrix_index, 1, GL_FALSE, glm::value_ptr(model)); glUniformMatrix4fv(view_matrix_index, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projection_matrix_index, 1, GL_FALSE, glm::value_ptr(proj)); // Set Vertex Attributes glVertexAttribPointer(v_pos_index, 3, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(v_color_index, 3, GL_FLOAT, GL_FALSE, 0, colors); glEnableVertexAttribArray(v_pos_index); glEnableVertexAttribArray(v_color_index); // Draw flat cube glDrawArrays(GL_TRIANGLES,0,36); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under 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) //======================================================================= #include <cassert> #include "Function.hpp" #include "Type.hpp" using namespace eddic; ParameterType::ParameterType(const std::string& n, std::shared_ptr<Type> t) : name(n), paramType(t) {} Function::Function(std::shared_ptr<Type> ret, const std::string& n) : returnType(ret), name(n), references(0) {} std::shared_ptr<Type> Function::getParameterType(const std::string& name){ for(auto& p : parameters){ if(p.name == name){ return p.paramType; } } assert(false && "This parameter does not exists in the given function"); } unsigned int Function::getParameterPositionByType(const std::string& name){ unsigned int position = 0; auto type = getParameterType(name); for(auto& p : parameters){ if(p.paramType == type){ ++position; } if(p.name == name){ return position; } } assert(false && "The parameter does not exists in the function"); } <commit_msg>Use the correct operator<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under 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) //======================================================================= #include <cassert> #include "Function.hpp" #include "Type.hpp" #include "Types.hpp" using namespace eddic; ParameterType::ParameterType(const std::string& n, std::shared_ptr<Type> t) : name(n), paramType(t) {} Function::Function(std::shared_ptr<Type> ret, const std::string& n) : returnType(ret), name(n), references(0) {} std::shared_ptr<Type> Function::getParameterType(const std::string& name){ for(auto& p : parameters){ if(p.name == name){ return p.paramType; } } assert(false && "This parameter does not exists in the given function"); } unsigned int Function::getParameterPositionByType(const std::string& name){ unsigned int position = 0; auto type = getParameterType(name); for(auto& p : parameters){ if(p.paramType == type){ ++position; } if(p.name == name){ return position; } } assert(false && "The parameter does not exists in the function"); } <|endoftext|>
<commit_before>#include "control.h" #include<chrono> std::atomic<int> BVS::Control::runningThreads; int BVS::Control::threadedModules = 0; BVS::Control::Control(Info& info) : info(info) , flag(SystemFlag::PAUSE) , logger("Control") , masterMutex() , masterLock(masterMutex) , masterCond() , threadMutex() , threadCond() , controlThread() , round(0) , timer(std::chrono::high_resolution_clock::now()) , timer2(std::chrono::high_resolution_clock::now()) { runningThreads.store(0); } BVS::Control& BVS::Control::masterController(const bool forkMasterController) { if (forkMasterController) { LOG(3, "master -> FORKED!"); controlThread = std::thread(&Control::masterController, this, false); return *this; } masterCond.notify_one(); masterCond.wait(masterLock, [&](){ return threadedModules == runningThreads.load(); }); runningThreads.store(0); while (flag != SystemFlag::QUIT) { // synchronize masterCond.wait(masterLock, [&](){ return runningThreads.load() == 0; }); switch (flag) { case SystemFlag::QUIT: break; case SystemFlag::PAUSE: if (!controlThread.joinable()) return *this; LOG(3, "PAUSE..."); masterCond.wait(masterLock, [&](){ return flag != SystemFlag::PAUSE; }); LOG(3, "CONTINUE..."); break; case SystemFlag::RUN: case SystemFlag::STEP: info.round = round; LOG(3, "ANNOUNCE ROUND: " << round++); for (auto& it: Loader::modules) { it.second->flag = ModuleFlag::RUN; if (it.second->asThread) runningThreads.fetch_add(1, std::memory_order_seq_cst); } timer2 = std::chrono::high_resolution_clock::now(); info.lastRoundDuration = std::chrono::duration_cast<std::chrono::milliseconds>(timer2 - timer); timer = timer2; threadCond.notify_all(); for (auto& it: Loader::masterModules) { timer2 = std::chrono::high_resolution_clock::now(); moduleController(*(it.get())); info.moduleDurations[it.get()->id] = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - timer2); } if (flag == SystemFlag::STEP) flag = SystemFlag::PAUSE; break; case SystemFlag::STEP_BACK: break; } LOG(3, "WAITING FOR MODULES!"); if (!controlThread.joinable() && flag != SystemFlag::RUN) return *this; } return *this; } BVS::Control& BVS::Control::sendCommand(const SystemFlag controlFlag) { LOG(3, "FLAG: " << (int)controlFlag); flag = controlFlag; // check if controlThread is running and notify it, otherwise call control function each time if (controlThread.joinable()) masterCond.notify_one(); else masterController(false); if (controlFlag == SystemFlag::QUIT) { if (controlThread.joinable()) { LOG(3, "JOIN MASTER CONTROLLER!"); controlThread.join(); } } return *this; } BVS::Control& BVS::Control::moduleController(ModuleData& data) { switch (data.flag) { case ModuleFlag::QUIT: break; case ModuleFlag::WAIT: break; case ModuleFlag::RUN: data.status = data.module->execute(); data.flag = ModuleFlag::WAIT; break; } return *this; } BVS::Control& BVS::Control::threadController(std::shared_ptr<ModuleData> data) { std::unique_lock<std::mutex> threadLock(threadMutex); runningThreads.fetch_add(1, std::memory_order_seq_cst); while (bool(data->flag)) { LOG(3, data->id << " -> WAIT!"); masterCond.notify_one(); threadCond.wait(threadLock, [&](){ return data->flag != ModuleFlag::WAIT; }); moduleController(*(data.get())); runningThreads.fetch_sub(1, std::memory_order_seq_cst); info.moduleDurations[data.get()->id] = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - timer); } return *this; } <commit_msg>control: remove verbose memory order settings (default anyway)<commit_after>#include "control.h" #include<chrono> std::atomic<int> BVS::Control::runningThreads; int BVS::Control::threadedModules = 0; BVS::Control::Control(Info& info) : info(info) , flag(SystemFlag::PAUSE) , logger("Control") , masterMutex() , masterLock(masterMutex) , masterCond() , threadMutex() , threadCond() , controlThread() , round(0) , timer(std::chrono::high_resolution_clock::now()) , timer2(std::chrono::high_resolution_clock::now()) { runningThreads.store(0); } BVS::Control& BVS::Control::masterController(const bool forkMasterController) { if (forkMasterController) { LOG(3, "master -> FORKED!"); controlThread = std::thread(&Control::masterController, this, false); return *this; } masterCond.notify_one(); masterCond.wait(masterLock, [&](){ return threadedModules == runningThreads.load(); }); runningThreads.store(0); while (flag != SystemFlag::QUIT) { // synchronize masterCond.wait(masterLock, [&](){ return runningThreads.load() == 0; }); switch (flag) { case SystemFlag::QUIT: break; case SystemFlag::PAUSE: if (!controlThread.joinable()) return *this; LOG(3, "PAUSE..."); masterCond.wait(masterLock, [&](){ return flag != SystemFlag::PAUSE; }); LOG(3, "CONTINUE..."); break; case SystemFlag::RUN: case SystemFlag::STEP: info.round = round; LOG(3, "ANNOUNCE ROUND: " << round++); for (auto& it: Loader::modules) { it.second->flag = ModuleFlag::RUN; if (it.second->asThread) runningThreads.fetch_add(1); } timer2 = std::chrono::high_resolution_clock::now(); info.lastRoundDuration = std::chrono::duration_cast<std::chrono::milliseconds>(timer2 - timer); timer = timer2; threadCond.notify_all(); for (auto& it: Loader::masterModules) { timer2 = std::chrono::high_resolution_clock::now(); moduleController(*(it.get())); info.moduleDurations[it.get()->id] = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - timer2); } if (flag == SystemFlag::STEP) flag = SystemFlag::PAUSE; break; case SystemFlag::STEP_BACK: break; } LOG(3, "WAITING FOR MODULES!"); if (!controlThread.joinable() && flag != SystemFlag::RUN) return *this; } return *this; } BVS::Control& BVS::Control::sendCommand(const SystemFlag controlFlag) { LOG(3, "FLAG: " << (int)controlFlag); flag = controlFlag; // check if controlThread is running and notify it, otherwise call control function each time if (controlThread.joinable()) masterCond.notify_one(); else masterController(false); if (controlFlag == SystemFlag::QUIT) { if (controlThread.joinable()) { LOG(3, "JOIN MASTER CONTROLLER!"); controlThread.join(); } } return *this; } BVS::Control& BVS::Control::moduleController(ModuleData& data) { switch (data.flag) { case ModuleFlag::QUIT: break; case ModuleFlag::WAIT: break; case ModuleFlag::RUN: data.status = data.module->execute(); data.flag = ModuleFlag::WAIT; break; } return *this; } BVS::Control& BVS::Control::threadController(std::shared_ptr<ModuleData> data) { std::unique_lock<std::mutex> threadLock(threadMutex); runningThreads.fetch_add(1); while (bool(data->flag)) { LOG(3, data->id << " -> WAIT!"); masterCond.notify_one(); threadCond.wait(threadLock, [&](){ return data->flag != ModuleFlag::WAIT; }); moduleController(*(data.get())); runningThreads.fetch_sub(1); info.moduleDurations[data.get()->id] = std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::high_resolution_clock::now() - timer); } return *this; } <|endoftext|>
<commit_before>#include <PCU.h> #include <MeshSim.h> #include <SimPartitionedMesh.h> #include <SimUtil.h> #include <SimParasolidKrnl.h> #include <apfSIM.h> #include <apfMDS.h> #include <gmi_sim.h> #include <apf.h> #include <apfConvert.h> #include <apfMesh2.h> static void fixMatches(apf::Mesh2* m) { if (m->hasMatching()) { if (apf::alignMdsMatches(m)) printf("fixed misaligned matches\n"); else printf("matches were aligned\n"); assert( ! apf::alignMdsMatches(m)); } } static void fixPyramids(apf::Mesh2* m) { ma::Input* in = ma::configureIdentity(m); in->shouldCleanupLayer = true; ma::adapt(in); } static void postConvert(apf::Mesh2* m) { fixMatches(m); fixPyramids(m); m->verify(); } int main(int argc, char** argv) { MPI_Init(&argc, &argv); PCU_Comm_Init(); if (argc != 4) { if(0==PCU_Comm_Self()) std::cerr << "usage: " << argv[0] << " <model file> <simmetrix mesh> <scorec mesh>\n"; return EXIT_FAILURE; } Sim_readLicenseFile(NULL); SimPartitionedMesh_start(&argc,&argv); SimModel_start(); pProgress progress = Progress_new(); Progress_setDefaultCallback(progress); pGModel simModel; simModel = GM_load(argv[1], NULL, progress); pParMesh sim_mesh = PM_load(argv[2],sthreadNone,0,progress); apf::Mesh* simApfMesh = apf::createMesh(sim_mesh); gmi_register_sim(); gmi_model* mdl = gmi_import_sim(simModel); apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh); apf::destroyMesh(simApfMesh); M_release(sim_mesh); postConvert(mesh); mesh->writeNative(argv[3]); mesh->destroyNative(); apf::destroyMesh(mesh); GM_release(simModel); Progress_delete(progress); SimModel_stop(); SimPartitionedMesh_stop(); Sim_unregisterAllKeys(); PCU_Comm_Free(); MPI_Finalize(); } <commit_msg>missing header in convert<commit_after>#include <PCU.h> #include <MeshSim.h> #include <SimPartitionedMesh.h> #include <SimUtil.h> #include <SimParasolidKrnl.h> #include <apfSIM.h> #include <apfMDS.h> #include <gmi_sim.h> #include <apf.h> #include <apfConvert.h> #include <apfMesh2.h> #include <ma.h> static void fixMatches(apf::Mesh2* m) { if (m->hasMatching()) { if (apf::alignMdsMatches(m)) printf("fixed misaligned matches\n"); else printf("matches were aligned\n"); assert( ! apf::alignMdsMatches(m)); } } static void fixPyramids(apf::Mesh2* m) { ma::Input* in = ma::configureIdentity(m); in->shouldCleanupLayer = true; ma::adapt(in); } static void postConvert(apf::Mesh2* m) { fixMatches(m); fixPyramids(m); m->verify(); } int main(int argc, char** argv) { MPI_Init(&argc, &argv); PCU_Comm_Init(); if (argc != 4) { if(0==PCU_Comm_Self()) std::cerr << "usage: " << argv[0] << " <model file> <simmetrix mesh> <scorec mesh>\n"; return EXIT_FAILURE; } Sim_readLicenseFile(NULL); SimPartitionedMesh_start(&argc,&argv); SimModel_start(); pProgress progress = Progress_new(); Progress_setDefaultCallback(progress); pGModel simModel; simModel = GM_load(argv[1], NULL, progress); pParMesh sim_mesh = PM_load(argv[2],sthreadNone,0,progress); apf::Mesh* simApfMesh = apf::createMesh(sim_mesh); gmi_register_sim(); gmi_model* mdl = gmi_import_sim(simModel); apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh); apf::destroyMesh(simApfMesh); M_release(sim_mesh); postConvert(mesh); mesh->writeNative(argv[3]); mesh->destroyNative(); apf::destroyMesh(mesh); GM_release(simModel); Progress_delete(progress); SimModel_stop(); SimPartitionedMesh_stop(); Sim_unregisterAllKeys(); PCU_Comm_Free(); MPI_Finalize(); } <|endoftext|>
<commit_before>#include <iostream> #include <osg/Array> #include <osg/BoundingSphere> #include <osg/BufferIndexBinding> #include <osg/BufferObject> #include <osg/Group> #include <osg/Math> #include <osg/MatrixTransform> #include <osg/Program> #include <osg/Shader> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgUtil/Optimizer> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> using namespace std; using namespace osg; // This example is based on the sample code in the // ARB_uniform_buffer_object extension specification. GLfloat colors1[] = { // block 0.45,0.45,1,1, 0.45,0.45,1,1, 0.75,0.75,0.75,1, 0.0,0.0,1.0,1, 0.0,1.0,0.0,1 }; GLfloat colors2[] = { // block 0.45,0.45,1,1, 0.45,0.45,1,1, 0.75,0.75,0.75,1, 1.0,0.0,0.0,1, 0.0,1.0,0.0,1, }; char vertexShaderSource[] = "// Vertex shader for Gooch shading\n" "// Author: Randi Rost\n" "// Copyright (c) 2002-2006 3Dlabs Inc. Ltd.\n" "// See 3Dlabs-License.txt for license information\n" "vec3 LightPosition = vec3(0.0, 10.0, 4.0); \n" "varying float NdotL;\n" "varying vec3 ReflectVec;\n" "varying vec3 ViewVec;\n" "void main(void)\n" "{\n" "vec3 ecPos = vec3 (gl_ModelViewMatrix * gl_Vertex);\n" "vec3 tnorm = normalize(gl_NormalMatrix * gl_Normal);\n" "vec3 lightVec = normalize(LightPosition - ecPos);\n" "ReflectVec = normalize(reflect(-lightVec, tnorm));\n" "ViewVec = normalize(-ecPos);\n" "NdotL = (dot(lightVec, tnorm) + 1.0) * 0.5;\n" "gl_Position = ftransform();\n" "}\n"; char fragmentShaderSource[] = "// Fragment shader for Gooch shading, adapted for ARB_uniform_buffer_object\n" "#extension GL_ARB_uniform_buffer_object : enable\n" "layout(std140) uniform colors0\n" "{\n" "float DiffuseCool;\n" "float DiffuseWarm;\n" "vec3 SurfaceColor;\n" "vec3 WarmColor;\n" "vec3 CoolColor;\n" "};\n" "varying float NdotL;\n" "varying vec3 ReflectVec;\n" "varying vec3 ViewVec;\n" "void main (void)\n" "{\n" "vec3 kcool = min(CoolColor + DiffuseCool * SurfaceColor, 1.0);\n" "vec3 kwarm = min(WarmColor + DiffuseWarm * SurfaceColor, 1.0); \n" "vec3 kfinal = mix(kcool, kwarm, NdotL);\n" "vec3 nreflect = normalize(ReflectVec);\n" "vec3 nview = normalize(ViewVec);\n" "float spec = max(dot(nreflect, nview), 0.0);\n" "spec = pow(spec, 32.0);\n" "gl_FragColor = vec4 (min(kfinal + spec, 1.0), 1.0);\n" "}\n"; // Callback for animating the WarmColor class UniformCallback : public StateAttributeCallback { public: void operator() (StateAttribute* attr, NodeVisitor* nv) { UniformBufferBinding* ubb = static_cast<UniformBufferBinding*>(attr); UniformBufferObject* ubo = static_cast<UniformBufferObject*>(ubb->getBufferObject()); FloatArray* array = static_cast<FloatArray*>(ubo->getBufferData(0)); double time = nv->getFrameStamp()->getSimulationTime(); double frac = fmod(time, 1.0); Vec4f warmColor = (Vec4f(0.0, 0.0, 1.0 ,1) * frac + Vec4f(1.0, 0.0, 0.0, 1) * (1 - frac)); // Since we're using the std140 layout, we know where the // warmColor variable is located in the buffer. for (int i = 0; i < 4; ++i) (*array)[12 + i] = warmColor[i]; array->dirty(); } }; int main(int argc, char** argv) { osg::ArgumentParser arguments(&argc,argv); osgViewer::Viewer viewer(arguments); if (arguments.argc() <= 1) { cerr << "Need a scene.\n"; return 1; } osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { cerr << "couldn't load " << argv[1] << "\n"; return 1; } osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); const BoundingSphere bound = loadedModel->getBound(); const float displacement = 2.25 * bound.radius(); Group* scene = new Group; StateSet* rootSS = scene->getOrCreateStateSet(); Shader* vertexShader = new Shader(Shader::VERTEX); vertexShader->setShaderSource(vertexShaderSource); Shader* fragmentShader = new Shader(Shader::FRAGMENT); fragmentShader->setShaderSource(fragmentShaderSource); Program* prog = new Program; prog->addShader(vertexShader); prog->addShader(fragmentShader); prog->addBindUniformBlock("colors0", 0); rootSS->setAttributeAndModes(prog, StateAttribute::ON); // Place 3 instances of the loaded model with different uniform // blocks for each. // // The blocksize is known because of the std140 format. const unsigned blockSize = 20 * sizeof(GLfloat); ref_ptr<FloatArray> colorArray = new FloatArray(&colors1[0], &colors1[sizeof(colors1) / sizeof(GLfloat)]); ref_ptr<UniformBufferObject> ubo = new UniformBufferObject; colorArray->setBufferObject(ubo.get()); Group* group1 = new Group; StateSet* ss1 = group1->getOrCreateStateSet(); group1->addChild(loadedModel.get()); scene->addChild(group1); ref_ptr<UniformBufferBinding> ubb1 = new UniformBufferBinding(0, ubo.get(), 0, blockSize); ss1->setAttributeAndModes(ubb1.get(), StateAttribute::ON); ref_ptr<FloatArray> colorArray2 = new FloatArray(&colors2[0], &colors2[sizeof(colors2) / sizeof(GLfloat)]); ref_ptr<UniformBufferObject> ubo2 = new UniformBufferObject; colorArray2->setBufferObject(ubo2.get()); MatrixTransform* group2 = new MatrixTransform; Matrix mat2 = Matrix::translate(-displacement, 0.0, 0.0); group2->setMatrix(mat2); StateSet* ss2 = group2->getOrCreateStateSet(); group2->addChild(loadedModel.get()); scene->addChild(group2); ref_ptr<UniformBufferBinding> ubb2 = new UniformBufferBinding(0, ubo2.get(), 0, blockSize); ss2->setAttributeAndModes(ubb2.get(), StateAttribute::ON); ref_ptr<FloatArray> colorArray3 = new FloatArray(&colors2[0], &colors2[sizeof(colors2) / sizeof(GLfloat)]); ref_ptr<UniformBufferObject> ubo3 = new UniformBufferObject; colorArray3->setBufferObject(ubo3.get()); MatrixTransform* group3 = new MatrixTransform; Matrix mat3 = Matrix::translate(displacement, 0.0, 0.0); group3->setMatrix(mat3); StateSet* ss3 = group3->getOrCreateStateSet(); group3->addChild(loadedModel.get()); scene->addChild(group3); ref_ptr<UniformBufferBinding> ubb3 = new UniformBufferBinding(0, ubo3.get(), 0, blockSize); ubb3->setUpdateCallback(new UniformCallback); ubb3->setDataVariance(Object::DYNAMIC); ss3->setAttributeAndModes(ubb3.get(), StateAttribute::ON); viewer.setSceneData(scene); viewer.realize(); return viewer.run(); } <commit_msg>Changed name of UniformCallback to UniformBufferCallback to avoid conflict with changes to come to the osg::Uniform::Callback -> osg::UniformCallback.<commit_after>#include <iostream> #include <osg/Array> #include <osg/BoundingSphere> #include <osg/BufferIndexBinding> #include <osg/BufferObject> #include <osg/Group> #include <osg/Math> #include <osg/MatrixTransform> #include <osg/Program> #include <osg/Shader> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgUtil/Optimizer> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> using namespace std; using namespace osg; // This example is based on the sample code in the // ARB_uniform_buffer_object extension specification. GLfloat colors1[] = { // block 0.45,0.45,1,1, 0.45,0.45,1,1, 0.75,0.75,0.75,1, 0.0,0.0,1.0,1, 0.0,1.0,0.0,1 }; GLfloat colors2[] = { // block 0.45,0.45,1,1, 0.45,0.45,1,1, 0.75,0.75,0.75,1, 1.0,0.0,0.0,1, 0.0,1.0,0.0,1, }; char vertexShaderSource[] = "// Vertex shader for Gooch shading\n" "// Author: Randi Rost\n" "// Copyright (c) 2002-2006 3Dlabs Inc. Ltd.\n" "// See 3Dlabs-License.txt for license information\n" "vec3 LightPosition = vec3(0.0, 10.0, 4.0); \n" "varying float NdotL;\n" "varying vec3 ReflectVec;\n" "varying vec3 ViewVec;\n" "void main(void)\n" "{\n" "vec3 ecPos = vec3 (gl_ModelViewMatrix * gl_Vertex);\n" "vec3 tnorm = normalize(gl_NormalMatrix * gl_Normal);\n" "vec3 lightVec = normalize(LightPosition - ecPos);\n" "ReflectVec = normalize(reflect(-lightVec, tnorm));\n" "ViewVec = normalize(-ecPos);\n" "NdotL = (dot(lightVec, tnorm) + 1.0) * 0.5;\n" "gl_Position = ftransform();\n" "}\n"; char fragmentShaderSource[] = "// Fragment shader for Gooch shading, adapted for ARB_uniform_buffer_object\n" "#extension GL_ARB_uniform_buffer_object : enable\n" "layout(std140) uniform colors0\n" "{\n" "float DiffuseCool;\n" "float DiffuseWarm;\n" "vec3 SurfaceColor;\n" "vec3 WarmColor;\n" "vec3 CoolColor;\n" "};\n" "varying float NdotL;\n" "varying vec3 ReflectVec;\n" "varying vec3 ViewVec;\n" "void main (void)\n" "{\n" "vec3 kcool = min(CoolColor + DiffuseCool * SurfaceColor, 1.0);\n" "vec3 kwarm = min(WarmColor + DiffuseWarm * SurfaceColor, 1.0); \n" "vec3 kfinal = mix(kcool, kwarm, NdotL);\n" "vec3 nreflect = normalize(ReflectVec);\n" "vec3 nview = normalize(ViewVec);\n" "float spec = max(dot(nreflect, nview), 0.0);\n" "spec = pow(spec, 32.0);\n" "gl_FragColor = vec4 (min(kfinal + spec, 1.0), 1.0);\n" "}\n"; // Callback for animating the WarmColor class UniformBufferCallback : public StateAttributeCallback { public: void operator() (StateAttribute* attr, NodeVisitor* nv) { UniformBufferBinding* ubb = static_cast<UniformBufferBinding*>(attr); UniformBufferObject* ubo = static_cast<UniformBufferObject*>(ubb->getBufferObject()); FloatArray* array = static_cast<FloatArray*>(ubo->getBufferData(0)); double time = nv->getFrameStamp()->getSimulationTime(); double frac = fmod(time, 1.0); Vec4f warmColor = (Vec4f(0.0, 0.0, 1.0 ,1) * frac + Vec4f(1.0, 0.0, 0.0, 1) * (1 - frac)); // Since we're using the std140 layout, we know where the // warmColor variable is located in the buffer. for (int i = 0; i < 4; ++i) (*array)[12 + i] = warmColor[i]; array->dirty(); } }; int main(int argc, char** argv) { osg::ArgumentParser arguments(&argc,argv); osgViewer::Viewer viewer(arguments); if (arguments.argc() <= 1) { cerr << "Need a scene.\n"; return 1; } osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { cerr << "couldn't load " << argv[1] << "\n"; return 1; } osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); const BoundingSphere bound = loadedModel->getBound(); const float displacement = 2.25 * bound.radius(); Group* scene = new Group; StateSet* rootSS = scene->getOrCreateStateSet(); Shader* vertexShader = new Shader(Shader::VERTEX); vertexShader->setShaderSource(vertexShaderSource); Shader* fragmentShader = new Shader(Shader::FRAGMENT); fragmentShader->setShaderSource(fragmentShaderSource); Program* prog = new Program; prog->addShader(vertexShader); prog->addShader(fragmentShader); prog->addBindUniformBlock("colors0", 0); rootSS->setAttributeAndModes(prog, StateAttribute::ON); // Place 3 instances of the loaded model with different uniform // blocks for each. // // The blocksize is known because of the std140 format. const unsigned blockSize = 20 * sizeof(GLfloat); ref_ptr<FloatArray> colorArray = new FloatArray(&colors1[0], &colors1[sizeof(colors1) / sizeof(GLfloat)]); ref_ptr<UniformBufferObject> ubo = new UniformBufferObject; colorArray->setBufferObject(ubo.get()); Group* group1 = new Group; StateSet* ss1 = group1->getOrCreateStateSet(); group1->addChild(loadedModel.get()); scene->addChild(group1); ref_ptr<UniformBufferBinding> ubb1 = new UniformBufferBinding(0, ubo.get(), 0, blockSize); ss1->setAttributeAndModes(ubb1.get(), StateAttribute::ON); ref_ptr<FloatArray> colorArray2 = new FloatArray(&colors2[0], &colors2[sizeof(colors2) / sizeof(GLfloat)]); ref_ptr<UniformBufferObject> ubo2 = new UniformBufferObject; colorArray2->setBufferObject(ubo2.get()); MatrixTransform* group2 = new MatrixTransform; Matrix mat2 = Matrix::translate(-displacement, 0.0, 0.0); group2->setMatrix(mat2); StateSet* ss2 = group2->getOrCreateStateSet(); group2->addChild(loadedModel.get()); scene->addChild(group2); ref_ptr<UniformBufferBinding> ubb2 = new UniformBufferBinding(0, ubo2.get(), 0, blockSize); ss2->setAttributeAndModes(ubb2.get(), StateAttribute::ON); ref_ptr<FloatArray> colorArray3 = new FloatArray(&colors2[0], &colors2[sizeof(colors2) / sizeof(GLfloat)]); ref_ptr<UniformBufferObject> ubo3 = new UniformBufferObject; colorArray3->setBufferObject(ubo3.get()); MatrixTransform* group3 = new MatrixTransform; Matrix mat3 = Matrix::translate(displacement, 0.0, 0.0); group3->setMatrix(mat3); StateSet* ss3 = group3->getOrCreateStateSet(); group3->addChild(loadedModel.get()); scene->addChild(group3); ref_ptr<UniformBufferBinding> ubb3 = new UniformBufferBinding(0, ubo3.get(), 0, blockSize); ubb3->setUpdateCallback(new UniformBufferCallback); ubb3->setDataVariance(Object::DYNAMIC); ss3->setAttributeAndModes(ubb3.get(), StateAttribute::ON); viewer.setSceneData(scene); viewer.realize(); return viewer.run(); } <|endoftext|>
<commit_before>/** * Copyright 2016 Pivotal Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #ifndef QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HPP_ #define QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HPP_ #include <string> #include <vector> #include "expressions/table_generator/GeneratorFunction.hpp" #include "expressions/table_generator/GeneratorFunctionHandle.hpp" #include "expressions/table_generator/GenerateSeriesHandle.hpp" #include "types/Type.hpp" #include "types/TypedValue.hpp" #include "types/TypeFactory.hpp" #include "types/operations/comparisons/GreaterComparison.hpp" #include "utility/Macros.hpp" namespace quickstep { /** \addtogroup Expressions * @{ */ /** * @brief GeneratorFunction that generates a series of values, from a start * value to a stop value with a step size. */ class GenerateSeries : public GeneratorFunction { public: /** * @brief Singleton instance of the GenerateSeries class. * @return a const reference to the singleton instance of the GenerateSeries * class. */ static const GenerateSeries& Instance() { static GenerateSeries instance; return instance; } std::string getName() const override { return "generate_series"; } GeneratorFunctionHandlePtr createHandle( const std::vector<TypedValue> &arguments) const override { // Checks arguments and create the function handle for generate_series. // Arguments should have the pattern (start, end) or (start, end, step). int arg_size = arguments.size(); if (arg_size != 2 && arg_size != 3) { throw GeneratorFunctionInvalidArguments("Invalid number of arguments"); } std::vector<const Type*> arg_types; for (const TypedValue &arg : arguments) { if (TypeFactory::TypeRequiresLengthParameter(arg.getTypeID())) { throw GeneratorFunctionInvalidArguments("Invalid argument types"); } arg_types.emplace_back(&TypeFactory::GetType(arg.getTypeID())); } // Get the unified type of all arguments. const Type *unified_type = arg_types[0]; for (int i = 1; i < arg_size && unified_type != nullptr; i++) { unified_type = TypeFactory::GetUnifyingType(*arg_types[i], *unified_type); } // Check if the unified type if applicable, then create the handle. if (unified_type != nullptr) { TypeID tid = unified_type->getTypeID(); if (tid == TypeID::kInt || tid == TypeID::kLong || tid == TypeID::kFloat || tid == TypeID::kDouble) { return concretizeWithType(arg_types, arguments, *unified_type); } } throw GeneratorFunctionInvalidArguments("Invalid argument types"); return nullptr; } protected: GenerateSeries() : GeneratorFunction() { } private: GeneratorFunctionHandlePtr concretizeWithType( const std::vector<const Type*> &arg_types, const std::vector<TypedValue> &args, const Type &type) const { DCHECK(args.size() == 2 || args.size() == 3); // Coerce all arguments to the unified type. TypedValue start = type.coerceValue(args[0], *arg_types[0]); TypedValue end = type.coerceValue(args[1], *arg_types[1]); TypedValue step = args.size() > 2 ? type.coerceValue(args[2], *arg_types[2]) : type.coerceValue(TypedValue(1), TypeFactory::GetType(TypeID::kInt)); // Check that step is not 0, and (end - start) / step is positive const GreaterComparison &gt_comparator = GreaterComparison::Instance(); bool start_gt_end = gt_comparator.compareTypedValuesChecked(start, type, end, type); bool step_gt_0 = gt_comparator.compareTypedValuesChecked( step, type, TypedValue(0), TypeFactory::GetType(TypeID::kInt)); bool step_lt_0 = gt_comparator.compareTypedValuesChecked( TypedValue(0), TypeFactory::GetType(TypeID::kInt), step, type); if ((!start_gt_end && step_lt_0) || (start_gt_end && step_gt_0)) { throw GeneratorFunctionInvalidArguments("Invalid step width"); } return GeneratorFunctionHandlePtr( new GenerateSeriesHandle(getName(), args, type, start, end, step)); } DISALLOW_COPY_AND_ASSIGN(GenerateSeries); }; /** @} */ } // namespace quickstep #endif /* QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HPP_ */ <commit_msg>make_travis_ci_start_building<commit_after>/** * Copyright 2016 Pivotal Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #ifndef QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HPP_ #define QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HPP_ #include <string> #include <vector> #include "expressions/table_generator/GeneratorFunction.hpp" #include "expressions/table_generator/GeneratorFunctionHandle.hpp" #include "expressions/table_generator/GenerateSeriesHandle.hpp" #include "types/Type.hpp" #include "types/TypedValue.hpp" #include "types/TypeFactory.hpp" #include "types/operations/comparisons/GreaterComparison.hpp" #include "utility/Macros.hpp" namespace quickstep { /** \addtogroup Expressions * @{ */ /** * @brief GeneratorFunction that generates a series of values, from a start * value to a stop value with a step size. */ class GenerateSeries : public GeneratorFunction { public: /** * @brief Singleton instance of the GenerateSeries class. * @return A const reference to the singleton instance of the GenerateSeries * class. */ static const GenerateSeries& Instance() { static GenerateSeries instance; return instance; } std::string getName() const override { return "generate_series"; } GeneratorFunctionHandlePtr createHandle( const std::vector<TypedValue> &arguments) const override { // Checks arguments and create the function handle for generate_series. // Arguments should have the pattern (start, end) or (start, end, step). int arg_size = arguments.size(); if (arg_size != 2 && arg_size != 3) { throw GeneratorFunctionInvalidArguments("Invalid number of arguments"); } std::vector<const Type*> arg_types; for (const TypedValue &arg : arguments) { if (TypeFactory::TypeRequiresLengthParameter(arg.getTypeID())) { throw GeneratorFunctionInvalidArguments("Invalid argument types"); } arg_types.emplace_back(&TypeFactory::GetType(arg.getTypeID())); } // Get the unified type of all arguments. const Type *unified_type = arg_types[0]; for (int i = 1; i < arg_size && unified_type != nullptr; i++) { unified_type = TypeFactory::GetUnifyingType(*arg_types[i], *unified_type); } // Check if the unified type if applicable, then create the handle. if (unified_type != nullptr) { TypeID tid = unified_type->getTypeID(); if (tid == TypeID::kInt || tid == TypeID::kLong || tid == TypeID::kFloat || tid == TypeID::kDouble) { return concretizeWithType(arg_types, arguments, *unified_type); } } throw GeneratorFunctionInvalidArguments("Invalid argument types"); return nullptr; } protected: GenerateSeries() : GeneratorFunction() { } private: GeneratorFunctionHandlePtr concretizeWithType( const std::vector<const Type*> &arg_types, const std::vector<TypedValue> &args, const Type &type) const { DCHECK(args.size() == 2 || args.size() == 3); // Coerce all arguments to the unified type. TypedValue start = type.coerceValue(args[0], *arg_types[0]); TypedValue end = type.coerceValue(args[1], *arg_types[1]); TypedValue step = args.size() > 2 ? type.coerceValue(args[2], *arg_types[2]) : type.coerceValue(TypedValue(1), TypeFactory::GetType(TypeID::kInt)); // Check that step is not 0, and (end - start) / step is positive const GreaterComparison &gt_comparator = GreaterComparison::Instance(); bool start_gt_end = gt_comparator.compareTypedValuesChecked(start, type, end, type); bool step_gt_0 = gt_comparator.compareTypedValuesChecked( step, type, TypedValue(0), TypeFactory::GetType(TypeID::kInt)); bool step_lt_0 = gt_comparator.compareTypedValuesChecked( TypedValue(0), TypeFactory::GetType(TypeID::kInt), step, type); if ((!start_gt_end && step_lt_0) || (start_gt_end && step_gt_0)) { throw GeneratorFunctionInvalidArguments("Invalid step width"); } return GeneratorFunctionHandlePtr( new GenerateSeriesHandle(getName(), args, type, start, end, step)); } DISALLOW_COPY_AND_ASSIGN(GenerateSeries); }; /** @} */ } // namespace quickstep #endif /* QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HPP_ */ <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE FastFourierTransform #include <boost/test/unit_test.hpp> #include <vexcl/vector.hpp> #include <vexcl/fft.hpp> #include <vexcl/random.hpp> #include <vexcl/element_index.hpp> #include <vexcl/reductor.hpp> #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(transform_expression) { const size_t N = 1024; std::vector<vex::backend::command_queue> queue(1, ctx.queue(0)); vex::vector<cl_float> data(queue, N); vex::FFT<cl_float> fft(queue, N); // should compile data += fft(data * data) * 5; } BOOST_AUTO_TEST_CASE(check_correctness) { const size_t N = 1024; std::vector<vex::backend::command_queue> queue(1, ctx.queue(0)); vex::vector<cl_double> in (queue, N); vex::vector<cl_double2> out (queue, N); vex::vector<cl_double> back(queue, N); vex::Random<cl_double> rnd; in = rnd(vex::element_index(), std::rand()); vex::FFT<cl_double, cl_double2> fft (queue, N); vex::FFT<cl_double2, cl_double > ifft(queue, N, vex::fft::inverse); out = fft (in ); back = ifft(out); vex::Reductor<cl_double, vex::SUM> sum(queue); BOOST_CHECK(std::sqrt(sum(pow(in - back, 2.0f)) / N) < 1e-3); } void test(const vex::Context &ctx, std::vector<size_t> ns, size_t batch) { std::cout << "FFT(C2C) size=" << ns[0]; for(size_t i = 1; i < ns.size(); i++) std::cout << 'x' << ns[i]; std::cout << " batch=" << batch << std::endl; std::vector<vex::backend::command_queue> queue(1, ctx.queue(0)); size_t n1 = std::accumulate(ns.begin(), ns.end(), static_cast<size_t>(1), std::multiplies<size_t>()); size_t n = n1 * batch; // random data. std::vector<cl_double2> inp_h = random_vector<cl_double2>(n); // test vex::vector<cl_double2> inp (queue, inp_h); vex::vector<cl_double2> out (queue, n); vex::vector<cl_double2> back(queue, n); std::vector<size_t> ns_(ns.begin(), ns.end()); std::vector<vex::fft::direction> dirs (ns.size(), vex::fft::forward); std::vector<vex::fft::direction> idirs(ns.size(), vex::fft::inverse); if(batch != 1) { ns_.insert(ns_.begin(), batch); dirs.insert(dirs.begin(), vex::fft::none); idirs.insert(idirs.begin(), vex::fft::none); } vex::FFT<cl_double2> fft (queue, ns_, dirs); vex::FFT<cl_double2> ifft(queue, ns_, idirs); out = fft (inp); back = ifft(out); auto rms = [&](const vex::vector<cl_double2> &a, const vex::vector<cl_double2> &b) -> double { // Required for CUDA compatibility: VEX_FUNCTION(cl_double2, minus, (cl_double2, a)(cl_double2, b), double2 r = {a.x - b.x, a.y - b.y}; return r; ); VEX_FUNCTION(double, dot2, (cl_double2, a)(cl_double2, b), return a.x * b.x + a.y * b.y; ); static vex::Reductor<double, vex::SUM> sum(queue); return std::sqrt(sum(dot2(minus(a, b), minus(a, b)))) / std::sqrt(sum(dot2(b, b))); }; BOOST_CHECK_SMALL(rms(back, inp), 1e-8); } // random dimension, mostly 1. size_t random_dim(double p, double s) { static std::default_random_engine rng( std::rand() ); static std::uniform_real_distribution<double> rnd(0.0, 1.0); return 1 + static_cast<size_t>( s * std::pow(rnd(rng), p) ); } BOOST_AUTO_TEST_CASE(test_dimensions) { #ifndef VEXCL_BACKEND_CUDA // TODO: POCL fails this test. if (vex::Filter::Platform("Portable Computing Language")(ctx.device(0))) return; #endif const size_t max = 1 << 12; vex::fft::planner p; for(size_t i = 0; i < 100; ++i) { // random number of dimensions, mostly 1. size_t dims = random_dim(3, 5); size_t batch = random_dim(5, 100); // random size. std::vector<size_t> n; size_t d_max = static_cast<size_t>(std::pow(static_cast<double>(max), 1.0 / dims)); size_t total = batch; for(size_t d = 0 ; d < dims ; d++) { size_t sz = random_dim(dims == 1 ? 3 : 1, static_cast<double>(d_max)); if(rand() % 3 != 0) sz = p.best_size(sz); n.push_back(sz); total *= sz; } // run if(total <= max) test(ctx, n, batch); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Fix mixed precision bug in last commit<commit_after>#define BOOST_TEST_MODULE FastFourierTransform #include <boost/test/unit_test.hpp> #include <vexcl/vector.hpp> #include <vexcl/fft.hpp> #include <vexcl/random.hpp> #include <vexcl/element_index.hpp> #include <vexcl/reductor.hpp> #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(transform_expression) { const size_t N = 1024; std::vector<vex::backend::command_queue> queue(1, ctx.queue(0)); vex::vector<cl_float> data(queue, N); vex::FFT<cl_float> fft(queue, N); // should compile data += fft(data * data) * 5; } BOOST_AUTO_TEST_CASE(check_correctness) { const size_t N = 1024; std::vector<vex::backend::command_queue> queue(1, ctx.queue(0)); vex::vector<cl_double> in (queue, N); vex::vector<cl_double2> out (queue, N); vex::vector<cl_double> back(queue, N); vex::Random<cl_double> rnd; in = rnd(vex::element_index(), std::rand()); vex::FFT<cl_double, cl_double2> fft (queue, N); vex::FFT<cl_double2, cl_double > ifft(queue, N, vex::fft::inverse); out = fft (in ); back = ifft(out); vex::Reductor<cl_double, vex::SUM> sum(queue); BOOST_CHECK(std::sqrt(sum(pow(in - back, 2.0)) / N) < 1e-3); } void test(const vex::Context &ctx, std::vector<size_t> ns, size_t batch) { std::cout << "FFT(C2C) size=" << ns[0]; for(size_t i = 1; i < ns.size(); i++) std::cout << 'x' << ns[i]; std::cout << " batch=" << batch << std::endl; std::vector<vex::backend::command_queue> queue(1, ctx.queue(0)); size_t n1 = std::accumulate(ns.begin(), ns.end(), static_cast<size_t>(1), std::multiplies<size_t>()); size_t n = n1 * batch; // random data. std::vector<cl_double2> inp_h = random_vector<cl_double2>(n); // test vex::vector<cl_double2> inp (queue, inp_h); vex::vector<cl_double2> out (queue, n); vex::vector<cl_double2> back(queue, n); std::vector<size_t> ns_(ns.begin(), ns.end()); std::vector<vex::fft::direction> dirs (ns.size(), vex::fft::forward); std::vector<vex::fft::direction> idirs(ns.size(), vex::fft::inverse); if(batch != 1) { ns_.insert(ns_.begin(), batch); dirs.insert(dirs.begin(), vex::fft::none); idirs.insert(idirs.begin(), vex::fft::none); } vex::FFT<cl_double2> fft (queue, ns_, dirs); vex::FFT<cl_double2> ifft(queue, ns_, idirs); out = fft (inp); back = ifft(out); auto rms = [&](const vex::vector<cl_double2> &a, const vex::vector<cl_double2> &b) -> double { // Required for CUDA compatibility: VEX_FUNCTION(cl_double2, minus, (cl_double2, a)(cl_double2, b), double2 r = {a.x - b.x, a.y - b.y}; return r; ); VEX_FUNCTION(double, dot2, (cl_double2, a)(cl_double2, b), return a.x * b.x + a.y * b.y; ); static vex::Reductor<double, vex::SUM> sum(queue); return std::sqrt(sum(dot2(minus(a, b), minus(a, b)))) / std::sqrt(sum(dot2(b, b))); }; BOOST_CHECK_SMALL(rms(back, inp), 1e-8); } // random dimension, mostly 1. size_t random_dim(double p, double s) { static std::default_random_engine rng( std::rand() ); static std::uniform_real_distribution<double> rnd(0.0, 1.0); return 1 + static_cast<size_t>( s * std::pow(rnd(rng), p) ); } BOOST_AUTO_TEST_CASE(test_dimensions) { #ifndef VEXCL_BACKEND_CUDA // TODO: POCL fails this test. if (vex::Filter::Platform("Portable Computing Language")(ctx.device(0))) return; #endif const size_t max = 1 << 12; vex::fft::planner p; for(size_t i = 0; i < 100; ++i) { // random number of dimensions, mostly 1. size_t dims = random_dim(3, 5); size_t batch = random_dim(5, 100); // random size. std::vector<size_t> n; size_t d_max = static_cast<size_t>(std::pow(static_cast<double>(max), 1.0 / dims)); size_t total = batch; for(size_t d = 0 ; d < dims ; d++) { size_t sz = random_dim(dims == 1 ? 3 : 1, static_cast<double>(d_max)); if(rand() % 3 != 0) sz = p.best_size(sz); n.push_back(sz); total *= sz; } // run if(total <= max) test(ctx, n, batch); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "coroutine.h" #include "gtest\gtest.h" void deterministic_test(void* arg) { context* ctx = static_cast<context*>(arg); for (uintptr_t i = 0; i < 64; ++i) { coroutine_yield(ctx, reinterpret_cast<void*>(i)); } } TEST(run, yield_unmodified) { context* ctx = coroutine_start({ 16382, &deterministic_test }); EXPECT_EQ(0, reinterpret_cast<uintptr_t>(coroutine_next(ctx, ctx))); for (uintptr_t i = 1; i < 64; ++i) { EXPECT_EQ(i, reinterpret_cast<uintptr_t>( coroutine_next(ctx, reinterpret_cast<void*>(i)) )); } } <commit_msg>Added more unit tests<commit_after>#include "coroutine.h" #include "gtest\gtest.h" #include <utility> void deterministic_test(void* arg) { context* ctx = static_cast<context*>(arg); for (uintptr_t i = 0; i < 64; ++i) { coroutine_yield(ctx, reinterpret_cast<void*>(i)); } } void set_var(void* arg) { std::pair<context*, int*>* vals = (std::pair<context*, int*>*)arg; coroutine_yield(vals->first, nullptr); *vals->second = 0xFFF; } TEST(run, yield_unmodified) { context* ctx = coroutine_start({ 16382, &deterministic_test }); EXPECT_EQ(0, reinterpret_cast<uintptr_t>(coroutine_next(ctx, ctx))); for (uintptr_t i = 1; i < 64; ++i) { EXPECT_EQ(i, reinterpret_cast<uintptr_t>( coroutine_next(ctx, reinterpret_cast<void*>(i)) )); } } TEST(run, destroy_completes_coroutine) { int r = 0; std::pair<context*, int*> pair; pair.first = coroutine_start({ 16382, &set_var }); pair.second = &r; coroutine_next(pair.first, &pair); coroutine_destroy(pair.first, nullptr); ASSERT_EQ(pair.second, 0xFFF); } TEST(run, abort_does_not_complete) { int r = 0; std::pair<context*, int*> pair; pair.first = coroutine_start({ 16382, &set_var }); pair.second = &r; coroutine_next(pair.first, &pair); coroutine_abort(pair.first); ASSERT_NE(pair.second, 0xFFF); } <|endoftext|>
<commit_before>/* * VHDL code generation for LPM devices. * * Copyright (C) 2008 Nick Gasson ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "vhdl_target.h" #include <iostream> #include <cassert> /* * Return the base of a part select. */ static vhdl_expr *part_select_base(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_expr *off; ivl_nexus_t base = ivl_lpm_data(lpm, 1); if (base != NULL) off = nexus_to_var_ref(scope, base); else off = new vhdl_const_int(ivl_lpm_base(lpm)); // Array indexes must be integers vhdl_type integer(VHDL_TYPE_INTEGER); return off->cast(&integer); } static vhdl_expr *concat_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_type *result_type = vhdl_type::type_for(ivl_lpm_width(lpm), ivl_lpm_signed(lpm) != 0); vhdl_binop_expr *expr = new vhdl_binop_expr(VHDL_BINOP_CONCAT, result_type); for (int i = ivl_lpm_selects(lpm) - 1; i >= 0; i--) { vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i)); if (NULL == e) return NULL; expr->add_expr(e); } return expr; } static vhdl_expr *binop_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t op) { unsigned out_width = ivl_lpm_width(lpm); vhdl_type *result_type = vhdl_type::type_for(out_width, ivl_lpm_signed(lpm) != 0); vhdl_binop_expr *expr = new vhdl_binop_expr(op, result_type); for (int i = 0; i < 2; i++) { vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i)); if (NULL == e) return NULL; expr->add_expr(e->cast(result_type)); } if (op == VHDL_BINOP_MULT) { // Need to resize the output to the desired size, // as this does not happen automatically in VHDL vhdl_fcall *resize = new vhdl_fcall("Resize", vhdl_type::nsigned(out_width)); resize->add_expr(expr); resize->add_expr(new vhdl_const_int(out_width)); return resize; } else return expr; } static vhdl_expr *rel_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t op) { vhdl_binop_expr *expr = new vhdl_binop_expr(op, vhdl_type::boolean()); for (int i = 0; i < 2; i++) { vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i)); if (NULL == e) return NULL; expr->add_expr(e); } // Need to make sure output is std_logic rather than Boolean vhdl_type std_logic(VHDL_TYPE_STD_LOGIC); return expr->cast(&std_logic); } static vhdl_expr *part_select_vp_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_var_ref *selfrom = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); if (NULL == selfrom) return NULL; vhdl_expr *off = part_select_base(scope, lpm);; if (NULL == off) return NULL; selfrom->set_slice(off, ivl_lpm_width(lpm) - 1); return selfrom; } static vhdl_expr *part_select_pv_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { return nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); } static vhdl_expr *ufunc_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { ivl_scope_t f_scope = ivl_lpm_define(lpm); vhdl_fcall *fcall = new vhdl_fcall(ivl_scope_basename(f_scope), NULL); for (unsigned i = 0; i < ivl_lpm_size(lpm); i++) { vhdl_var_ref *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i)); if (NULL == ref) return NULL; fcall->add_expr(ref); } return fcall; } static vhdl_expr *reduction_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, support_function_t f, bool invert) { vhdl_var_ref *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); if (NULL == ref) return NULL; vhdl_expr *result; if (ref->get_type()->get_name() == VHDL_TYPE_STD_LOGIC) result = ref; else { require_support_function(f); vhdl_fcall *fcall = new vhdl_fcall(support_function::function_name(f), vhdl_type::std_logic()); vhdl_type std_logic_vector(VHDL_TYPE_STD_LOGIC_VECTOR); fcall->add_expr(ref->cast(&std_logic_vector)); result = fcall; } if (invert) return new vhdl_unaryop_expr (VHDL_UNARYOP_NOT, result, vhdl_type::std_logic()); else return result; } static vhdl_expr *sign_extend_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_expr *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); if (ref) return ref->resize(ivl_lpm_width(lpm)); else return NULL; } static vhdl_expr *array_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { ivl_signal_t array = ivl_lpm_array(lpm); if (!seen_signal_before(array)) return NULL; const char *renamed = get_renamed_signal(array).c_str(); vhdl_decl *adecl = scope->get_decl(renamed); assert(adecl); vhdl_type *atype = new vhdl_type(*adecl->get_type()); vhdl_expr *select = nexus_to_var_ref(scope, ivl_lpm_select(lpm)); if (NULL == select) return NULL; vhdl_var_ref *ref = new vhdl_var_ref(renamed, atype); vhdl_type integer(VHDL_TYPE_INTEGER); ref->set_slice(select->cast(&integer)); return ref; } static vhdl_expr *shift_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t shift_op) { vhdl_expr *lhs = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); vhdl_expr *rhs = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 1)); if (!lhs || !rhs) return NULL; // The RHS must be an integer vhdl_type integer(VHDL_TYPE_INTEGER); vhdl_expr *r_cast = rhs->cast(&integer); vhdl_type *rtype = new vhdl_type(*lhs->get_type()); return new vhdl_binop_expr(lhs, shift_op, r_cast, rtype); } static vhdl_expr *repeat_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_expr *in = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); return new vhdl_bit_spec_expr(NULL, in); } static vhdl_expr *lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { switch (ivl_lpm_type(lpm)) { case IVL_LPM_ADD: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_ADD); case IVL_LPM_SUB: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_SUB); case IVL_LPM_MULT: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_MULT); case IVL_LPM_DIVIDE: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_DIV); case IVL_LPM_MOD: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_MOD); case IVL_LPM_CONCAT: return concat_lpm_to_expr(scope, lpm); case IVL_LPM_CMP_GE: return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_GEQ); case IVL_LPM_CMP_GT: return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_GT); case IVL_LPM_CMP_NE: case IVL_LPM_CMP_NEE: return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_NEQ); case IVL_LPM_CMP_EQ: case IVL_LPM_CMP_EEQ: return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_EQ); case IVL_LPM_PART_VP: return part_select_vp_lpm_to_expr(scope, lpm); case IVL_LPM_PART_PV: return part_select_pv_lpm_to_expr(scope, lpm); case IVL_LPM_UFUNC: return ufunc_lpm_to_expr(scope, lpm); case IVL_LPM_RE_AND: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_AND, false); case IVL_LPM_RE_NAND: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_AND, true); case IVL_LPM_RE_NOR: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_OR, true); case IVL_LPM_RE_OR: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_OR, false); case IVL_LPM_RE_XOR: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_XOR, false); case IVL_LPM_RE_XNOR: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_XOR, true); case IVL_LPM_SIGN_EXT: return sign_extend_lpm_to_expr(scope, lpm); case IVL_LPM_ARRAY: return array_lpm_to_expr(scope, lpm); case IVL_LPM_SHIFTL: return shift_lpm_to_expr(scope, lpm, VHDL_BINOP_SL); case IVL_LPM_SHIFTR: return shift_lpm_to_expr(scope, lpm, VHDL_BINOP_SR); case IVL_LPM_REPEAT: return repeat_lpm_to_expr(scope, lpm); default: error("Unsupported LPM type: %d", ivl_lpm_type(lpm)); return NULL; } } static int draw_mux_lpm(vhdl_arch *arch, ivl_lpm_t lpm) { int nselects = ivl_lpm_selects(lpm); if (nselects > 1) { error("Only 1 LPM select bit supported at the moment"); return 1; } vhdl_scope *scope = arch->get_scope(); vhdl_expr *s0 = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); vhdl_expr *s1 = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 1)); vhdl_expr *sel = nexus_to_var_ref(scope, ivl_lpm_select(lpm)); vhdl_expr *b1 = new vhdl_const_bit('1'); vhdl_expr *t1 = new vhdl_binop_expr(sel, VHDL_BINOP_EQ, b1, vhdl_type::boolean()); vhdl_var_ref *out = nexus_to_var_ref(scope, ivl_lpm_q(lpm, 0)); vhdl_cassign_stmt *s = new vhdl_cassign_stmt(out, s0); s->add_condition(s1, t1); arch->add_stmt(s); return 0; } int draw_lpm(vhdl_arch *arch, ivl_lpm_t lpm) { if (ivl_lpm_type(lpm) == IVL_LPM_MUX) return draw_mux_lpm(arch, lpm); vhdl_expr *f = lpm_to_expr(arch->get_scope(), lpm); if (NULL == f) return 1; vhdl_var_ref *out = nexus_to_var_ref(arch->get_scope(), ivl_lpm_q(lpm, 0)); if (ivl_lpm_type(lpm) == IVL_LPM_PART_PV) { vhdl_expr *off = part_select_base(arch->get_scope(), lpm); assert(off); out->set_slice(off, ivl_lpm_width(lpm) - 1); } arch->add_stmt(new vhdl_cassign_stmt(out, f->cast(out->get_type()))); return 0; } <commit_msg>Fix IVL_LPM_MUX where inputs are different signedness to outputs<commit_after>/* * VHDL code generation for LPM devices. * * Copyright (C) 2008 Nick Gasson ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "vhdl_target.h" #include <iostream> #include <cassert> /* * Return the base of a part select. */ static vhdl_expr *part_select_base(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_expr *off; ivl_nexus_t base = ivl_lpm_data(lpm, 1); if (base != NULL) off = nexus_to_var_ref(scope, base); else off = new vhdl_const_int(ivl_lpm_base(lpm)); // Array indexes must be integers vhdl_type integer(VHDL_TYPE_INTEGER); return off->cast(&integer); } static vhdl_expr *concat_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_type *result_type = vhdl_type::type_for(ivl_lpm_width(lpm), ivl_lpm_signed(lpm) != 0); vhdl_binop_expr *expr = new vhdl_binop_expr(VHDL_BINOP_CONCAT, result_type); for (int i = ivl_lpm_selects(lpm) - 1; i >= 0; i--) { vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i)); if (NULL == e) return NULL; expr->add_expr(e); } return expr; } static vhdl_expr *binop_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t op) { unsigned out_width = ivl_lpm_width(lpm); vhdl_type *result_type = vhdl_type::type_for(out_width, ivl_lpm_signed(lpm) != 0); vhdl_binop_expr *expr = new vhdl_binop_expr(op, result_type); for (int i = 0; i < 2; i++) { vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i)); if (NULL == e) return NULL; expr->add_expr(e->cast(result_type)); } if (op == VHDL_BINOP_MULT) { // Need to resize the output to the desired size, // as this does not happen automatically in VHDL vhdl_fcall *resize = new vhdl_fcall("Resize", vhdl_type::nsigned(out_width)); resize->add_expr(expr); resize->add_expr(new vhdl_const_int(out_width)); return resize; } else return expr; } static vhdl_expr *rel_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t op) { vhdl_binop_expr *expr = new vhdl_binop_expr(op, vhdl_type::boolean()); for (int i = 0; i < 2; i++) { vhdl_expr *e = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i)); if (NULL == e) return NULL; expr->add_expr(e); } // Need to make sure output is std_logic rather than Boolean vhdl_type std_logic(VHDL_TYPE_STD_LOGIC); return expr->cast(&std_logic); } static vhdl_expr *part_select_vp_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_var_ref *selfrom = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); if (NULL == selfrom) return NULL; vhdl_expr *off = part_select_base(scope, lpm);; if (NULL == off) return NULL; selfrom->set_slice(off, ivl_lpm_width(lpm) - 1); return selfrom; } static vhdl_expr *part_select_pv_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { return nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); } static vhdl_expr *ufunc_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { ivl_scope_t f_scope = ivl_lpm_define(lpm); vhdl_fcall *fcall = new vhdl_fcall(ivl_scope_basename(f_scope), NULL); for (unsigned i = 0; i < ivl_lpm_size(lpm); i++) { vhdl_var_ref *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, i)); if (NULL == ref) return NULL; fcall->add_expr(ref); } return fcall; } static vhdl_expr *reduction_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, support_function_t f, bool invert) { vhdl_var_ref *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); if (NULL == ref) return NULL; vhdl_expr *result; if (ref->get_type()->get_name() == VHDL_TYPE_STD_LOGIC) result = ref; else { require_support_function(f); vhdl_fcall *fcall = new vhdl_fcall(support_function::function_name(f), vhdl_type::std_logic()); vhdl_type std_logic_vector(VHDL_TYPE_STD_LOGIC_VECTOR); fcall->add_expr(ref->cast(&std_logic_vector)); result = fcall; } if (invert) return new vhdl_unaryop_expr (VHDL_UNARYOP_NOT, result, vhdl_type::std_logic()); else return result; } static vhdl_expr *sign_extend_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_expr *ref = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); if (ref) return ref->resize(ivl_lpm_width(lpm)); else return NULL; } static vhdl_expr *array_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { ivl_signal_t array = ivl_lpm_array(lpm); if (!seen_signal_before(array)) return NULL; const char *renamed = get_renamed_signal(array).c_str(); vhdl_decl *adecl = scope->get_decl(renamed); assert(adecl); vhdl_type *atype = new vhdl_type(*adecl->get_type()); vhdl_expr *select = nexus_to_var_ref(scope, ivl_lpm_select(lpm)); if (NULL == select) return NULL; vhdl_var_ref *ref = new vhdl_var_ref(renamed, atype); vhdl_type integer(VHDL_TYPE_INTEGER); ref->set_slice(select->cast(&integer)); return ref; } static vhdl_expr *shift_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm, vhdl_binop_t shift_op) { vhdl_expr *lhs = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); vhdl_expr *rhs = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 1)); if (!lhs || !rhs) return NULL; // The RHS must be an integer vhdl_type integer(VHDL_TYPE_INTEGER); vhdl_expr *r_cast = rhs->cast(&integer); vhdl_type *rtype = new vhdl_type(*lhs->get_type()); return new vhdl_binop_expr(lhs, shift_op, r_cast, rtype); } static vhdl_expr *repeat_lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { vhdl_expr *in = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); return new vhdl_bit_spec_expr(NULL, in); } static vhdl_expr *lpm_to_expr(vhdl_scope *scope, ivl_lpm_t lpm) { switch (ivl_lpm_type(lpm)) { case IVL_LPM_ADD: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_ADD); case IVL_LPM_SUB: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_SUB); case IVL_LPM_MULT: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_MULT); case IVL_LPM_DIVIDE: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_DIV); case IVL_LPM_MOD: return binop_lpm_to_expr(scope, lpm, VHDL_BINOP_MOD); case IVL_LPM_CONCAT: return concat_lpm_to_expr(scope, lpm); case IVL_LPM_CMP_GE: return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_GEQ); case IVL_LPM_CMP_GT: return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_GT); case IVL_LPM_CMP_NE: case IVL_LPM_CMP_NEE: return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_NEQ); case IVL_LPM_CMP_EQ: case IVL_LPM_CMP_EEQ: return rel_lpm_to_expr(scope, lpm, VHDL_BINOP_EQ); case IVL_LPM_PART_VP: return part_select_vp_lpm_to_expr(scope, lpm); case IVL_LPM_PART_PV: return part_select_pv_lpm_to_expr(scope, lpm); case IVL_LPM_UFUNC: return ufunc_lpm_to_expr(scope, lpm); case IVL_LPM_RE_AND: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_AND, false); case IVL_LPM_RE_NAND: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_AND, true); case IVL_LPM_RE_NOR: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_OR, true); case IVL_LPM_RE_OR: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_OR, false); case IVL_LPM_RE_XOR: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_XOR, false); case IVL_LPM_RE_XNOR: return reduction_lpm_to_expr(scope, lpm, SF_REDUCE_XOR, true); case IVL_LPM_SIGN_EXT: return sign_extend_lpm_to_expr(scope, lpm); case IVL_LPM_ARRAY: return array_lpm_to_expr(scope, lpm); case IVL_LPM_SHIFTL: return shift_lpm_to_expr(scope, lpm, VHDL_BINOP_SL); case IVL_LPM_SHIFTR: return shift_lpm_to_expr(scope, lpm, VHDL_BINOP_SR); case IVL_LPM_REPEAT: return repeat_lpm_to_expr(scope, lpm); default: error("Unsupported LPM type: %d", ivl_lpm_type(lpm)); return NULL; } } static int draw_mux_lpm(vhdl_arch *arch, ivl_lpm_t lpm) { int nselects = ivl_lpm_selects(lpm); if (nselects > 1) { error("Only 1 LPM select bit supported at the moment"); return 1; } vhdl_scope *scope = arch->get_scope(); vhdl_expr *s0 = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 0)); vhdl_expr *s1 = nexus_to_var_ref(scope, ivl_lpm_data(lpm, 1)); vhdl_expr *sel = nexus_to_var_ref(scope, ivl_lpm_select(lpm)); vhdl_expr *b1 = new vhdl_const_bit('1'); vhdl_expr *t1 = new vhdl_binop_expr(sel, VHDL_BINOP_EQ, b1, vhdl_type::boolean()); vhdl_var_ref *out = nexus_to_var_ref(scope, ivl_lpm_q(lpm, 0)); // Make sure s0 and s1 have the same type as the output s0 = s0->cast(out->get_type()); s1 = s1->cast(out->get_type()); vhdl_cassign_stmt *s = new vhdl_cassign_stmt(out, s0); s->add_condition(s1, t1); arch->add_stmt(s); return 0; } int draw_lpm(vhdl_arch *arch, ivl_lpm_t lpm) { if (ivl_lpm_type(lpm) == IVL_LPM_MUX) return draw_mux_lpm(arch, lpm); vhdl_expr *f = lpm_to_expr(arch->get_scope(), lpm); if (NULL == f) return 1; vhdl_var_ref *out = nexus_to_var_ref(arch->get_scope(), ivl_lpm_q(lpm, 0)); if (ivl_lpm_type(lpm) == IVL_LPM_PART_PV) { vhdl_expr *off = part_select_base(arch->get_scope(), lpm); assert(off); out->set_slice(off, ivl_lpm_width(lpm) - 1); } arch->add_stmt(new vhdl_cassign_stmt(out, f->cast(out->get_type()))); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ppttoxml.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:47:05 $ * * 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 _PPTTOXML_HXX #define _PPTTOXML_HXX #ifndef _PPTCOM_HXX #include "pptcom.hxx" #endif // ------------ // - PptToXml - // ------------ class PptToXml { REF( NMSP_SAX::XDocumentHandler ) xHdl; public: PptToXml(); ~PptToXml(); sal_Bool filter( const SEQ( NMSP_BEANS::PropertyValue )& aDescriptor, REF(NMSP_SAX::XDocumentHandler) xHandler ); void cancel(); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.430); FILE MERGED 2008/04/01 10:56:17 thb 1.2.430.2: #i85898# Stripping all external header guards 2008/03/28 15:31:21 rt 1.2.430.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: ppttoxml.hxx,v $ * $Revision: 1.3 $ * * 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 _PPTTOXML_HXX #define _PPTTOXML_HXX #include "pptcom.hxx" // ------------ // - PptToXml - // ------------ class PptToXml { REF( NMSP_SAX::XDocumentHandler ) xHdl; public: PptToXml(); ~PptToXml(); sal_Bool filter( const SEQ( NMSP_BEANS::PropertyValue )& aDescriptor, REF(NMSP_SAX::XDocumentHandler) xHandler ); void cancel(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: framelistanalyzer.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2005-07-12 14:13:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "classes/framelistanalyzer.hxx" //_______________________________________________ // my own includes #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_TARGETS_H_ #include <targets.h> #endif #ifndef __FRAMEWORK_PROPERTIES_H_ #include <properties.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_______________________________________________ // interface includes #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif //_______________________________________________ // includes of other projects #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ //_______________________________________________ // non exported const //_______________________________________________ // non exported definitions //_______________________________________________ // declarations //_______________________________________________ /** */ FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier , const css::uno::Reference< css::frame::XFrame >& xReferenceFrame , sal_uInt32 eDetectMode ) : m_xSupplier (xSupplier ) , m_xReferenceFrame(xReferenceFrame) , m_eDetectMode (eDetectMode ) { impl_analyze(); } //_______________________________________________ /** */ FrameListAnalyzer::~FrameListAnalyzer() { } //_______________________________________________ /** returns an analyzed list of all currently opened (top!) frames inside the desktop tree. We try to get a snapshot of all opened frames, which are part of the desktop frame container. Of course we can't access frames, which stands outside of this tree. But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last frame wrong. Further we analyze this list and split into different parts. E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model. These frames must be closed then. But all other frames must be untouched. In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window or document was closed. Then we have to initialize the backing window ... Last but not least we must know something about our special help frame. It must be handled seperatly. And last but not least - the backing component frame must be detected too. */ void FrameListAnalyzer::impl_analyze() { // reset all members to get a consistent state m_bReferenceIsHidden = sal_False; m_bReferenceIsHelp = sal_False; m_bReferenceIsBacking = sal_False; m_xHelp = css::uno::Reference< css::frame::XFrame >(); m_xBackingComponent = css::uno::Reference< css::frame::XFrame >(); // try to get the task container by using the given supplier css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY); // All return list get an initial size to include all possible frames. // They will be packed at the end of this method ... using the actual step positions then. sal_Int32 nVisibleStep = 0; sal_Int32 nHiddenStep = 0; sal_Int32 nModelStep = 0; sal_Int32 nCount = xFrameContainer->getCount(); m_lOtherVisibleFrames.realloc(nCount); m_lOtherHiddenFrames.realloc(nCount); m_lModelFrames.realloc(nCount); // ask for the model of the given reference frame. // It must be compared with the model of every frame of the container // to sort it into the list of frames with the same model. // Supress this step, if right detect mode isn't set. css::uno::Reference< css::frame::XModel > xReferenceModel; if ((m_eDetectMode & E_MODEL) == E_MODEL ) { css::uno::Reference< css::frame::XController > xReferenceController; if (m_xReferenceFrame.is()) xReferenceController = m_xReferenceFrame->getController(); if (xReferenceController.is()) xReferenceModel = xReferenceController->getModel(); } // check, if the reference frame is in hidden mode. // But look, if this analyze step is realy needed. css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY); if ( ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) && (xSet.is() ) ) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= m_bReferenceIsHidden; } // check, if the reference frame includes the backing component. // But look, if this analyze step is realy needed. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(m_xReferenceFrame); m_bReferenceIsBacking = (sModule.equals(SERVICENAME_STARTMODULE)); } catch(const css::uno::Exception&) {} } // check, if the reference frame includes the help module. // But look, if this analyze step is realy needed. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (m_xReferenceFrame.is() ) && (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK) ) { m_bReferenceIsHelp = sal_True; } try { // Step over all frames of the desktop frame container and analyze it. for (sal_Int32 i=0; i<nCount; ++i) { // Ignore invalid items ... and of course the reference frame. // It will be a member of the given frame list too - but it was already // analyzed before! css::uno::Reference< css::frame::XFrame > xFrame; if ( !(xFrameContainer->getByIndex(i) >>= xFrame) || !(xFrame.is() ) || (xFrame==m_xReferenceFrame ) ) continue; #ifdef ENABLE_WARNINGS if ( ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) && ( (!xFrame->getContainerWindow().is()) || (!xFrame->getComponentWindow().is()) ) ) { LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!") } #endif // ------------------------------------------------- // a) Is it the special help task? // Return it seperated from any return list. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (xFrame->getName()==SPECIALTARGET_HELPTASK) ) { m_xHelp = xFrame; continue; } // ------------------------------------------------- // b) Or is includes this task the special backing component? // Return it seperated from any return list. // But check if the reference task itself is the backing frame. // Our user mst know it to decide right. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(xFrame); if (sModule.equals(SERVICENAME_STARTMODULE)) { m_xBackingComponent = xFrame; continue; } } catch(const css::uno::Exception&) {} } // ------------------------------------------------- // c) Or is it the a task, which uses the specified model? // Add it to the list of "model frames". if ((m_eDetectMode & E_MODEL) == E_MODEL) { css::uno::Reference< css::frame::XController > xController = xFrame->getController(); css::uno::Reference< css::frame::XModel > xModel ; if (xController.is()) xModel = xController->getModel(); if (xModel==xReferenceModel) { m_lModelFrames[nModelStep] = xFrame; ++nModelStep; continue; } } // ------------------------------------------------- // d) Or is it the a task, which use another or no model at all? // Add it to the list of "other frames". But look for it's // visible state ... if it's allowed to do so. // ------------------------------------------------- sal_Bool bHidden = sal_False; if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN ) { xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY); if (xSet.is()) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= bHidden; } } if (bHidden) { m_lOtherHiddenFrames[nHiddenStep] = xFrame; ++nHiddenStep; } else { m_lOtherVisibleFrames[nVisibleStep] = xFrame; ++nVisibleStep; } } } catch(css::lang::IndexOutOfBoundsException) { // stop copying if index seams to be wrong. // This interface can't realy guarantee its count for multithreaded // environments. So it can occure! } // Pack both lists by using the actual step positions. // All empty or ignorable items should exist at the end of these lists // behind the position pointers. So they will be removed by a reallocation. m_lOtherVisibleFrames.realloc(nVisibleStep); m_lOtherHiddenFrames.realloc(nHiddenStep); m_lModelFrames.realloc(nModelStep); } } // namespace framework <commit_msg>INTEGRATION: CWS ooo19126 (1.6.38); FILE MERGED 2005/09/05 13:06:06 rt 1.6.38.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: framelistanalyzer.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:10:44 $ * * 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 "classes/framelistanalyzer.hxx" //_______________________________________________ // my own includes #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_TARGETS_H_ #include <targets.h> #endif #ifndef __FRAMEWORK_PROPERTIES_H_ #include <properties.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_______________________________________________ // interface includes #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif //_______________________________________________ // includes of other projects #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ //_______________________________________________ // non exported const //_______________________________________________ // non exported definitions //_______________________________________________ // declarations //_______________________________________________ /** */ FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier , const css::uno::Reference< css::frame::XFrame >& xReferenceFrame , sal_uInt32 eDetectMode ) : m_xSupplier (xSupplier ) , m_xReferenceFrame(xReferenceFrame) , m_eDetectMode (eDetectMode ) { impl_analyze(); } //_______________________________________________ /** */ FrameListAnalyzer::~FrameListAnalyzer() { } //_______________________________________________ /** returns an analyzed list of all currently opened (top!) frames inside the desktop tree. We try to get a snapshot of all opened frames, which are part of the desktop frame container. Of course we can't access frames, which stands outside of this tree. But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last frame wrong. Further we analyze this list and split into different parts. E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model. These frames must be closed then. But all other frames must be untouched. In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window or document was closed. Then we have to initialize the backing window ... Last but not least we must know something about our special help frame. It must be handled seperatly. And last but not least - the backing component frame must be detected too. */ void FrameListAnalyzer::impl_analyze() { // reset all members to get a consistent state m_bReferenceIsHidden = sal_False; m_bReferenceIsHelp = sal_False; m_bReferenceIsBacking = sal_False; m_xHelp = css::uno::Reference< css::frame::XFrame >(); m_xBackingComponent = css::uno::Reference< css::frame::XFrame >(); // try to get the task container by using the given supplier css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY); // All return list get an initial size to include all possible frames. // They will be packed at the end of this method ... using the actual step positions then. sal_Int32 nVisibleStep = 0; sal_Int32 nHiddenStep = 0; sal_Int32 nModelStep = 0; sal_Int32 nCount = xFrameContainer->getCount(); m_lOtherVisibleFrames.realloc(nCount); m_lOtherHiddenFrames.realloc(nCount); m_lModelFrames.realloc(nCount); // ask for the model of the given reference frame. // It must be compared with the model of every frame of the container // to sort it into the list of frames with the same model. // Supress this step, if right detect mode isn't set. css::uno::Reference< css::frame::XModel > xReferenceModel; if ((m_eDetectMode & E_MODEL) == E_MODEL ) { css::uno::Reference< css::frame::XController > xReferenceController; if (m_xReferenceFrame.is()) xReferenceController = m_xReferenceFrame->getController(); if (xReferenceController.is()) xReferenceModel = xReferenceController->getModel(); } // check, if the reference frame is in hidden mode. // But look, if this analyze step is realy needed. css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY); if ( ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) && (xSet.is() ) ) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= m_bReferenceIsHidden; } // check, if the reference frame includes the backing component. // But look, if this analyze step is realy needed. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(m_xReferenceFrame); m_bReferenceIsBacking = (sModule.equals(SERVICENAME_STARTMODULE)); } catch(const css::uno::Exception&) {} } // check, if the reference frame includes the help module. // But look, if this analyze step is realy needed. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (m_xReferenceFrame.is() ) && (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK) ) { m_bReferenceIsHelp = sal_True; } try { // Step over all frames of the desktop frame container and analyze it. for (sal_Int32 i=0; i<nCount; ++i) { // Ignore invalid items ... and of course the reference frame. // It will be a member of the given frame list too - but it was already // analyzed before! css::uno::Reference< css::frame::XFrame > xFrame; if ( !(xFrameContainer->getByIndex(i) >>= xFrame) || !(xFrame.is() ) || (xFrame==m_xReferenceFrame ) ) continue; #ifdef ENABLE_WARNINGS if ( ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) && ( (!xFrame->getContainerWindow().is()) || (!xFrame->getComponentWindow().is()) ) ) { LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!") } #endif // ------------------------------------------------- // a) Is it the special help task? // Return it seperated from any return list. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (xFrame->getName()==SPECIALTARGET_HELPTASK) ) { m_xHelp = xFrame; continue; } // ------------------------------------------------- // b) Or is includes this task the special backing component? // Return it seperated from any return list. // But check if the reference task itself is the backing frame. // Our user mst know it to decide right. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(xFrame); if (sModule.equals(SERVICENAME_STARTMODULE)) { m_xBackingComponent = xFrame; continue; } } catch(const css::uno::Exception&) {} } // ------------------------------------------------- // c) Or is it the a task, which uses the specified model? // Add it to the list of "model frames". if ((m_eDetectMode & E_MODEL) == E_MODEL) { css::uno::Reference< css::frame::XController > xController = xFrame->getController(); css::uno::Reference< css::frame::XModel > xModel ; if (xController.is()) xModel = xController->getModel(); if (xModel==xReferenceModel) { m_lModelFrames[nModelStep] = xFrame; ++nModelStep; continue; } } // ------------------------------------------------- // d) Or is it the a task, which use another or no model at all? // Add it to the list of "other frames". But look for it's // visible state ... if it's allowed to do so. // ------------------------------------------------- sal_Bool bHidden = sal_False; if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN ) { xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY); if (xSet.is()) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= bHidden; } } if (bHidden) { m_lOtherHiddenFrames[nHiddenStep] = xFrame; ++nHiddenStep; } else { m_lOtherVisibleFrames[nVisibleStep] = xFrame; ++nVisibleStep; } } } catch(css::lang::IndexOutOfBoundsException) { // stop copying if index seams to be wrong. // This interface can't realy guarantee its count for multithreaded // environments. So it can occure! } // Pack both lists by using the actual step positions. // All empty or ignorable items should exist at the end of these lists // behind the position pointers. So they will be removed by a reallocation. m_lOtherVisibleFrames.realloc(nVisibleStep); m_lOtherHiddenFrames.realloc(nHiddenStep); m_lModelFrames.realloc(nModelStep); } } // namespace framework <|endoftext|>
<commit_before> #include <QAction> #include <QToolBar> #include "wd.h" #include "toolbar.h" #include "form.h" #include "pane.h" #include "cmd.h" // --------------------------------------------------------------------- ToolBar::ToolBar(string n, string s, Form *f, Pane *p) : Child(n,s,f,p) { type="ToolBar"; QToolBar *w=new QToolBar(p); widget=(QWidget*) w; QString qn=s2q(n); QStringList opt=qsplit(s); w->setObjectName(qn); if (opt.size()) { QString t=opt.at(0); if (qshasonly(t,"0123456789x")) { QStringList sizes=t.split('x'); if (sizes.size()<2) { error("invalid icon width, height: "+q2s(t)); return; } qDebug() << "setting icon size" << sizes; w->setIconSize(QSize(c_strtoi(q2s(sizes.at(0))),c_strtoi(q2s(sizes.at(1))))); } } connect(w,SIGNAL(actionTriggered(QAction *)), this,SLOT(actionTriggered(QAction *))); } // --------------------------------------------------------------------- void ToolBar::actionTriggered(QAction *a) { event="button"; id=q2s(a->objectName()); pform->signalevent(this); } // --------------------------------------------------------------------- void ToolBar::makeact(QStringList opt) { if (opt.size()<3) { error("toolbar add needs id, text, image"); return; } QToolBar *w=(QToolBar *)widget; QString id=opt.at(0); QString text=opt.at(1); QIcon image=QIcon(opt.at(2)); if (image.isNull()) { error("invalid icon image: " + q2s(opt.at(2))); return; } QAction *a=w->addAction(image,text); a->setObjectName(id); ids.append(id); acts.append(a); } // --------------------------------------------------------------------- void ToolBar::set(string p,string v) { QToolBar *w=(QToolBar *)widget; QStringList opt=qsplit(v); if (p=="add") makeact(opt); else if (p=="addsep") w->addSeparator(); else if (p=="checkable") setbutton(p,opt); else if (p=="checked") setbutton(p,opt); else if (p=="enable") setbutton(p,opt); else Child::set(p,v); } // --------------------------------------------------------------------- int ToolBar::getindex(QString p) { int i; for (i=0; i<ids.size(); i++) if (ids.at(i)==p) return i; return -1; } // --------------------------------------------------------------------- void ToolBar::setbutton(string p, QStringList opt) { bool n=true; if (opt.isEmpty()) { error("set toolbar requires button_id: " + p); return; } else if (1<opt.size()) n=!!c_strtoi(q2s(opt.at(1))); QString btnid= opt.at(0); int i=getindex(btnid); if (0>i) { error("set toolbar cannot find button_id: " + p + " " + q2s(btnid)); return; } if (p=="checkable") acts.at(i)->setCheckable(n); else if (p=="checked") acts.at(i)->setChecked(n); else if (p=="enable") acts.at(i)->setEnabled(n); else { error("set toolbar attribute error: " + p); return; } } <commit_msg>toolbar enable/disable<commit_after> #include <QAction> #include <QToolBar> #include "wd.h" #include "toolbar.h" #include "form.h" #include "pane.h" #include "cmd.h" // --------------------------------------------------------------------- ToolBar::ToolBar(string n, string s, Form *f, Pane *p) : Child(n,s,f,p) { type="ToolBar"; QToolBar *w=new QToolBar(p); widget=(QWidget*) w; QString qn=s2q(n); QStringList opt=qsplit(s); w->setObjectName(qn); if (opt.size()) { QString t=opt.at(0); if (qshasonly(t,"0123456789x")) { QStringList sizes=t.split('x'); if (sizes.size()<2) { error("invalid icon width, height: "+q2s(t)); return; } qDebug() << "setting icon size" << sizes; w->setIconSize(QSize(c_strtoi(q2s(sizes.at(0))),c_strtoi(q2s(sizes.at(1))))); } } connect(w,SIGNAL(actionTriggered(QAction *)), this,SLOT(actionTriggered(QAction *))); } // --------------------------------------------------------------------- void ToolBar::actionTriggered(QAction *a) { event="button"; id=q2s(a->objectName()); pform->signalevent(this); } // --------------------------------------------------------------------- void ToolBar::makeact(QStringList opt) { if (opt.size()<3) { error("toolbar add needs id, text, image"); return; } QToolBar *w=(QToolBar *)widget; QString id=opt.at(0); QString text=opt.at(1); QIcon image=QIcon(opt.at(2)); if (image.isNull()) { error("invalid icon image: " + q2s(opt.at(2))); return; } QAction *a=w->addAction(image,text); a->setObjectName(id); ids.append(id); acts.append(a); } // --------------------------------------------------------------------- void ToolBar::set(string p,string v) { QToolBar *w=(QToolBar *)widget; QStringList opt=qsplit(v); if (p=="add") makeact(opt); else if (p=="addsep") w->addSeparator(); else if (p=="checkable") setbutton(p,opt); else if (p=="checked") setbutton(p,opt); else if (p=="enable") { if (opt.isEmpty()) Child::set(p,v); else if (1==opt.size() && (!opt.at(0).isEmpty()) && opt.at(0)[0].isNumber()) Child::set(p,v); else setbutton(p,opt); } else Child::set(p,v); } // --------------------------------------------------------------------- int ToolBar::getindex(QString p) { for (int i=0; i<ids.size(); i++) if (ids.at(i)==p) return i; return -1; } // --------------------------------------------------------------------- void ToolBar::setbutton(string p, QStringList opt) { bool n=true; if (opt.isEmpty()) { error("set toolbar requires button_id: " + p); return; } else if (1<opt.size()) n=!!c_strtoi(q2s(opt.at(1))); QString btnid= opt.at(0); int i=getindex(btnid); if (0>i) { error("set toolbar cannot find button_id: " + p + " " + q2s(btnid)); return; } if (p=="checkable") acts.at(i)->setCheckable(n); else if (p=="checked") acts.at(i)->setChecked(n); else if (p=="enable") acts.at(i)->setEnabled(n); else { error("set toolbar attribute error: " + p); return; } } <|endoftext|>
<commit_before>/** Copyright (C) 2012 Aldebaran Robotics */ #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <qi/log.hpp> #include <qi/os.hpp> #include <qimessaging/applicationsession.hpp> #include <qitype/jsoncodec.hpp> #include "qicli.hpp" #define foreach BOOST_FOREACH static const char* callType[] = { "?", "C", "R", "E", "S" }; typedef std::map<std::string, qi::AnyObject> ObjectMap; static ObjectMap objectMap; static bool numeric = false; static bool printMo = false; static bool disableTrace = false; static bool traceState = false; static bool cleaned = false; static bool full = false; static std::vector<std::string> objectNames; static unsigned int maxServiceLength = 0; qiLogCategory("qitrace"); void onTrace(ObjectMap::value_type ov, const qi::EventTrace& trace) { static qi::int64_t secStart = 0; if (!secStart && !full) secStart = trace.timestamp().tv_sec; static unsigned int maxLen = 0; std::string name = boost::lexical_cast<std::string>(trace.slotId()); if (!numeric) { qi::MetaObject mo = ov.second.metaObject(); qi::MetaMethod* m = mo.method(trace.slotId()); if (m) name = m->name(); else { qi::MetaSignal* s = mo.signal(trace.slotId()); if (s) name = s->name(); else name = name + "(??" ")"; // trigraph protect mode on } } if (!full && name.size() > 25) { name = name.substr(0, 22) + "..."; } std::string serviceName = ov.first; if (!full && serviceName.size() > 17) serviceName = serviceName.substr(0, 14) + "..."; maxLen = std::max(maxLen, (unsigned int)name.size()); unsigned int traceKind = trace.kind(); if (traceKind > 4) traceKind = 0; std::string spacing(maxLen + 2 - name.size(), ' '); std::string spacing2((full?maxServiceLength:17) + 2 - ov.first.size(), ' '); if (trace.kind() == qi::EventTrace::Event_Result) { std::cout << serviceName << spacing2 << trace.id() << ' ' << callType[traceKind] << ' ' << name << spacing << (trace.timestamp().tv_sec - secStart) << '.' << trace.timestamp().tv_usec << ' ' << trace.userUsTime() << ' ' << trace.systemUsTime() << ' ' << qi::encodeJSON(trace.arguments()) << std::endl; } else { std::cout << serviceName << spacing2 << trace.id() << ' ' << callType[traceKind] << ' ' << name << spacing << (trace.timestamp().tv_sec - secStart) << '.' << trace.timestamp().tv_usec << ' ' << qi::encodeJSON(trace.arguments()) << std::endl; } } int subCmd_trace(int argc, char **argv, qi::ApplicationSession& app) { po::options_description desc("Usage: qicli trace [<ServicePattern>..]"); std::vector<std::string> serviceList; desc.add_options() ("numeric,n", po::bool_switch(&numeric), "Do not resolve slot Ids to names") ("full,f", po::bool_switch(&full), "Do not abreviate anything") ("service,s", po::value<std::vector<std::string> >(&objectNames), "Object(s) to monitor, specify multiple times, comma-separate, use '*' for all, use '-globPattern' to remove from list") ("print,p", po::bool_switch(&printMo), "Print out the Metaobject and exit") ("disable,d", po::bool_switch(&disableTrace), "Disable trace on objects and exit") ("trace-status", po::bool_switch(&traceState), "Show trace status on objects and exit"); po::positional_options_description positionalOptions; positionalOptions.add("service", -1); po::variables_map vm; if (!poDefault(po::command_line_parser(argc, argv).options(desc).positional(positionalOptions), vm, desc)) return 1; qiLogVerbose() << "Connecting to service directory"; app.start(); qi::Session& s = app.session(); qiLogVerbose() << "Resolving services"; std::vector<std::string> allServices; std::vector<qi::ServiceInfo> si = s.services(); for (unsigned i=0; i<si.size(); ++i) allServices.push_back(si[i].name()); std::vector<std::string> services = parseServiceList(objectNames, allServices); std::vector<std::string> servicesOk; qiLogVerbose() << "Fetching services: " << boost::join(services, ","); // access services for (unsigned i=0; i<services.size(); ++i) { qi::AnyObject o; try { o = s.service(services[i]); } catch (const std::exception& e) { qiLogError() << "Error fetching " << services[i] << " : " << e.what(); services[i] = ""; continue; } if (!o) { qiLogError() << "Error fetching " << services[i]; services[i] = ""; continue; } objectMap[services[i]] = o; servicesOk.push_back(services[i]); if (printMo) { std::cout << "\n\n" << services[i] << "\n"; qi::details::printMetaObject(std::cout, o.metaObject()); } if (disableTrace) { try { o.call<void>("enableTrace", false); } catch(...) {} } if (traceState) { try { bool s = o.call<bool>("isTraceEnabled"); std::cout << services[i] << ": " << s << std::endl; } catch(...) {} } } if (printMo || disableTrace || traceState || objectMap.empty()) return 0; qiLogVerbose() << "Monitoring services: " << boost::join(servicesOk, ","); foreach(ObjectMap::value_type& ov, objectMap) { maxServiceLength = std::max(maxServiceLength, (unsigned int)ov.first.size()); ov.second.connect("traceObject", (boost::function<void(qi::EventTrace)>) boost::bind(&onTrace, ov, _1)).async(); } qi::Application::run(); while (!cleaned) qi::os::msleep(20); return 0; } <commit_msg>qicli trace: Show newly available thread ids.<commit_after>/** Copyright (C) 2012 Aldebaran Robotics */ #include <iostream> #include <iomanip> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <boost/io/ios_state.hpp> #include <qi/log.hpp> #include <qi/os.hpp> #include <qimessaging/applicationsession.hpp> #include <qitype/jsoncodec.hpp> #include "qicli.hpp" #define foreach BOOST_FOREACH static const char* callType[] = { "?", "C", "R", "E", "S" }; typedef std::map<std::string, qi::AnyObject> ObjectMap; static ObjectMap objectMap; static bool numeric = false; static bool printMo = false; static bool disableTrace = false; static bool traceState = false; static bool cleaned = false; static bool full = false; static std::vector<std::string> objectNames; static unsigned int maxServiceLength = 0; qiLogCategory("qitrace"); // helper to format thread id struct ThreadFormat { ThreadFormat(unsigned int tid) : tid(tid) {} unsigned int tid; }; std::ostream& operator << (std::ostream& o, const ThreadFormat& tf) { boost::io::ios_flags_saver ifs(o); return o << std::setfill('0') << std::setw(5) << tf.tid; } void onTrace(ObjectMap::value_type ov, const qi::EventTrace& trace) { static qi::int64_t secStart = 0; if (!secStart && !full) secStart = trace.timestamp().tv_sec; static unsigned int maxLen = 0; std::string name = boost::lexical_cast<std::string>(trace.slotId()); if (!numeric) { qi::MetaObject mo = ov.second.metaObject(); qi::MetaMethod* m = mo.method(trace.slotId()); if (m) name = m->name(); else { qi::MetaSignal* s = mo.signal(trace.slotId()); if (s) name = s->name(); else name = name + "(??" ")"; // trigraph protect mode on } } if (!full && name.size() > 25) { name = name.substr(0, 22) + "..."; } std::string serviceName = ov.first; if (!full && serviceName.size() > 17) serviceName = serviceName.substr(0, 14) + "..."; maxLen = std::max(maxLen, (unsigned int)name.size()); unsigned int traceKind = trace.kind(); if (traceKind > 4) traceKind = 0; std::string spacing(maxLen + 2 - name.size(), ' '); std::string spacing2((full?maxServiceLength:17) + 2 - ov.first.size(), ' '); if (trace.kind() == qi::EventTrace::Event_Result || qi::EventTrace::Event_Error) { std::cout << serviceName << spacing2 << trace.id() << ' ' << ThreadFormat(trace.callerContext()) << ' ' << ThreadFormat(trace.calleeContext()) << ' ' << callType[traceKind] << ' ' << name << spacing << (trace.timestamp().tv_sec - secStart) << '.' << trace.timestamp().tv_usec << ' ' << trace.userUsTime() << ' ' << trace.systemUsTime() << ' ' << qi::encodeJSON(trace.arguments()) << std::endl; } else { std::cout << serviceName << spacing2 << trace.id() << ' ' << ThreadFormat(trace.callerContext()) << ' ' << ThreadFormat(trace.calleeContext()) << ' ' << callType[traceKind] << ' ' << name << spacing << (trace.timestamp().tv_sec - secStart) << '.' << trace.timestamp().tv_usec << ' ' << qi::encodeJSON(trace.arguments()) << std::endl; } } int subCmd_trace(int argc, char **argv, qi::ApplicationSession& app) { po::options_description desc("Usage: qicli trace [<ServicePattern>..]"); std::vector<std::string> serviceList; desc.add_options() ("numeric,n", po::bool_switch(&numeric), "Do not resolve slot Ids to names") ("full,f", po::bool_switch(&full), "Do not abreviate anything") ("service,s", po::value<std::vector<std::string> >(&objectNames), "Object(s) to monitor, specify multiple times, comma-separate, use '*' for all, use '-globPattern' to remove from list") ("print,p", po::bool_switch(&printMo), "Print out the Metaobject and exit") ("disable,d", po::bool_switch(&disableTrace), "Disable trace on objects and exit") ("trace-status", po::bool_switch(&traceState), "Show trace status on objects and exit"); po::positional_options_description positionalOptions; positionalOptions.add("service", -1); po::variables_map vm; if (!poDefault(po::command_line_parser(argc, argv).options(desc).positional(positionalOptions), vm, desc)) return 1; qiLogVerbose() << "Connecting to service directory"; app.start(); qi::Session& s = app.session(); qiLogVerbose() << "Resolving services"; std::vector<std::string> allServices; std::vector<qi::ServiceInfo> si = s.services(); for (unsigned i=0; i<si.size(); ++i) allServices.push_back(si[i].name()); std::vector<std::string> services = parseServiceList(objectNames, allServices); std::vector<std::string> servicesOk; qiLogVerbose() << "Fetching services: " << boost::join(services, ","); // access services for (unsigned i=0; i<services.size(); ++i) { qi::AnyObject o; try { o = s.service(services[i]); } catch (const std::exception& e) { qiLogError() << "Error fetching " << services[i] << " : " << e.what(); services[i] = ""; continue; } if (!o) { qiLogError() << "Error fetching " << services[i]; services[i] = ""; continue; } objectMap[services[i]] = o; servicesOk.push_back(services[i]); if (printMo) { std::cout << "\n\n" << services[i] << "\n"; qi::details::printMetaObject(std::cout, o.metaObject()); } if (disableTrace) { try { o.call<void>("enableTrace", false); } catch(...) {} } if (traceState) { try { bool s = o.call<bool>("isTraceEnabled"); std::cout << services[i] << ": " << s << std::endl; } catch(...) {} } } if (printMo || disableTrace || traceState || objectMap.empty()) return 0; qiLogVerbose() << "Monitoring services: " << boost::join(servicesOk, ","); foreach(ObjectMap::value_type& ov, objectMap) { maxServiceLength = std::max(maxServiceLength, (unsigned int)ov.first.size()); ov.second.connect("traceObject", (boost::function<void(qi::EventTrace)>) boost::bind(&onTrace, ov, _1)).async(); } qi::Application::run(); while (!cleaned) qi::os::msleep(20); return 0; } <|endoftext|>
<commit_before>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/curl_wrappers.h" #include "google/cloud/log.h" #include "google/cloud/storage/internal/binary_data_as_debug_string.h" #include <openssl/crypto.h> #include <openssl/opensslv.h> #include <algorithm> #include <cctype> #include <iostream> #include <string> #include <thread> #include <vector> namespace google { namespace cloud { namespace storage { inline namespace STORAGE_CLIENT_NS { namespace internal { namespace { // The Google Cloud Storage C++ client library depends on libcurl, which depends // on many different SSL libraries, depending on the library the library needs // to take action to be thread-safe. More details can be found here: // // https://curl.haxx.se/libcurl/c/threadsafe.html // std::once_flag ssl_locking_initialized; #if LIBRESSL_VERSION_NUMBER // LibreSSL calls itself OpenSSL > 2.0, but it really is based on SSL 1.0.2 // and requires locks. #define GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS 1 #elif OPENSSL_VERSION_NUMBER < 0x10100000L // Older than version 1.1.0 // Before 1.1.0 OpenSSL requires locks to be used by multiple threads. #define GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS 1 #else #define GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS 0 #endif #if GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS std::vector<std::mutex> ssl_locks; // A callback to lock and unlock the mutexes needed by the SSL library. extern "C" void ssl_locking_cb(int mode, int type, char const* file, int line) { if (mode & CRYPTO_LOCK) { ssl_locks[type].lock(); } else { ssl_locks[type].unlock(); } } void InitializeSslLocking(bool enable_ssl_callbacks) { std::string curl_ssl = CurlSslLibraryId(); // Only enable the lock callbacks if needed. We need to look at what SSL // library is used by libcurl. Many of them work fine without any additional // setup. if (!SslLibraryNeedsLocking(curl_ssl)) { GCP_LOG(INFO) << "SSL locking callbacks not installed because the" << " SSL library does not need them."; return; } if (!enable_ssl_callbacks) { GCP_LOG(INFO) << "SSL locking callbacks not installed because the" << " application disabled them."; return; } if (CRYPTO_get_locking_callback() != nullptr) { GCP_LOG(INFO) << "SSL locking callbacks not installed because there are" << " callbacks already installed."; return; } // If we need to configure locking, make sure the library we linked against is // the same library that libcurl is using. In environments where both // OpenSSL/1.0.2 are OpenSSL/1.1.0 are available it is easy to link the wrong // one, and that does not work because they have completely different symbols, // despite the version numbers suggesting otherwise. std::string expected_prefix = curl_ssl; std::transform(expected_prefix.begin(), expected_prefix.end(), expected_prefix.begin(), [](char x) { return x == '/' ? ' ' : x; }); // LibreSSL seems to be using semantic versioning, so just check the major // version. if (expected_prefix.rfind("LibreSSL 2", 0) == 0) { expected_prefix = "LibreSSL 2"; } #ifdef OPENSSL_VERSION std::string openssl_v = OpenSSL_version(OPENSSL_VERSION); #else std::string openssl_v = SSLeay_version(SSLEAY_VERSION); #endif // OPENSSL_VERSION // We check the prefix for two reasons: (a) for some libraries it is enough // that the major version matches (e.g. LibreSSL), and (b) because the // `openssl_v` string sometimes reads `OpenSSL 1.1.0 May 2018` while the // string reported by libcurl would be `OpenSSL/1.1.0`, sigh... if (openssl_v.rfind(expected_prefix, 0) != 0) { std::ostringstream os; os << "Mismatched versions of OpenSSL linked in libcurl vs. the version" << " linked by the Google Cloud Storage C++ library.\n" << "libcurl is linked against " << curl_ssl << "\nwhile the google cloud storage library links against " << openssl_v << "\nMismatched versions are not supported. The Google Cloud Storage" << "\nC++ library needs to configure the OpenSSL library used by libcurl" << "\nand this is not possible if you link different versions."; // This is a case where printing to stderr is justified, this happens during // the library initialization, nothing else may get reported to the // application developer. std::cerr << os.str() << "\n"; google::cloud::internal::ThrowRuntimeError(os.str()); } // If we get to this point, we need to initialize the OpenSSL library to have // a callback, the documentation: // https://www.openssl.org/docs/man1.0.2/crypto/threads.html // is a bit hard to parse, but basically one must create CRYPTO_num_lock() // mutexes, and a single callback for all of them. // GCP_LOG(INFO) << "Installing SSL locking callbacks."; ssl_locks = std::vector<std::mutex>(static_cast<std::size_t>(CRYPTO_num_locks())); CRYPTO_set_locking_callback(ssl_locking_cb); // The documentation also recommends calling CRYPTO_THREADID_set_callback() to // setup a function to return thread ids as integers (or pointers). Writing a // portable function like that would be non-trivial, C++ thread identifiers // are opaque, they cannot be converted to integers, pointers or the native // thread type. // // Fortunately the documentation also states that a default version is // provided: // "If the application does not register such a callback using // CRYPTO_THREADID_set_callback(), then a default implementation // is used" // then goes on to describe how this default version works: // "on Windows and BeOS this uses the system's default thread identifying // APIs, and on all other platforms it uses the address of errno." // Luckily, the C++11 standard guarantees that `errno` is a thread-specific // object: // https://en.cppreference.com/w/cpp/error/errno // There are no guarantees (as far as I know) that the errno used by a // C-library like OpenSSL is the same errno as the one used by C++. But such // an implementation would be terribly broken: it would be impossible to call // C functions from C++. In my ([email protected]) opinion, we can rely on the // default version. } #else void InitializeSslLocking(bool) {} #endif // GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS /// Automatically initialize (and cleanup) the libcurl library. class CurlInitializer { public: CurlInitializer() { curl_global_init(CURL_GLOBAL_ALL); } ~CurlInitializer() { curl_global_cleanup(); } }; } // namespace std::string CurlSslLibraryId() { auto vinfo = curl_version_info(CURLVERSION_NOW); return vinfo->ssl_version; } bool SslLibraryNeedsLocking(std::string const& curl_ssl_id) { // Based on: // https://curl.haxx.se/libcurl/c/threadsafe.html // Only these library prefixes require special configuration for using safely // with multiple threads. return (curl_ssl_id.rfind("OpenSSL/1.0", 0) == 0 || curl_ssl_id.rfind("LibreSSL/2", 0) == 0); } bool SslLockingCallbacksInstalled() { #if GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS return !ssl_locks.empty(); #else return false; #endif // GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS } std::size_t CurlAppendHeaderData(CurlReceivedHeaders& received_headers, char const* data, std::size_t size) { if (size <= 2) { // Empty header (including the \r\n), ignore. return size; } if ('\r' != data[size - 2] || '\n' != data[size - 1]) { // Invalid header (should end in \r\n), ignore. return size; } auto separator = std::find(data, data + size, ':'); std::string header_name = std::string(data, separator); std::string header_value; // If there is a value, capture it, but ignore the final \r\n. if (static_cast<std::size_t>(separator - data) < size - 2) { header_value = std::string(separator + 2, data + size - 2); } std::transform(header_name.begin(), header_name.end(), header_name.begin(), [](char x) { return std::tolower(x); }); received_headers.emplace(std::move(header_name), std::move(header_value)); return size; } void CurlInitializeOnce(bool enable_ssl_callbacks) { static CurlInitializer curl_initializer; std::call_once(ssl_locking_initialized, InitializeSslLocking, enable_ssl_callbacks); } } // namespace internal } // namespace STORAGE_CLIENT_NS } // namespace storage } // namespace cloud } // namespace google <commit_msg>Fix linter warnings. (#2134)<commit_after>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/curl_wrappers.h" #include "google/cloud/log.h" #include "google/cloud/storage/internal/binary_data_as_debug_string.h" #include <openssl/crypto.h> #include <openssl/opensslv.h> #include <algorithm> #include <cctype> #include <iostream> #include <string> #include <thread> #include <vector> namespace google { namespace cloud { namespace storage { inline namespace STORAGE_CLIENT_NS { namespace internal { namespace { // The Google Cloud Storage C++ client library depends on libcurl, which depends // on many different SSL libraries, depending on the library the library needs // to take action to be thread-safe. More details can be found here: // // https://curl.haxx.se/libcurl/c/threadsafe.html // std::once_flag ssl_locking_initialized; #if LIBRESSL_VERSION_NUMBER // LibreSSL calls itself OpenSSL > 2.0, but it really is based on SSL 1.0.2 // and requires locks. #define GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS 1 #elif OPENSSL_VERSION_NUMBER < 0x10100000L // Older than version 1.1.0 // Before 1.1.0 OpenSSL requires locks to be used by multiple threads. #define GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS 1 #else #define GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS 0 #endif #if GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS std::vector<std::mutex> ssl_locks; // A callback to lock and unlock the mutexes needed by the SSL library. extern "C" void SslLockingCb(int mode, int type, char const*, int) { if ((mode & CRYPTO_LOCK) != 0) { ssl_locks[type].lock(); } else { ssl_locks[type].unlock(); } } void InitializeSslLocking(bool enable_ssl_callbacks) { std::string curl_ssl = CurlSslLibraryId(); // Only enable the lock callbacks if needed. We need to look at what SSL // library is used by libcurl. Many of them work fine without any additional // setup. if (!SslLibraryNeedsLocking(curl_ssl)) { GCP_LOG(INFO) << "SSL locking callbacks not installed because the" << " SSL library does not need them."; return; } if (!enable_ssl_callbacks) { GCP_LOG(INFO) << "SSL locking callbacks not installed because the" << " application disabled them."; return; } if (CRYPTO_get_locking_callback() != nullptr) { GCP_LOG(INFO) << "SSL locking callbacks not installed because there are" << " callbacks already installed."; return; } // If we need to configure locking, make sure the library we linked against is // the same library that libcurl is using. In environments where both // OpenSSL/1.0.2 are OpenSSL/1.1.0 are available it is easy to link the wrong // one, and that does not work because they have completely different symbols, // despite the version numbers suggesting otherwise. std::string expected_prefix = curl_ssl; std::transform(expected_prefix.begin(), expected_prefix.end(), expected_prefix.begin(), [](char x) { return x == '/' ? ' ' : x; }); // LibreSSL seems to be using semantic versioning, so just check the major // version. if (expected_prefix.rfind("LibreSSL 2", 0) == 0) { expected_prefix = "LibreSSL 2"; } #ifdef OPENSSL_VERSION std::string openssl_v = OpenSSL_version(OPENSSL_VERSION); #else std::string openssl_v = SSLeay_version(SSLEAY_VERSION); #endif // OPENSSL_VERSION // We check the prefix for two reasons: (a) for some libraries it is enough // that the major version matches (e.g. LibreSSL), and (b) because the // `openssl_v` string sometimes reads `OpenSSL 1.1.0 May 2018` while the // string reported by libcurl would be `OpenSSL/1.1.0`, sigh... if (openssl_v.rfind(expected_prefix, 0) != 0) { std::ostringstream os; os << "Mismatched versions of OpenSSL linked in libcurl vs. the version" << " linked by the Google Cloud Storage C++ library.\n" << "libcurl is linked against " << curl_ssl << "\nwhile the google cloud storage library links against " << openssl_v << "\nMismatched versions are not supported. The Google Cloud Storage" << "\nC++ library needs to configure the OpenSSL library used by libcurl" << "\nand this is not possible if you link different versions."; // This is a case where printing to stderr is justified, this happens during // the library initialization, nothing else may get reported to the // application developer. std::cerr << os.str() << "\n"; google::cloud::internal::ThrowRuntimeError(os.str()); } // If we get to this point, we need to initialize the OpenSSL library to have // a callback, the documentation: // https://www.openssl.org/docs/man1.0.2/crypto/threads.html // is a bit hard to parse, but basically one must create CRYPTO_num_lock() // mutexes, and a single callback for all of them. // GCP_LOG(INFO) << "Installing SSL locking callbacks."; ssl_locks = std::vector<std::mutex>(static_cast<std::size_t>(CRYPTO_num_locks())); CRYPTO_set_locking_callback(SslLockingCb); // The documentation also recommends calling CRYPTO_THREADID_set_callback() to // setup a function to return thread ids as integers (or pointers). Writing a // portable function like that would be non-trivial, C++ thread identifiers // are opaque, they cannot be converted to integers, pointers or the native // thread type. // // Fortunately the documentation also states that a default version is // provided: // "If the application does not register such a callback using // CRYPTO_THREADID_set_callback(), then a default implementation // is used" // then goes on to describe how this default version works: // "on Windows and BeOS this uses the system's default thread identifying // APIs, and on all other platforms it uses the address of errno." // Luckily, the C++11 standard guarantees that `errno` is a thread-specific // object: // https://en.cppreference.com/w/cpp/error/errno // There are no guarantees (as far as I know) that the errno used by a // C-library like OpenSSL is the same errno as the one used by C++. But such // an implementation would be terribly broken: it would be impossible to call // C functions from C++. In my ([email protected]) opinion, we can rely on the // default version. } #else void InitializeSslLocking(bool) {} #endif // GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS /// Automatically initialize (and cleanup) the libcurl library. class CurlInitializer { public: CurlInitializer() { curl_global_init(CURL_GLOBAL_ALL); } ~CurlInitializer() { curl_global_cleanup(); } }; } // namespace std::string CurlSslLibraryId() { auto vinfo = curl_version_info(CURLVERSION_NOW); return vinfo->ssl_version; } bool SslLibraryNeedsLocking(std::string const& curl_ssl_id) { // Based on: // https://curl.haxx.se/libcurl/c/threadsafe.html // Only these library prefixes require special configuration for using safely // with multiple threads. return (curl_ssl_id.rfind("OpenSSL/1.0", 0) == 0 || curl_ssl_id.rfind("LibreSSL/2", 0) == 0); } bool SslLockingCallbacksInstalled() { #if GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS return !ssl_locks.empty(); #else return false; #endif // GOOGLE_CLOUD_CPP_SSL_REQUIRES_LOCKS } std::size_t CurlAppendHeaderData(CurlReceivedHeaders& received_headers, char const* data, std::size_t size) { if (size <= 2) { // Empty header (including the \r\n), ignore. return size; } if ('\r' != data[size - 2] || '\n' != data[size - 1]) { // Invalid header (should end in \r\n), ignore. return size; } auto separator = std::find(data, data + size, ':'); std::string header_name = std::string(data, separator); std::string header_value; // If there is a value, capture it, but ignore the final \r\n. if (static_cast<std::size_t>(separator - data) < size - 2) { header_value = std::string(separator + 2, data + size - 2); } std::transform(header_name.begin(), header_name.end(), header_name.begin(), [](char x) { return std::tolower(x); }); received_headers.emplace(std::move(header_name), std::move(header_value)); return size; } void CurlInitializeOnce(bool enable_ssl_callbacks) { static CurlInitializer curl_initializer; std::call_once(ssl_locking_initialized, InitializeSslLocking, enable_ssl_callbacks); } } // namespace internal } // namespace STORAGE_CLIENT_NS } // namespace storage } // namespace cloud } // namespace google <|endoftext|>
<commit_before>/* * Copyright 2018 NXP. * * 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 NXP Semiconductor nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "gitversion.h" #include "libuuu.h" #include <string> #include <string.h> using namespace std; #ifndef BUILD_VER #define BUILD_VER "1.2.4" #endif static const char g_version[] = "libuuu-" BUILD_VER GIT_VERSION; const char *uuu_get_version_string() { return g_version; } int uuu_get_version() { string str = g_version; int maj, min, build; str = str.substr(strlen("libuuu-")); size_t pos = 0; string s = str.substr(0, pos=str.find(".", pos)); maj = stoll(s, 0, 10); str = str.substr(pos + 1); s = str.substr(0, pos = str.find(".", pos)); min = stoll(s, 0, 10); str = str.substr(pos + 1); s = str.substr(0, pos = str.find("-", pos)); build = stoll(s, 0, 10); return (maj << 16) | (min << 8) | build; } <commit_msg>roll back version number to 1.1.4<commit_after>/* * Copyright 2018 NXP. * * 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 NXP Semiconductor nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "gitversion.h" #include "libuuu.h" #include <string> #include <string.h> using namespace std; #ifndef BUILD_VER #define BUILD_VER "1.1.4" #endif static const char g_version[] = "libuuu-" BUILD_VER GIT_VERSION; const char *uuu_get_version_string() { return g_version; } int uuu_get_version() { string str = g_version; int maj, min, build; str = str.substr(strlen("libuuu-")); size_t pos = 0; string s = str.substr(0, pos=str.find(".", pos)); maj = stoll(s, 0, 10); str = str.substr(pos + 1); s = str.substr(0, pos = str.find(".", pos)); min = stoll(s, 0, 10); str = str.substr(pos + 1); s = str.substr(0, pos = str.find("-", pos)); build = stoll(s, 0, 10); return (maj << 16) | (min << 8) | build; } <|endoftext|>
<commit_before>// Licence 2 #include <cstring> #include <stdlib.h> #include <sstream> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include "include/dart_api.h" #include "include/dart_native_api.h" Dart_Handle NewDartExceptionWithMessage(const char* library_url, const char* exception_name, const char* message); /* Called the first time a native function with a given name is called, to resolve the Dart name of the native function into a C function pointer. */ Dart_NativeFunction ResolveName(Dart_Handle name, int argc); Dart_Handle HandleError(Dart_Handle handle); int64_t openAsync(const char* portname, int64_t baudrate_speed){ // Open serial port speed_t baudrate; switch(baudrate_speed){ // TODO baudrate 0 ? B0 case 50: baudrate = B50; break; case 75: baudrate = B75; break; case 110: baudrate = B110; break; case 134: baudrate = B134; break; case 150: baudrate = B150; break; case 200: baudrate = B200; break; case 300: baudrate = B300; break; case 600: baudrate = B600; break; case 1200: baudrate = B1200; break; case 1800: baudrate = B1800; break; case 2400: baudrate = B2400; break; case 4800: baudrate = B4800; break; case 9600: baudrate = B9600; break; case 19200: baudrate = B19200; break; case 38400: baudrate = B38400; break; case 57600: baudrate = B57600; break; case 115200: baudrate = B115200; break; case 230400: baudrate = B230400; break; #ifdef B460800 case 460800: baudrate = B460800;break; #endif #ifdef B500000 case 500000: baudrate = B500000; break; #endif #ifdef B576000 case 576000: baudrate = B576000; break; #endif #ifdef B921600 case 921600: baudrate = B921600; break; #endif #ifdef B1000000 case 1000000: baudrate = B1000000; break; #endif #ifdef B1152000 case 1152000: baudrate = B1152000; break; #endif #ifdef B1500000 case 1500000: baudrate = B1500000; break; #endif #ifdef B2000000 case 2000000: baudrate = B2000000; break; #endif #ifdef B2500000 case 2500000: baudrate = B2500000; break; #endif #ifdef B3000000 case 3000000: baudrate = B3000000; break; #endif #ifdef B3500000 case 3500000: baudrate = B3500000; break; #endif #ifdef B4000000 case 4000000: baudrate = B4000000; break; #endif #ifdef B7200 case 7200: baudrate = B7200; break; #endif #ifdef B14400 case 14400: baudrate = B14400; break; #endif #ifdef B28800 case 28800: baudrate = B28800; break; #endif #ifdef B76800 case 76800: baudrate = B76800; break; #endif } struct termios tio; memset(&tio, 0, sizeof(tio)); tio.c_iflag=0; tio.c_oflag=0; tio.c_cflag=CS8|CREAD|CLOCAL; tio.c_lflag=0; tio.c_cc[VMIN]=1; tio.c_cc[VTIME]=5; int tty_fd = open(portname, O_RDWR | O_NONBLOCK); if(tty_fd > 0) { cfsetospeed(&tio, baudrate); cfsetispeed(&tio, baudrate); tcsetattr(tty_fd, TCSANOW, &tio); } return tty_fd; } void closeAsync(int64_t tty_fd){ close(tty_fd); } int sendAsync(int64_t tty_fd, const char* data){ return write(tty_fd, data, strlen(data)); } // TODO maybe check type // result.type = Dart_CObject_kNull; void wrappedSerialPortServicePort(Dart_Port send_port_id, Dart_CObject* message){ Dart_Port reply_port_id = message->value.as_array.values[0]->value.as_send_port; Dart_CObject result; int argc = message->value.as_array.length - 1; \ Dart_CObject** argv = message->value.as_array.values + 1; char *name = argv[0]->value.as_string; argv++; argc--; // TODO replace by switch if (strcmp("open", name) == 0) { //Dart_CObject* param0 = message->value.as_array.values[0]; //Dart_CObject* param1 = message->value.as_array.values[1]; const char* portname = argv[0]->value.as_string; int64_t baudrate_speed = argv[1]->value.as_int64; int64_t tty_fd = openAsync(portname, baudrate_speed); result.type = Dart_CObject_kInt64; result.value.as_int64 = tty_fd; } else if (strcmp("close", name) == 0) { int64_t tty_fd = argv[0]->value.as_int64; closeAsync(tty_fd); result.type = Dart_CObject_kBool; result.value.as_bool = true; } else if (strcmp("send", name) == 0) { int64_t tty_fd = argv[0]->value.as_int64; const char* data = argv[1]->value.as_string; int value = sendAsync(tty_fd, data); result.type = Dart_CObject_kInt64; result.value.as_int64 = value; } else if (strcmp("read", name) == 0) { int64_t tty_fd = argv[0]->value.as_int64; int64_t buffer_size = argv[1]->value.as_int64; int8_t buffer[buffer_size]; fd_set readfs; FD_ZERO(&readfs); FD_SET(tty_fd, &readfs); select(tty_fd+1, &readfs, NULL, NULL, NULL); // TODO add delay ? int n = read(tty_fd, &buffer, sizeof(buffer)); if(n > 0){ result.type = Dart_CObject_kArray; result.value.as_array.length = n; for(int i=0; i<n; i++){ Dart_CObject* v = (Dart_CObject*) malloc(sizeof(Dart_CObject_kInt32)); v->type = Dart_CObject_kInt32; v->value.as_int32 = buffer[i]; result.value.as_array.values[i] = v; } } else { result.type = Dart_CObject_kNull; } } else { // TODO printf("ERROR :Unknow function\n"); } Dart_PostCObject(reply_port_id, &result); } void serialPortServicePort(Dart_NativeArguments arguments) { Dart_EnterScope(); Dart_SetReturnValue(arguments, Dart_Null()); Dart_Port service_port = Dart_NewNativePort("SerialPortServicePort", wrappedSerialPortServicePort, true); if (service_port != ILLEGAL_PORT) { Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port)); Dart_SetReturnValue(arguments, send_port); } Dart_ExitScope(); } DART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) { if (Dart_IsError(parent_library)) { return parent_library; } Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName); if (Dart_IsError(result_code)) return result_code; return Dart_Null(); } Dart_NativeFunction ResolveName(Dart_Handle name, int argc) { // If we fail, we return NULL, and Dart throws an exception. if (!Dart_IsString(name)) return NULL; Dart_NativeFunction result = NULL; Dart_EnterScope(); const char* cname; HandleError(Dart_StringToCString(name, &cname)); if (strcmp("serialPortServicePort", cname) == 0) result = serialPortServicePort; Dart_ExitScope(); return result; } Dart_Handle HandleError(Dart_Handle handle) { if (Dart_IsError(handle)) Dart_PropagateError(handle); return handle; } Dart_Handle NewDartExceptionWithMessage(const char* library_url, const char* exception_name, const char* message) { // Create a Dart Exception object with a message. Dart_Handle type = Dart_GetType(Dart_LookupLibrary( Dart_NewStringFromCString(library_url)), Dart_NewStringFromCString(exception_name), 0, NULL); if (Dart_IsError(type)) { Dart_PropagateError(type); } if (message != NULL) { Dart_Handle args[1]; args[0] = Dart_NewStringFromCString(message); if (Dart_IsError(args[0])) { Dart_PropagateError(args[0]); } return Dart_New(type, Dart_Null(), 1, args); } else { return Dart_New(type, Dart_Null(), 0, NULL); } } <commit_msg>Open serial with O_NOCTTY<commit_after>// Licence 2 #include <cstring> #include <stdlib.h> #include <sstream> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include "include/dart_api.h" #include "include/dart_native_api.h" Dart_Handle NewDartExceptionWithMessage(const char* library_url, const char* exception_name, const char* message); /* Called the first time a native function with a given name is called, to resolve the Dart name of the native function into a C function pointer. */ Dart_NativeFunction ResolveName(Dart_Handle name, int argc); Dart_Handle HandleError(Dart_Handle handle); int64_t openAsync(const char* portname, int64_t baudrate_speed){ // Open serial port speed_t baudrate; switch(baudrate_speed){ // TODO baudrate 0 ? B0 case 50: baudrate = B50; break; case 75: baudrate = B75; break; case 110: baudrate = B110; break; case 134: baudrate = B134; break; case 150: baudrate = B150; break; case 200: baudrate = B200; break; case 300: baudrate = B300; break; case 600: baudrate = B600; break; case 1200: baudrate = B1200; break; case 1800: baudrate = B1800; break; case 2400: baudrate = B2400; break; case 4800: baudrate = B4800; break; case 9600: baudrate = B9600; break; case 19200: baudrate = B19200; break; case 38400: baudrate = B38400; break; case 57600: baudrate = B57600; break; case 115200: baudrate = B115200; break; case 230400: baudrate = B230400; break; #ifdef B460800 case 460800: baudrate = B460800;break; #endif #ifdef B500000 case 500000: baudrate = B500000; break; #endif #ifdef B576000 case 576000: baudrate = B576000; break; #endif #ifdef B921600 case 921600: baudrate = B921600; break; #endif #ifdef B1000000 case 1000000: baudrate = B1000000; break; #endif #ifdef B1152000 case 1152000: baudrate = B1152000; break; #endif #ifdef B1500000 case 1500000: baudrate = B1500000; break; #endif #ifdef B2000000 case 2000000: baudrate = B2000000; break; #endif #ifdef B2500000 case 2500000: baudrate = B2500000; break; #endif #ifdef B3000000 case 3000000: baudrate = B3000000; break; #endif #ifdef B3500000 case 3500000: baudrate = B3500000; break; #endif #ifdef B4000000 case 4000000: baudrate = B4000000; break; #endif #ifdef B7200 case 7200: baudrate = B7200; break; #endif #ifdef B14400 case 14400: baudrate = B14400; break; #endif #ifdef B28800 case 28800: baudrate = B28800; break; #endif #ifdef B76800 case 76800: baudrate = B76800; break; #endif } struct termios tio; memset(&tio, 0, sizeof(tio)); tio.c_iflag=0; tio.c_oflag=0; tio.c_cflag=CS8|CREAD|CLOCAL; tio.c_lflag=0; tio.c_cc[VMIN]=1; tio.c_cc[VTIME]=5; int tty_fd = open(portname, O_RDWR | O_NOCTTY | O_NONBLOCK); if(tty_fd > 0) { cfsetospeed(&tio, baudrate); cfsetispeed(&tio, baudrate); tcsetattr(tty_fd, TCSANOW, &tio); } return tty_fd; } void closeAsync(int64_t tty_fd){ close(tty_fd); } int sendAsync(int64_t tty_fd, const char* data){ return write(tty_fd, data, strlen(data)); } // TODO maybe check type // result.type = Dart_CObject_kNull; void wrappedSerialPortServicePort(Dart_Port send_port_id, Dart_CObject* message){ Dart_Port reply_port_id = message->value.as_array.values[0]->value.as_send_port; Dart_CObject result; int argc = message->value.as_array.length - 1; \ Dart_CObject** argv = message->value.as_array.values + 1; char *name = argv[0]->value.as_string; argv++; argc--; // TODO replace by switch if (strcmp("open", name) == 0) { //Dart_CObject* param0 = message->value.as_array.values[0]; //Dart_CObject* param1 = message->value.as_array.values[1]; const char* portname = argv[0]->value.as_string; int64_t baudrate_speed = argv[1]->value.as_int64; int64_t tty_fd = openAsync(portname, baudrate_speed); result.type = Dart_CObject_kInt64; result.value.as_int64 = tty_fd; } else if (strcmp("close", name) == 0) { int64_t tty_fd = argv[0]->value.as_int64; closeAsync(tty_fd); result.type = Dart_CObject_kBool; result.value.as_bool = true; } else if (strcmp("send", name) == 0) { int64_t tty_fd = argv[0]->value.as_int64; const char* data = argv[1]->value.as_string; int value = sendAsync(tty_fd, data); result.type = Dart_CObject_kInt64; result.value.as_int64 = value; } else if (strcmp("read", name) == 0) { int64_t tty_fd = argv[0]->value.as_int64; int64_t buffer_size = argv[1]->value.as_int64; int8_t buffer[buffer_size]; fd_set readfs; FD_ZERO(&readfs); FD_SET(tty_fd, &readfs); select(tty_fd+1, &readfs, NULL, NULL, NULL); // TODO add delay ? int n = read(tty_fd, &buffer, sizeof(buffer)); if(n > 0){ result.type = Dart_CObject_kArray; result.value.as_array.length = n; for(int i=0; i<n; i++){ Dart_CObject* v = (Dart_CObject*) malloc(sizeof(Dart_CObject_kInt32)); v->type = Dart_CObject_kInt32; v->value.as_int32 = buffer[i]; result.value.as_array.values[i] = v; } } else { result.type = Dart_CObject_kNull; } } else { // TODO printf("ERROR :Unknow function\n"); } Dart_PostCObject(reply_port_id, &result); } void serialPortServicePort(Dart_NativeArguments arguments) { Dart_EnterScope(); Dart_SetReturnValue(arguments, Dart_Null()); Dart_Port service_port = Dart_NewNativePort("SerialPortServicePort", wrappedSerialPortServicePort, true); if (service_port != ILLEGAL_PORT) { Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port)); Dart_SetReturnValue(arguments, send_port); } Dart_ExitScope(); } DART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) { if (Dart_IsError(parent_library)) { return parent_library; } Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName); if (Dart_IsError(result_code)) return result_code; return Dart_Null(); } Dart_NativeFunction ResolveName(Dart_Handle name, int argc) { // If we fail, we return NULL, and Dart throws an exception. if (!Dart_IsString(name)) return NULL; Dart_NativeFunction result = NULL; Dart_EnterScope(); const char* cname; HandleError(Dart_StringToCString(name, &cname)); if (strcmp("serialPortServicePort", cname) == 0) result = serialPortServicePort; Dart_ExitScope(); return result; } Dart_Handle HandleError(Dart_Handle handle) { if (Dart_IsError(handle)) Dart_PropagateError(handle); return handle; } Dart_Handle NewDartExceptionWithMessage(const char* library_url, const char* exception_name, const char* message) { // Create a Dart Exception object with a message. Dart_Handle type = Dart_GetType(Dart_LookupLibrary( Dart_NewStringFromCString(library_url)), Dart_NewStringFromCString(exception_name), 0, NULL); if (Dart_IsError(type)) { Dart_PropagateError(type); } if (message != NULL) { Dart_Handle args[1]; args[0] = Dart_NewStringFromCString(message); if (Dart_IsError(args[0])) { Dart_PropagateError(args[0]); } return Dart_New(type, Dart_Null(), 1, args); } else { return Dart_New(type, Dart_Null(), 0, NULL); } } <|endoftext|>
<commit_before>// // CameraRenderer.cpp // G3MiOSSDK // // Created by José Miguel S N on 04/06/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "CameraRenderer.hpp" #include "Camera.hpp" CameraRenderer::CameraRenderer(): _camera0(NULL, 0,0), _initialPoint(0,0,0), _currentGesture(None), _camera(NULL), _initialPixel(0,0,0) { } void CameraRenderer::initialize(const InitializationContext* ic){ _logger = ic->getLogger(); } int CameraRenderer::render(const RenderContext* rc) { _camera = rc->getCamera(); //Saving camera reference _planet = rc->getPlanet(); gl = rc->getGL(); _camera->render(*rc); // TEMP TO DRAW A POINT WHERE USER PRESS if (true) if (_currentGesture==Zoom) { float vertices[] = { 0,0,0}; unsigned int indices[] = {0,1}; gl->enableVerticesPosition(); gl->disableTexture2D(); gl->disableTextures(); gl->vertexPointer(3, 0, vertices); gl->color((float) 1, (float) 1, (float) 1, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(_initialPoint.asVector3D().times(1.01)); gl->multMatrixf(T); gl->drawPoints(1, indices); gl->popMatrix(); Geodetic2D g = _planet->toGeodetic2D(_initialPoint.asVector3D()); //printf ("zoom with initial point = (%f, %f)\n", g.latitude().degrees(), g.longitude().degrees()); } return MAX_TIME_TO_RENDER; } void CameraRenderer::onResizeViewportEvent(int width, int height) { if (_camera != NULL) { _camera->resizeViewport(width, height); } } void CameraRenderer::onDown(const TouchEvent& touchEvent) { //Saving Camera0 _camera0 = Camera(*_camera); //Initial Point for interaction MutableVector2D pixel = touchEvent.getTouch(0)->getPos().asMutableVector2D(); const Vector3D ray = _camera0.pixel2Ray(pixel.asVector2D()); _initialPoint = _planet->closestIntersection(_camera0.getPosition(), ray).asMutableVector3D(); _currentGesture = Drag; //Dragging } void CameraRenderer::makeDrag(const TouchEvent& touchEvent) { if (!_initialPoint.isNan()) { //VALID INITIAL POINT const Vector2D pixel = touchEvent.getTouch(0)->getPos(); const Vector3D ray = _camera0.pixel2Ray(pixel); const Vector3D pos = _camera0.getPosition(); MutableVector3D finalPoint = _planet->closestIntersection(pos, ray).asMutableVector3D(); if (finalPoint.isNan()) { //INVALID FINAL POINT finalPoint = _planet->closestPointToSphere(pos, ray).asMutableVector3D(); } _camera->copyFrom(_camera0); _camera->dragCamera(_initialPoint.asVector3D(), finalPoint.asVector3D()); } } void CameraRenderer::makeDoubleDrag(const TouchEvent& touchEvent) { int __agustin_at_work; if (!_initialPoint.isNan()) { /* MutableVector2D pixel0 = touchEvent.getTouch(0)->getPos().asMutableVector2D(); MutableVector2D pixel1 = touchEvent.getTouch(1)->getPos().asMutableVector2D(); double finalFingerSeparation = pixel1.sub(pixel0).length(); double factor = finalFingerSeparation/_initialFingerSeparation; // compute mid 3D point between both fingers double x0 = (pixel0.x()-_camera0.getWidth())*factor+_camera->getWidth(); pixel0 = MutableVector2D(x0, pixel0.y()); Vector3D ray0 = _camera0.pixel2Ray(pixel0.asVector2D()); Vector3D P0 = _planet->closestIntersection(_camera0.getPosition(), ray0); double x1 = (pixel1.x()-_camera0.getWidth())*factor+_camera->getWidth(); pixel1 = MutableVector2D(x1, pixel1.y()); Vector3D ray1 = _camera0.pixel2Ray(pixel1.asVector2D()); Vector3D P1 = _planet->closestIntersection(_camera0.getPosition(), ray1); Geodetic2D g = _planet->getMidPoint(_planet->toGeodetic2D(P0), _planet->toGeodetic2D(P1)); Vector3D finalPoint = _planet->toVector3D(g);*/ Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); Vector2D difPixel = pixel1.sub(pixel0); double finalFingerSeparation = difPixel.length(); double angle = difPixel.orientation().radians() - _initialFingerInclination; double factor = finalFingerSeparation/_initialFingerSeparation; Vector2D averagePixel = pixel0.add(pixel1).div(2); Vector3D ray = _camera0.pixel2Ray(averagePixel); Vector3D finalPoint = _planet->closestIntersection(_camera0.getPosition(), ray); // compute 3D point of view center Vector2D centerPixel(_camera->getWidth()*0.5, _camera->getHeight()*0.5); Vector3D centerRay = _camera0.pixel2Ray(centerPixel); Vector3D centerPoint = _planet->closestIntersection(_camera0.getPosition(), centerRay); _camera->copyFrom(_camera0); //_camera->dragCameraWith2Fingers(_initialPoint.asVector3D(), centerP, finalPoint, finalFingerSeparation/_initialFingerSeparation); Vector3D initialPoint = _initialPoint.asVector3D(); // rotate globe from initialPoint to centerPoing { const Vector3D rotationAxis = initialPoint.cross(centerPoint); const Angle rotationDelta = Angle::fromRadians( - acos(initialPoint.normalized().dot(centerPoint.normalized())) ); if (rotationDelta.isNan()) return; _camera->rotateWithAxis(rotationAxis, rotationDelta); } // move the camara { double distance = _camera->getPosition().sub(centerPoint).length(); _camera->moveForward(distance*(factor-1)/factor); Geodetic3D g = _planet->toGeodetic3D(_camera->getPosition()); printf ("camera height = %f\n", g.height()); } // rotate the camera { _camera->rotateWithAxis(_camera->getCenter().sub(_camera->getPosition()), Angle::fromRadians(-angle)); } // detect new final point { _camera->updateModelMatrix(); // compute 3D point of view center Vector2D centerPixel(_camera->getWidth()*0.5, _camera->getHeight()*0.5); Vector3D centerRay = _camera->pixel2Ray(centerPixel); Vector3D centerPoint = _planet->closestIntersection(_camera->getPosition(), centerRay); Vector2D averagePixel = pixel0.add(pixel1).div(2); Vector3D ray = _camera->pixel2Ray(averagePixel); Vector3D finalPoint = _planet->closestIntersection(_camera->getPosition(), ray); /* MutableVector2D pixel0 = touchEvent.getTouch(0)->getPos().asMutableVector2D(); // double x0 = (pixel0.x()-_camera0.getWidth())*factor+_camera->getWidth(); // pixel0 = MutableVector2D(x0, pixel0.y()); Vector3D ray0 = _camera0.pixel2Ray(pixel0.asVector2D()); Vector3D P0 = _planet->closestIntersection(_camera0.getPosition(), ray0); MutableVector2D pixel1 = touchEvent.getTouch(1)->getPos().asMutableVector2D(); // double x1 = (pixel1.x()-_camera0.getWidth())*factor+_camera->getWidth(); // pixel1 = MutableVector2D(x1, pixel1.y()); Vector3D ray1 = _camera0.pixel2Ray(pixel1.asVector2D()); Vector3D P1 = _planet->closestIntersection(_camera0.getPosition(), ray1); Geodetic2D g = _planet->getMidPoint(_planet->toGeodetic2D(P0), _planet->toGeodetic2D(P1)); Vector3D finalPoint = _planet->toVector3D(g); printf ("final poin = %f %f %f ----- final point old = %f %f %f\n", finalPoint.x(), finalPoint.y(), finalPoint.z(), finalPoint_old.x(), finalPoint_old.y(), finalPoint_old.z()); */ // rotate globe from centerPoint to finalPoint const Vector3D rotationAxis = centerPoint.cross(finalPoint); const Angle rotationDelta = Angle::fromRadians( - acos(centerPoint.normalized().dot(finalPoint.normalized())) ); if (rotationDelta.isNan()) return; _camera->rotateWithAxis(rotationAxis, rotationDelta); } } } void CameraRenderer::makeZoom(const TouchEvent& touchEvent) { const Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); const Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); const Vector2D pixelCenter = pixel0.add(pixel1).div(2.0); const Vector3D ray = _camera0.pixel2Ray(pixelCenter); _initialPoint = _planet->closestIntersection(_camera0.getPosition(), ray).asMutableVector3D(); const Vector2D centerOfViewport(_camera0.getWidth() / 2, _camera0.getHeight() / 2); const Vector3D ray2 = _camera0.pixel2Ray(centerOfViewport); const Vector3D pointInCenterOfView = _planet->closestIntersection(_camera0.getPosition(), ray2); //IF CENTER PIXEL INTERSECTS THE PLANET if (!_initialPoint.isNan()){ //IF THE CENTER OF THE VIEW INTERSECTS THE PLANET if (!pointInCenterOfView.isNan()){ const Vector2D prevPixel0 = touchEvent.getTouch(0)->getPrevPos(); const Vector2D prevPixel1 = touchEvent.getTouch(1)->getPrevPos(); const double dist = pixel0.sub(pixel1).length(); const double prevDist = prevPixel0.sub(prevPixel1).length(); const Vector2D pixelDelta = pixel1.sub(pixel0); const Vector2D prevPixelDelta = prevPixel1.sub(prevPixel0); const Angle angle = pixelDelta.angle(); const Angle prevAngle = prevPixelDelta.angle(); //We rotate and zoom the camera with the same gesture _camera->zoom(prevDist /dist); _camera->pivotOnCenter(angle.sub(prevAngle)); } } } Gesture CameraRenderer::getGesture(const TouchEvent& touchEvent) { int n = touchEvent.getNumTouch(); if (n == 1) { //Dragging if (_currentGesture == Drag) { return Drag; } else { return None; } } if (n== 2){ // if it's the first movement, init zoom with the middle 3D point if (_currentGesture != Zoom) { /* // middle point in 3D MutableVector2D pixel0 = touchEvent.getTouch(0)->getPos().asMutableVector2D(); Vector3D ray0 = _camera0.pixel2Ray(pixel0.asVector2D()); Vector3D P0 = _planet->closestIntersection(_camera0.getPosition(), ray0); MutableVector2D pixel1 = touchEvent.getTouch(1)->getPos().asMutableVector2D(); Vector3D ray1 = _camera0.pixel2Ray(pixel1.asVector2D()); Vector3D P1 = _planet->closestIntersection(_camera0.getPosition(), ray1); Geodetic2D g = _planet->getMidPoint(_planet->toGeodetic2D(P0), _planet->toGeodetic2D(P1)); _initialPoint = _planet->toVector3D(g).asMutableVector3D();*/ Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); Vector2D averagePixel = pixel0.add(pixel1).div(2); Vector3D ray = _camera0.pixel2Ray(averagePixel); _initialPoint = _planet->closestIntersection(_camera0.getPosition(), ray).asMutableVector3D(); Vector2D difPixel = pixel1.sub(pixel0); _initialFingerSeparation = difPixel.length(); _initialFingerInclination = difPixel.orientation().radians(); } return Zoom; /* //If the gesture is set we don't have to change it if (_currentGesture == Zoom) return Zoom; if (_currentGesture == Rotate) return Rotate; //We have to fingers and the previous event was Drag const Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); const Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); const Vector2D prevPixel0 = touchEvent.getTouch(0)->getPrevPos(); const Vector2D prevPixel1 = touchEvent.getTouch(1)->getPrevPos(); //If both fingers go in the same direction we should rotate the camera if ( (pixel0.y() > prevPixel0.y() && pixel1.y() > prevPixel1.y()) || (pixel0.x() > prevPixel0.x() && pixel1.x() > prevPixel1.x()) || (pixel0.y() < prevPixel0.y() && pixel1.y() < prevPixel1.y()) || (pixel0.x() < prevPixel0.x() && pixel1.x() < prevPixel1.x())) { return Rotate; } else { //If fingers are diverging it is zoom return Zoom; } */ } return None; } void CameraRenderer::makeRotate(const TouchEvent& touchEvent) { int todo_JM_there_is_a_bug; const Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); const Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); const Vector2D pixelCenter = pixel0.add(pixel1).div(2.0); //The gesture is starting if (_initialPixel.isNan()){ //Storing starting pixel _initialPixel = Vector3D(pixelCenter.x(), pixelCenter.y(), 0).asMutableVector3D(); } //Calculating the point we are going to rotate around const Vector3D rotatingPoint = centerOfViewOnPlanet(_camera0); if (rotatingPoint.isNan()) { return; //We don't rotate without a valid rotating point } //Rotating axis const Vector3D camVec = _camera0.getPosition().sub(_camera0.getCenter()); const Vector3D normal = _planet->geodeticSurfaceNormal(rotatingPoint); const Vector3D horizontalAxis = normal.cross(camVec); //Calculating the angle we have to rotate the camera vertically double distY = pixelCenter.y() - _initialPixel.y(); double distX = pixelCenter.x() - _initialPixel.x(); const Angle verticalAngle = Angle::fromDegrees( (distY / (double)_camera0.getHeight()) * 180.0 ); const Angle horizontalAngle = Angle::fromDegrees( (distX / (double)_camera0.getWidth()) * 360.0 ); // _logger->logInfo("ROTATING V=%f H=%f\n", verticalAngle.degrees(), horizontalAngle.degrees()); //Back-Up camera0 Camera cameraAux(_camera0); //Rotating vertically cameraAux.rotateWithAxisAndPoint(horizontalAxis, rotatingPoint, verticalAngle); //Up and down //Check if the view isn't too low Vector3D vCamAux = cameraAux.getPosition().sub(cameraAux.getCenter()); Angle alpha = vCamAux.angleBetween(normal); Vector3D center = centerOfViewOnPlanet(*_camera); if ((alpha.degrees() > 85.0) || center.isNan()){ cameraAux.copyFrom(_camera0); //We trash the vertical rotation } //Rotating horizontally cameraAux.rotateWithAxisAndPoint(normal, rotatingPoint, horizontalAngle); //Horizontally //Finally we copy the new camera _camera->copyFrom(cameraAux); } Vector3D CameraRenderer::centerOfViewOnPlanet(const Camera& c) const { const Vector2D centerViewport(c.getWidth() / 2, c.getHeight() / 2); const Vector3D rayCV = c.pixel2Ray(centerViewport); return _planet->closestIntersection(c.getPosition(), rayCV); } void CameraRenderer::onMove(const TouchEvent& touchEvent) { _currentGesture = getGesture(touchEvent); switch (_currentGesture) { case Drag: makeDrag(touchEvent); break; case Zoom: //makeZoom(touchEvent); makeDoubleDrag(touchEvent); break; case Rotate: makeRotate(touchEvent); break; default: break; } } void CameraRenderer::onUp(const TouchEvent& touchEvent) { _currentGesture = None; _initialPixel = Vector3D::nan().asMutableVector3D(); } bool CameraRenderer::onTouchEvent(const TouchEvent* touchEvent) { switch (touchEvent->getType()) { case Down: onDown(*touchEvent); break; case Move: onMove(*touchEvent); break; case Up: onUp(*touchEvent); default: break; } return true; }<commit_msg>now double drag includes zoom and rotate<commit_after>// // CameraRenderer.cpp // G3MiOSSDK // // Created by José Miguel S N on 04/06/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "CameraRenderer.hpp" #include "Camera.hpp" CameraRenderer::CameraRenderer(): _camera0(NULL, 0,0), _initialPoint(0,0,0), _currentGesture(None), _camera(NULL), _initialPixel(0,0,0) { } void CameraRenderer::initialize(const InitializationContext* ic){ _logger = ic->getLogger(); } int CameraRenderer::render(const RenderContext* rc) { _camera = rc->getCamera(); //Saving camera reference _planet = rc->getPlanet(); gl = rc->getGL(); _camera->render(*rc); // TEMP TO DRAW A POINT WHERE USER PRESS if (true) if (_currentGesture==Zoom) { float vertices[] = { 0,0,0}; unsigned int indices[] = {0,1}; gl->enableVerticesPosition(); gl->disableTexture2D(); gl->disableTextures(); gl->vertexPointer(3, 0, vertices); gl->color((float) 1, (float) 1, (float) 1, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(_initialPoint.asVector3D().times(1.01)); gl->multMatrixf(T); gl->drawPoints(1, indices); gl->popMatrix(); Geodetic2D g = _planet->toGeodetic2D(_initialPoint.asVector3D()); //printf ("zoom with initial point = (%f, %f)\n", g.latitude().degrees(), g.longitude().degrees()); } return MAX_TIME_TO_RENDER; } void CameraRenderer::onResizeViewportEvent(int width, int height) { if (_camera != NULL) { _camera->resizeViewport(width, height); } } void CameraRenderer::onDown(const TouchEvent& touchEvent) { //Saving Camera0 _camera0 = Camera(*_camera); //Initial Point for interaction MutableVector2D pixel = touchEvent.getTouch(0)->getPos().asMutableVector2D(); const Vector3D ray = _camera0.pixel2Ray(pixel.asVector2D()); _initialPoint = _planet->closestIntersection(_camera0.getPosition(), ray).asMutableVector3D(); _currentGesture = Drag; //Dragging } void CameraRenderer::makeDrag(const TouchEvent& touchEvent) { if (!_initialPoint.isNan()) { //VALID INITIAL POINT const Vector2D pixel = touchEvent.getTouch(0)->getPos(); const Vector3D ray = _camera0.pixel2Ray(pixel); const Vector3D pos = _camera0.getPosition(); MutableVector3D finalPoint = _planet->closestIntersection(pos, ray).asMutableVector3D(); if (finalPoint.isNan()) { //INVALID FINAL POINT finalPoint = _planet->closestPointToSphere(pos, ray).asMutableVector3D(); } _camera->copyFrom(_camera0); _camera->dragCamera(_initialPoint.asVector3D(), finalPoint.asVector3D()); } } void CameraRenderer::makeDoubleDrag(const TouchEvent& touchEvent) { int __agustin_at_work; if (!_initialPoint.isNan()) { Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); Vector2D difPixel = pixel1.sub(pixel0); double finalFingerSeparation = difPixel.length(); double angle = difPixel.orientation().radians() - _initialFingerInclination; double factor = finalFingerSeparation/_initialFingerSeparation; _camera->copyFrom(_camera0); //_camera->dragCameraWith2Fingers(_initialPoint.asVector3D(), centerP, finalPoint, finalFingerSeparation/_initialFingerSeparation); // computer center view point Vector2D centerPixel(_camera->getWidth()*0.5, _camera->getHeight()*0.5); Vector3D centerRay = _camera->pixel2Ray(centerPixel); Vector3D centerPoint = _planet->closestIntersection(_camera->getPosition(), centerRay); // rotate globe from initialPoint to centerPoing { Vector3D initialPoint = _initialPoint.asVector3D(); const Vector3D rotationAxis = initialPoint.cross(centerPoint); const Angle rotationDelta = Angle::fromRadians( - acos(initialPoint.normalized().dot(centerPoint.normalized())) ); if (rotationDelta.isNan()) return; _camera->rotateWithAxis(rotationAxis, rotationDelta); } // move the camara { double distance = _camera->getPosition().sub(centerPoint).length(); _camera->moveForward(distance*(factor-1)/factor); Geodetic3D g = _planet->toGeodetic3D(_camera->getPosition()); printf ("camera height = %f\n", g.height()); } // rotate the camera { _camera->rotateWithAxis(_camera->getCenter().sub(_camera->getPosition()), Angle::fromRadians(-angle)); } // detect new final point { _camera->updateModelMatrix(); // compute 3D point of view center Vector2D centerPixel(_camera->getWidth()*0.5, _camera->getHeight()*0.5); Vector3D centerRay = _camera->pixel2Ray(centerPixel); Vector3D centerPoint = _planet->closestIntersection(_camera->getPosition(), centerRay); // middle point in 3D Vector3D ray0 = _camera->pixel2Ray(pixel0); Vector3D P0 = _planet->closestIntersection(_camera->getPosition(), ray0); Vector3D ray1 = _camera->pixel2Ray(pixel1); Vector3D P1 = _planet->closestIntersection(_camera->getPosition(), ray1); Geodetic2D g = _planet->getMidPoint(_planet->toGeodetic2D(P0), _planet->toGeodetic2D(P1)); Vector3D finalPoint = _planet->toVector3D(g); /* // middle point in 2D Vector2D averagePixel = pixel0.add(pixel1).div(2); Vector3D ray = _camera->pixel2Ray(averagePixel); Vector3D finalPoint = _planet->closestIntersection(_camera->getPosition(), ray);*/ // rotate globe from centerPoint to finalPoint const Vector3D rotationAxis = centerPoint.cross(finalPoint); const Angle rotationDelta = Angle::fromRadians( - acos(centerPoint.normalized().dot(finalPoint.normalized())) ); if (rotationDelta.isNan()) return; _camera->rotateWithAxis(rotationAxis, rotationDelta); } } } void CameraRenderer::makeZoom(const TouchEvent& touchEvent) { const Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); const Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); const Vector2D pixelCenter = pixel0.add(pixel1).div(2.0); const Vector3D ray = _camera0.pixel2Ray(pixelCenter); _initialPoint = _planet->closestIntersection(_camera0.getPosition(), ray).asMutableVector3D(); const Vector2D centerOfViewport(_camera0.getWidth() / 2, _camera0.getHeight() / 2); const Vector3D ray2 = _camera0.pixel2Ray(centerOfViewport); const Vector3D pointInCenterOfView = _planet->closestIntersection(_camera0.getPosition(), ray2); //IF CENTER PIXEL INTERSECTS THE PLANET if (!_initialPoint.isNan()){ //IF THE CENTER OF THE VIEW INTERSECTS THE PLANET if (!pointInCenterOfView.isNan()){ const Vector2D prevPixel0 = touchEvent.getTouch(0)->getPrevPos(); const Vector2D prevPixel1 = touchEvent.getTouch(1)->getPrevPos(); const double dist = pixel0.sub(pixel1).length(); const double prevDist = prevPixel0.sub(prevPixel1).length(); const Vector2D pixelDelta = pixel1.sub(pixel0); const Vector2D prevPixelDelta = prevPixel1.sub(prevPixel0); const Angle angle = pixelDelta.angle(); const Angle prevAngle = prevPixelDelta.angle(); //We rotate and zoom the camera with the same gesture _camera->zoom(prevDist /dist); _camera->pivotOnCenter(angle.sub(prevAngle)); } } } Gesture CameraRenderer::getGesture(const TouchEvent& touchEvent) { int n = touchEvent.getNumTouch(); if (n == 1) { //Dragging if (_currentGesture == Drag) { return Drag; } else { return None; } } if (n== 2){ // if it's the first movement, init zoom with the middle 3D point if (_currentGesture != Zoom) { Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); // middle point in 3D Vector3D ray0 = _camera0.pixel2Ray(pixel0); Vector3D P0 = _planet->closestIntersection(_camera0.getPosition(), ray0); Vector3D ray1 = _camera0.pixel2Ray(pixel1); Vector3D P1 = _planet->closestIntersection(_camera0.getPosition(), ray1); Geodetic2D g = _planet->getMidPoint(_planet->toGeodetic2D(P0), _planet->toGeodetic2D(P1)); _initialPoint = _planet->toVector3D(g).asMutableVector3D(); /* // middle point in 2D Vector2D averagePixel = pixel0.add(pixel1).div(2); Vector3D ray = _camera0.pixel2Ray(averagePixel); _initialPoint = _planet->closestIntersection(_camera0.getPosition(), ray).asMutableVector3D();*/ Vector2D difPixel = pixel1.sub(pixel0); _initialFingerSeparation = difPixel.length(); _initialFingerInclination = difPixel.orientation().radians(); } return Zoom; /* //If the gesture is set we don't have to change it if (_currentGesture == Zoom) return Zoom; if (_currentGesture == Rotate) return Rotate; //We have to fingers and the previous event was Drag const Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); const Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); const Vector2D prevPixel0 = touchEvent.getTouch(0)->getPrevPos(); const Vector2D prevPixel1 = touchEvent.getTouch(1)->getPrevPos(); //If both fingers go in the same direction we should rotate the camera if ( (pixel0.y() > prevPixel0.y() && pixel1.y() > prevPixel1.y()) || (pixel0.x() > prevPixel0.x() && pixel1.x() > prevPixel1.x()) || (pixel0.y() < prevPixel0.y() && pixel1.y() < prevPixel1.y()) || (pixel0.x() < prevPixel0.x() && pixel1.x() < prevPixel1.x())) { return Rotate; } else { //If fingers are diverging it is zoom return Zoom; } */ } return None; } void CameraRenderer::makeRotate(const TouchEvent& touchEvent) { int todo_JM_there_is_a_bug; const Vector2D pixel0 = touchEvent.getTouch(0)->getPos(); const Vector2D pixel1 = touchEvent.getTouch(1)->getPos(); const Vector2D pixelCenter = pixel0.add(pixel1).div(2.0); //The gesture is starting if (_initialPixel.isNan()){ //Storing starting pixel _initialPixel = Vector3D(pixelCenter.x(), pixelCenter.y(), 0).asMutableVector3D(); } //Calculating the point we are going to rotate around const Vector3D rotatingPoint = centerOfViewOnPlanet(_camera0); if (rotatingPoint.isNan()) { return; //We don't rotate without a valid rotating point } //Rotating axis const Vector3D camVec = _camera0.getPosition().sub(_camera0.getCenter()); const Vector3D normal = _planet->geodeticSurfaceNormal(rotatingPoint); const Vector3D horizontalAxis = normal.cross(camVec); //Calculating the angle we have to rotate the camera vertically double distY = pixelCenter.y() - _initialPixel.y(); double distX = pixelCenter.x() - _initialPixel.x(); const Angle verticalAngle = Angle::fromDegrees( (distY / (double)_camera0.getHeight()) * 180.0 ); const Angle horizontalAngle = Angle::fromDegrees( (distX / (double)_camera0.getWidth()) * 360.0 ); // _logger->logInfo("ROTATING V=%f H=%f\n", verticalAngle.degrees(), horizontalAngle.degrees()); //Back-Up camera0 Camera cameraAux(_camera0); //Rotating vertically cameraAux.rotateWithAxisAndPoint(horizontalAxis, rotatingPoint, verticalAngle); //Up and down //Check if the view isn't too low Vector3D vCamAux = cameraAux.getPosition().sub(cameraAux.getCenter()); Angle alpha = vCamAux.angleBetween(normal); Vector3D center = centerOfViewOnPlanet(*_camera); if ((alpha.degrees() > 85.0) || center.isNan()){ cameraAux.copyFrom(_camera0); //We trash the vertical rotation } //Rotating horizontally cameraAux.rotateWithAxisAndPoint(normal, rotatingPoint, horizontalAngle); //Horizontally //Finally we copy the new camera _camera->copyFrom(cameraAux); } Vector3D CameraRenderer::centerOfViewOnPlanet(const Camera& c) const { const Vector2D centerViewport(c.getWidth() / 2, c.getHeight() / 2); const Vector3D rayCV = c.pixel2Ray(centerViewport); return _planet->closestIntersection(c.getPosition(), rayCV); } void CameraRenderer::onMove(const TouchEvent& touchEvent) { _currentGesture = getGesture(touchEvent); switch (_currentGesture) { case Drag: makeDrag(touchEvent); break; case Zoom: //makeZoom(touchEvent); makeDoubleDrag(touchEvent); break; case Rotate: makeRotate(touchEvent); break; default: break; } } void CameraRenderer::onUp(const TouchEvent& touchEvent) { _currentGesture = None; _initialPixel = Vector3D::nan().asMutableVector3D(); } bool CameraRenderer::onTouchEvent(const TouchEvent* touchEvent) { switch (touchEvent->getType()) { case Down: onDown(*touchEvent); break; case Move: onMove(*touchEvent); break; case Up: onUp(*touchEvent); default: break; } return true; }<|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Log.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "Log.h" #include <string> #include <iostream> #include <thread> #include <boost/asio/ip/tcp.hpp> #include "Guards.h" using namespace std; using namespace dev; //⊳⊲◀▶■▣▢□▷◁▧▨▩▲◆◉◈◇◎●◍◌○◼☑☒☎☢☣☰☀♽♥♠✩✭❓✔✓✖✕✘✓✔✅⚒⚡⦸⬌∅⁕«««»»»⚙ // Logging int dev::g_logVerbosity = 5; mutex x_logOverride; /// Map of Log Channel types to bool, false forces the channel to be disabled, true forces it to be enabled. /// If a channel has no entry, then it will output as long as its verbosity (LogChannel::verbosity) is less than /// or equal to the currently output verbosity (g_logVerbosity). static map<type_info const*, bool> s_logOverride; bool isLogVisible(std::type_info const* _ch, bool _default) { Guard l(x_logOverride); if (s_logOverride.count(_ch)) return s_logOverride[_ch]; return _default; } LogOverrideAux::LogOverrideAux(std::type_info const* _ch, bool _value): m_ch(_ch) { Guard l(x_logOverride); m_old = s_logOverride.count(_ch) ? (int)s_logOverride[_ch] : c_null; s_logOverride[m_ch] = _value; } LogOverrideAux::~LogOverrideAux() { Guard l(x_logOverride); if (m_old == c_null) s_logOverride.erase(m_ch); else s_logOverride[m_ch] = (bool)m_old; } #ifdef _WIN32 const char* LogChannel::name() { return EthGray "..."; } const char* LeftChannel::name() { return EthNavy "<--"; } const char* RightChannel::name() { return EthGreen "-->"; } const char* WarnChannel::name() { return EthOnRed EthBlackBold " X"; } const char* NoteChannel::name() { return EthBlue " i"; } const char* DebugChannel::name() { return EthWhite " D"; } #else const char* LogChannel::name() { return EthGray "···"; } const char* LeftChannel::name() { return EthNavy "◀▬▬"; } const char* RightChannel::name() { return EthGreen "▬▬▶"; } const char* WarnChannel::name() { return EthOnRed EthBlackBold " ✘"; } const char* NoteChannel::name() { return EthBlue " ℹ"; } const char* DebugChannel::name() { return EthWhite " ◇"; } #endif LogOutputStreamBase::LogOutputStreamBase(char const* _id, std::type_info const* _info, unsigned _v, bool _autospacing): m_autospacing(_autospacing), m_verbosity(_v) { Guard l(x_logOverride); auto it = s_logOverride.find(_info); if ((it != s_logOverride.end() && it->second == true) || (it == s_logOverride.end() && (int)_v <= g_logVerbosity)) { time_t rawTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); char buf[24]; if (strftime(buf, 24, "%X", localtime(&rawTime)) == 0) buf[0] = '\0'; // empty if case strftime fails static char const* c_begin = " " EthViolet; static char const* c_sep1 = EthReset EthBlack "|" EthNavy; static char const* c_sep2 = EthReset EthBlack "|" EthTeal; static char const* c_end = EthReset " "; m_sstr << _id << c_begin << buf << c_sep1 << getThreadName() << ThreadContext::join(c_sep2) << c_end; } } void LogOutputStreamBase::append(boost::asio::ip::basic_endpoint<boost::asio::ip::tcp> const& _t) { m_sstr << EthNavyUnder "tcp://" << _t << EthReset; } /// Associate a name with each thread for nice logging. struct ThreadLocalLogName { ThreadLocalLogName(std::string const& _name) { m_name.reset(new string(_name)); } boost::thread_specific_ptr<std::string> m_name; }; /// Associate a name with each thread for nice logging. struct ThreadLocalLogContext { ThreadLocalLogContext() = default; void push(std::string const& _name) { if (!m_contexts.get()) m_contexts.reset(new vector<string>); m_contexts->push_back(_name); } void pop() { m_contexts->pop_back(); } string join(string const& _prior) { string ret; if (m_contexts.get()) for (auto const& i: *m_contexts) ret += _prior + i; return ret; } boost::thread_specific_ptr<std::vector<std::string>> m_contexts; }; ThreadLocalLogContext g_logThreadContext; ThreadLocalLogName g_logThreadName("main"); void dev::ThreadContext::push(string const& _n) { g_logThreadContext.push(_n); } void dev::ThreadContext::pop() { g_logThreadContext.pop(); } string dev::ThreadContext::join(string const& _prior) { return g_logThreadContext.join(_prior); } // foward declare without all of Windows.h #ifdef _WIN32 extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char* lpOutputString); #endif string dev::getThreadName() { #ifdef __linux__ char buffer[128]; pthread_getname_np(pthread_self(), buffer, 127); buffer[127] = 0; return buffer; #else return g_logThreadName.m_name.get() ? *g_logThreadName.m_name.get() : "<unknown>"; #endif } void dev::setThreadName(string const& _n) { #ifdef __linux__ pthread_setname_np(pthread_self(), _n.c_str()); #else g_logThreadName.m_name.reset(new std::string(_n)); #endif } void dev::simpleDebugOut(std::string const& _s, char const*) { static SpinLock s_lock; SpinGuard l(s_lock); cerr << _s << endl << flush; // helpful to use OutputDebugString on windows #ifdef _WIN32 { OutputDebugStringA(_s.data()); OutputDebugStringA("\n"); } #endif } std::function<void(std::string const&, char const*)> dev::g_logPost = simpleDebugOut; <commit_msg>Fix for isChannelVisible link error.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Log.cpp * @author Gav Wood <[email protected]> * @date 2014 */ #include "Log.h" #include <string> #include <iostream> #include <thread> #include <boost/asio/ip/tcp.hpp> #include "Guards.h" using namespace std; using namespace dev; //⊳⊲◀▶■▣▢□▷◁▧▨▩▲◆◉◈◇◎●◍◌○◼☑☒☎☢☣☰☀♽♥♠✩✭❓✔✓✖✕✘✓✔✅⚒⚡⦸⬌∅⁕«««»»»⚙ // Logging int dev::g_logVerbosity = 5; mutex x_logOverride; /// Map of Log Channel types to bool, false forces the channel to be disabled, true forces it to be enabled. /// If a channel has no entry, then it will output as long as its verbosity (LogChannel::verbosity) is less than /// or equal to the currently output verbosity (g_logVerbosity). static map<type_info const*, bool> s_logOverride; bool isChannelVisible(std::type_info const* _ch, bool _default) { Guard l(x_logOverride); if (s_logOverride.count(_ch)) return s_logOverride[_ch]; return _default; } LogOverrideAux::LogOverrideAux(std::type_info const* _ch, bool _value): m_ch(_ch) { Guard l(x_logOverride); m_old = s_logOverride.count(_ch) ? (int)s_logOverride[_ch] : c_null; s_logOverride[m_ch] = _value; } LogOverrideAux::~LogOverrideAux() { Guard l(x_logOverride); if (m_old == c_null) s_logOverride.erase(m_ch); else s_logOverride[m_ch] = (bool)m_old; } #ifdef _WIN32 const char* LogChannel::name() { return EthGray "..."; } const char* LeftChannel::name() { return EthNavy "<--"; } const char* RightChannel::name() { return EthGreen "-->"; } const char* WarnChannel::name() { return EthOnRed EthBlackBold " X"; } const char* NoteChannel::name() { return EthBlue " i"; } const char* DebugChannel::name() { return EthWhite " D"; } #else const char* LogChannel::name() { return EthGray "···"; } const char* LeftChannel::name() { return EthNavy "◀▬▬"; } const char* RightChannel::name() { return EthGreen "▬▬▶"; } const char* WarnChannel::name() { return EthOnRed EthBlackBold " ✘"; } const char* NoteChannel::name() { return EthBlue " ℹ"; } const char* DebugChannel::name() { return EthWhite " ◇"; } #endif LogOutputStreamBase::LogOutputStreamBase(char const* _id, std::type_info const* _info, unsigned _v, bool _autospacing): m_autospacing(_autospacing), m_verbosity(_v) { Guard l(x_logOverride); auto it = s_logOverride.find(_info); if ((it != s_logOverride.end() && it->second == true) || (it == s_logOverride.end() && (int)_v <= g_logVerbosity)) { time_t rawTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); char buf[24]; if (strftime(buf, 24, "%X", localtime(&rawTime)) == 0) buf[0] = '\0'; // empty if case strftime fails static char const* c_begin = " " EthViolet; static char const* c_sep1 = EthReset EthBlack "|" EthNavy; static char const* c_sep2 = EthReset EthBlack "|" EthTeal; static char const* c_end = EthReset " "; m_sstr << _id << c_begin << buf << c_sep1 << getThreadName() << ThreadContext::join(c_sep2) << c_end; } } void LogOutputStreamBase::append(boost::asio::ip::basic_endpoint<boost::asio::ip::tcp> const& _t) { m_sstr << EthNavyUnder "tcp://" << _t << EthReset; } /// Associate a name with each thread for nice logging. struct ThreadLocalLogName { ThreadLocalLogName(std::string const& _name) { m_name.reset(new string(_name)); } boost::thread_specific_ptr<std::string> m_name; }; /// Associate a name with each thread for nice logging. struct ThreadLocalLogContext { ThreadLocalLogContext() = default; void push(std::string const& _name) { if (!m_contexts.get()) m_contexts.reset(new vector<string>); m_contexts->push_back(_name); } void pop() { m_contexts->pop_back(); } string join(string const& _prior) { string ret; if (m_contexts.get()) for (auto const& i: *m_contexts) ret += _prior + i; return ret; } boost::thread_specific_ptr<std::vector<std::string>> m_contexts; }; ThreadLocalLogContext g_logThreadContext; ThreadLocalLogName g_logThreadName("main"); void dev::ThreadContext::push(string const& _n) { g_logThreadContext.push(_n); } void dev::ThreadContext::pop() { g_logThreadContext.pop(); } string dev::ThreadContext::join(string const& _prior) { return g_logThreadContext.join(_prior); } // foward declare without all of Windows.h #ifdef _WIN32 extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char* lpOutputString); #endif string dev::getThreadName() { #ifdef __linux__ char buffer[128]; pthread_getname_np(pthread_self(), buffer, 127); buffer[127] = 0; return buffer; #else return g_logThreadName.m_name.get() ? *g_logThreadName.m_name.get() : "<unknown>"; #endif } void dev::setThreadName(string const& _n) { #ifdef __linux__ pthread_setname_np(pthread_self(), _n.c_str()); #else g_logThreadName.m_name.reset(new std::string(_n)); #endif } void dev::simpleDebugOut(std::string const& _s, char const*) { static SpinLock s_lock; SpinGuard l(s_lock); cerr << _s << endl << flush; // helpful to use OutputDebugString on windows #ifdef _WIN32 { OutputDebugStringA(_s.data()); OutputDebugStringA("\n"); } #endif } std::function<void(std::string const&, char const*)> dev::g_logPost = simpleDebugOut; <|endoftext|>
<commit_before>// Ouzel by Elviss Strazdins #ifndef OUZEL_ASSETS_SPRITELOADER_HPP #define OUZEL_ASSETS_SPRITELOADER_HPP #include <algorithm> #include "Loader.hpp" #include "Bundle.hpp" #include "../scene/SpriteRenderer.hpp" #include "../formats/Json.hpp" namespace ouzel::assets { class SpriteLoader final: public Loader { public: explicit SpriteLoader(): Loader{Asset::Type::sprite} {} bool loadAsset(Cache&, Bundle& bundle, const std::string& name, const std::vector<std::byte>& data, const Asset::Options& options) override { scene::SpriteData spriteData; const auto d = json::parse(data); if (!d.hasMember("meta") || !d.hasMember("frames")) return false; const json::Value& metaObject = d["meta"]; const auto imageFilename = metaObject["image"].as<std::string>(); spriteData.texture = bundle.getTexture(imageFilename); if (!spriteData.texture) { bundle.loadAsset(Asset::Type::image, imageFilename, imageFilename, options); spriteData.texture = bundle.getTexture(imageFilename); } if (!spriteData.texture) return false; const Size<float, 2> textureSize{ static_cast<float>(spriteData.texture->getSize().v[0]), static_cast<float>(spriteData.texture->getSize().v[1]) }; const json::Value& framesArray = d["frames"]; scene::SpriteData::Animation animation; animation.frames.reserve(framesArray.getSize()); for (const json::Value& frameObject : framesArray) { const auto filename = frameObject["filename"].as<std::string>(); const json::Value& frameRectangleObject = frameObject["frame"]; const Rect<float> frameRectangle{ frameRectangleObject["x"].as<float>(), frameRectangleObject["y"].as<float>(), frameRectangleObject["w"].as<float>(), frameRectangleObject["h"].as<float>() }; const json::Value& sourceSizeObject = frameObject["sourceSize"]; const Size<float, 2> sourceSize{ sourceSizeObject["w"].as<float>(), sourceSizeObject["h"].as<float>() }; const json::Value& spriteSourceSizeObject = frameObject["spriteSourceSize"]; const Vector<float, 2> sourceOffset{ spriteSourceSizeObject["x"].as<float>(), spriteSourceSizeObject["y"].as<float>() }; const json::Value& pivotObject = frameObject["pivot"]; const Vector<float, 2> pivot{ pivotObject["x"].as<float>(), pivotObject["y"].as<float>() }; if (frameObject.hasMember("vertices") && frameObject.hasMember("verticesUV") && frameObject.hasMember("triangles")) { std::vector<std::uint16_t> indices; const json::Value& trianglesObject = frameObject["triangles"]; for (const json::Value& triangleObject : trianglesObject) for (const json::Value& indexObject : triangleObject) indices.push_back(static_cast<std::uint16_t>(indexObject.as<std::uint32_t>())); // reverse the vertices, so that they are counterclockwise std::reverse(indices.begin(), indices.end()); std::vector<graphics::Vertex> vertices; const json::Value& verticesObject = frameObject["vertices"]; const json::Value& verticesUVObject = frameObject["verticesUV"]; const Vector<float, 2> finalOffset{ -sourceSize.v[0] * pivot.v[0] + sourceOffset.v[0], -sourceSize.v[1] * pivot.v[1] + (sourceSize.v[1] - frameRectangle.size.v[1] - sourceOffset.v[1]) }; for (std::size_t vertexIndex = 0; vertexIndex < verticesObject.getSize(); ++vertexIndex) { const json::Value& vertexObject = verticesObject[vertexIndex]; const json::Value& vertexUVObject = verticesUVObject[vertexIndex]; vertices.emplace_back(Vector<float, 3>{static_cast<float>(vertexObject[0].as<std::int32_t>()) + finalOffset.v[0], -static_cast<float>(vertexObject[1].as<std::int32_t>()) - finalOffset.v[1], 0.0F}, Color::white(), Vector<float, 2>{static_cast<float>(vertexUVObject[0].as<std::int32_t>()) / textureSize.v[0], static_cast<float>(vertexUVObject[1].as<std::int32_t>()) / textureSize.v[1]}, Vector<float, 3>{0.0F, 0.0F, -1.0F}); } animation.frames.emplace_back(filename, indices, vertices, frameRectangle, sourceSize, sourceOffset, pivot); } else { const auto rotated = frameObject["rotated"].as<bool>(); animation.frames.emplace_back(filename, textureSize, frameRectangle, rotated, sourceSize, sourceOffset, pivot); } } spriteData.animations[""] = std::move(animation); bundle.setSpriteData(name, spriteData); return true; } }; } #endif // OUZEL_ASSETS_SPRITELOADER_HPP <commit_msg>Use auto<commit_after>// Ouzel by Elviss Strazdins #ifndef OUZEL_ASSETS_SPRITELOADER_HPP #define OUZEL_ASSETS_SPRITELOADER_HPP #include <algorithm> #include "Loader.hpp" #include "Bundle.hpp" #include "../scene/SpriteRenderer.hpp" #include "../formats/Json.hpp" namespace ouzel::assets { class SpriteLoader final: public Loader { public: explicit SpriteLoader(): Loader{Asset::Type::sprite} {} bool loadAsset(Cache&, Bundle& bundle, const std::string& name, const std::vector<std::byte>& data, const Asset::Options& options) override { scene::SpriteData spriteData; const auto d = json::parse(data); if (!d.hasMember("meta") || !d.hasMember("frames")) return false; const auto& metaObject = d["meta"]; const auto imageFilename = metaObject["image"].as<std::string>(); spriteData.texture = bundle.getTexture(imageFilename); if (!spriteData.texture) { bundle.loadAsset(Asset::Type::image, imageFilename, imageFilename, options); spriteData.texture = bundle.getTexture(imageFilename); } if (!spriteData.texture) return false; const Size<float, 2> textureSize{ static_cast<float>(spriteData.texture->getSize().v[0]), static_cast<float>(spriteData.texture->getSize().v[1]) }; const auto& framesArray = d["frames"]; scene::SpriteData::Animation animation; animation.frames.reserve(framesArray.getSize()); for (const auto& frameObject : framesArray) { const auto filename = frameObject["filename"].as<std::string>(); const auto& frameRectangleObject = frameObject["frame"]; const Rect<float> frameRectangle{ frameRectangleObject["x"].as<float>(), frameRectangleObject["y"].as<float>(), frameRectangleObject["w"].as<float>(), frameRectangleObject["h"].as<float>() }; const auto& sourceSizeObject = frameObject["sourceSize"]; const Size<float, 2> sourceSize{ sourceSizeObject["w"].as<float>(), sourceSizeObject["h"].as<float>() }; const auto& spriteSourceSizeObject = frameObject["spriteSourceSize"]; const Vector<float, 2> sourceOffset{ spriteSourceSizeObject["x"].as<float>(), spriteSourceSizeObject["y"].as<float>() }; const auto& pivotObject = frameObject["pivot"]; const Vector<float, 2> pivot{ pivotObject["x"].as<float>(), pivotObject["y"].as<float>() }; if (frameObject.hasMember("vertices") && frameObject.hasMember("verticesUV") && frameObject.hasMember("triangles")) { std::vector<std::uint16_t> indices; const auto& trianglesObject = frameObject["triangles"]; for (const auto& triangleObject : trianglesObject) for (const auto& indexObject : triangleObject) indices.push_back(static_cast<std::uint16_t>(indexObject.as<std::uint32_t>())); // reverse the vertices, so that they are counterclockwise std::reverse(indices.begin(), indices.end()); std::vector<graphics::Vertex> vertices; const auto& verticesObject = frameObject["vertices"]; const auto& verticesUVObject = frameObject["verticesUV"]; const Vector<float, 2> finalOffset{ -sourceSize.v[0] * pivot.v[0] + sourceOffset.v[0], -sourceSize.v[1] * pivot.v[1] + (sourceSize.v[1] - frameRectangle.size.v[1] - sourceOffset.v[1]) }; for (std::size_t vertexIndex = 0; vertexIndex < verticesObject.getSize(); ++vertexIndex) { const auto& vertexObject = verticesObject[vertexIndex]; const auto& vertexUVObject = verticesUVObject[vertexIndex]; vertices.emplace_back(Vector<float, 3>{static_cast<float>(vertexObject[0].as<std::int32_t>()) + finalOffset.v[0], -static_cast<float>(vertexObject[1].as<std::int32_t>()) - finalOffset.v[1], 0.0F}, Color::white(), Vector<float, 2>{static_cast<float>(vertexUVObject[0].as<std::int32_t>()) / textureSize.v[0], static_cast<float>(vertexUVObject[1].as<std::int32_t>()) / textureSize.v[1]}, Vector<float, 3>{0.0F, 0.0F, -1.0F}); } animation.frames.emplace_back(filename, indices, vertices, frameRectangle, sourceSize, sourceOffset, pivot); } else { const auto rotated = frameObject["rotated"].as<bool>(); animation.frames.emplace_back(filename, textureSize, frameRectangle, rotated, sourceSize, sourceOffset, pivot); } } spriteData.animations[""] = std::move(animation); bundle.setSpriteData(name, spriteData); return true; } }; } #endif // OUZEL_ASSETS_SPRITELOADER_HPP <|endoftext|>
<commit_before>#include <StdAfx.h> #include <Interpret/SmartView/SIDBin.h> #include <UI/MySecInfo.h> namespace smartview { void SIDBin::Parse() { auto hRes = S_OK; const PSID SidStart = const_cast<LPBYTE>(m_Parser.GetCurrentAddress()); const auto cbSid = m_Parser.RemainingBytes(); m_Parser.Advance(cbSid); if (SidStart && cbSid >= sizeof(SID) - sizeof(DWORD) + sizeof(DWORD) * static_cast<PISID>(SidStart)->SubAuthorityCount && IsValidSid(SidStart)) { DWORD dwSidName = 0; DWORD dwSidDomain = 0; SID_NAME_USE SidNameUse; if (!LookupAccountSidW(nullptr, SidStart, nullptr, &dwSidName, nullptr, &dwSidDomain, &SidNameUse)) { const auto dwErr = GetLastError(); hRes = HRESULT_FROM_WIN32(dwErr); if (ERROR_NONE_MAPPED != dwErr && STRSAFE_E_INSUFFICIENT_BUFFER != hRes) { error::LogFunctionCall( hRes, NULL, false, false, true, dwErr, "LookupAccountSid", __FILE__, __LINE__); } } if (SUCCEEDED(hRes)) { const auto lpSidName = dwSidName ? new WCHAR[dwSidName] : nullptr; const auto lpSidDomain = dwSidDomain ? new WCHAR[dwSidDomain] : nullptr; // Only make the call if we got something to get if (lpSidName || lpSidDomain) { WC_BS(LookupAccountSidW( nullptr, SidStart, lpSidName, &dwSidName, lpSidDomain, &dwSidDomain, &SidNameUse)); if (lpSidName) m_lpSidName = lpSidName; if (lpSidDomain) m_lpSidDomain = lpSidDomain; delete[] lpSidName; delete[] lpSidDomain; } } m_lpStringSid = sid::GetTextualSid(SidStart); } } _Check_return_ std::wstring SIDBin::ToStringInternal() { auto szDomain = !m_lpSidDomain.empty() ? m_lpSidDomain : strings::formatmessage(IDS_NODOMAIN); auto szName = !m_lpSidName.empty() ? m_lpSidName : strings::formatmessage(IDS_NONAME); auto szSID = !m_lpStringSid.empty() ? m_lpStringSid : strings::formatmessage(IDS_NOSID); return strings::formatmessage(IDS_SIDHEADER, szDomain.c_str(), szName.c_str(), szSID.c_str()); } }<commit_msg>Fix sid test<commit_after>#include <StdAfx.h> #include <Interpret/SmartView/SIDBin.h> #include <UI/MySecInfo.h> namespace smartview { void SIDBin::Parse() { const PSID SidStart = const_cast<LPBYTE>(m_Parser.GetCurrentAddress()); const auto cbSid = m_Parser.RemainingBytes(); m_Parser.Advance(cbSid); if (SidStart && cbSid >= sizeof(SID) - sizeof(DWORD) + sizeof(DWORD) * static_cast<PISID>(SidStart)->SubAuthorityCount && IsValidSid(SidStart)) { DWORD dwSidName = 0; DWORD dwSidDomain = 0; SID_NAME_USE SidNameUse; if (!LookupAccountSidW(nullptr, SidStart, nullptr, &dwSidName, nullptr, &dwSidDomain, &SidNameUse)) { const auto dwErr = GetLastError(); if (dwErr != ERROR_NONE_MAPPED && dwErr != ERROR_INSUFFICIENT_BUFFER) { error::LogFunctionCall( HRESULT_FROM_WIN32(dwErr), NULL, false, false, true, dwErr, "LookupAccountSid", __FILE__, __LINE__); } } const auto lpSidName = dwSidName ? new WCHAR[dwSidName] : nullptr; const auto lpSidDomain = dwSidDomain ? new WCHAR[dwSidDomain] : nullptr; // Only make the call if we got something to get if (lpSidName || lpSidDomain) { WC_BS(LookupAccountSidW( nullptr, SidStart, lpSidName, &dwSidName, lpSidDomain, &dwSidDomain, &SidNameUse)); if (lpSidName) m_lpSidName = lpSidName; if (lpSidDomain) m_lpSidDomain = lpSidDomain; delete[] lpSidName; delete[] lpSidDomain; } m_lpStringSid = sid::GetTextualSid(SidStart); } } _Check_return_ std::wstring SIDBin::ToStringInternal() { auto szDomain = !m_lpSidDomain.empty() ? m_lpSidDomain : strings::formatmessage(IDS_NODOMAIN); auto szName = !m_lpSidName.empty() ? m_lpSidName : strings::formatmessage(IDS_NONAME); auto szSID = !m_lpStringSid.empty() ? m_lpStringSid : strings::formatmessage(IDS_NOSID); return strings::formatmessage(IDS_SIDHEADER, szDomain.c_str(), szName.c_str(), szSID.c_str()); } }<|endoftext|>
<commit_before>/* * Author(s): * - Cedric Gestes <[email protected]> * - Herve Cuche <[email protected]> * * Copyright (C) 2012 Aldebaran Robotics */ #include <qimessaging/session.hpp> #include <qimessaging/datastream.hpp> #include <qimessaging/transport_socket.hpp> #include <qimessaging/object.hpp> #include <qimessaging/service_info.hpp> #include "src/remoteobject_p.hpp" #include "src/network_thread.hpp" #include "src/session_p.hpp" static int uniqueRequestId = 0; namespace qi { SessionPrivate::SessionPrivate() { _networkThread = new qi::NetworkThread(); _serviceSocket = new qi::TransportSocket(); _serviceSocket->setDelegate(this); } SessionPrivate::~SessionPrivate() { _serviceSocket->disconnect(); delete _networkThread; delete _serviceSocket; } void SessionPrivate::onWriteDone(TransportSocket *client) { } void SessionPrivate::onReadyRead(TransportSocket *client, Message &msg) { } void SessionPrivate::onConnected(TransportSocket *client) { } void SessionPrivate::onDisconnected(TransportSocket *client) { } void SessionPrivate::connect(const std::string &url) { _serviceSocket->connect(url, _networkThread->getEventBase()); } std::vector<ServiceInfo> SessionPrivate::services() { std::vector<ServiceInfo> result; qi::Message msg; msg.setType(qi::Message::Type_Call); msg.setService(qi::Message::Service_ServiceDirectory); msg.setPath(qi::Message::Path_Main); msg.setFunction(qi::Message::ServiceDirectoryFunction_Services); _serviceSocket->send(msg); _serviceSocket->waitForId(msg.id()); qi::Message ans; _serviceSocket->read(msg.id(), &ans); qi::DataStream d(ans.buffer()); d >> result; return result; } qi::TransportSocket* SessionPrivate::serviceSocket(const std::string &name, unsigned int *idx, qi::Url::Protocol type) { qi::Message msg; qi::DataStream dr(msg.buffer()); dr << name; msg.setType(qi::Message::Type_Call); msg.setService(qi::Message::Service_ServiceDirectory); msg.setPath(qi::Message::Path_Main); msg.setFunction(qi::Message::ServiceDirectoryFunction_Service); _serviceSocket->send(msg); _serviceSocket->waitForId(msg.id()); qi::Message ans; _serviceSocket->read(msg.id(), &ans); qi::ServiceInfo si; qi::DataStream d(ans.buffer()); d >> si; *idx = si.serviceId(); for (std::vector<std::string>::const_iterator it = si.endpoints().begin(); it != si.endpoints().end(); ++it) { qi::Url url(*it); if (type == qi::Url::Protocol_Any || type == url.protocol()) { qi::TransportSocket* ts = NULL; ts = new qi::TransportSocket(); ts->setDelegate(this); ts->connect(url, _nthd->getEventBase()); ts->waitForConnected(); return ts; } } return 0; } qi::Object* SessionPrivate::service(const std::string &service, qi::Url::Protocol type) { qi::Object *obj; unsigned int serviceId = 0; qi::TransportSocket *ts = serviceSocket(service, &serviceId, type); if (ts == 0) { return 0; } qi::Message msg; msg.setType(qi::Message::Type_Call); msg.setService(serviceId); msg.setPath(qi::Message::Path_Main); msg.setFunction(qi::Message::Function_MetaObject); ts->send(msg); ts->waitForId(msg.id()); qi::Message ret; ts->read(msg.id(), &ret); qi::MetaObject *mo = new qi::MetaObject; qi::DataStream ds(ret.buffer()); ds >> *mo; qi::RemoteObject *robj = new qi::RemoteObject(ts, serviceId, mo); obj = robj; return obj; } // ###### Session Session::Session() : _p(new SessionPrivate()) { } Session::~Session() { delete _p; } void Session::connect(const std::string &masterAddress) { _p->connect(masterAddress); } bool Session::disconnect() { return true; } bool Session::waitForConnected(int msecs) { return _p->_serviceSocket->waitForConnected(msecs); } bool Session::waitForDisconnected(int msecs) { return _p->_serviceSocket->waitForDisconnected(msecs); } std::vector<ServiceInfo> Session::services() { return _p->services(); } qi::TransportSocket* Session::serviceSocket(const std::string &name, unsigned int *idx, qi::Url::Protocol type) { return _p->serviceSocket(name, idx, type); } qi::Object* Session::service(const std::string &service, qi::Url::Protocol type) { return _p->service(service, type); } void Session::join() { _p->_networkThread->join(); } } <commit_msg>session: fix typo<commit_after>/* * Author(s): * - Cedric Gestes <[email protected]> * - Herve Cuche <[email protected]> * * Copyright (C) 2012 Aldebaran Robotics */ #include <qimessaging/session.hpp> #include <qimessaging/datastream.hpp> #include <qimessaging/transport_socket.hpp> #include <qimessaging/object.hpp> #include <qimessaging/service_info.hpp> #include "src/remoteobject_p.hpp" #include "src/network_thread.hpp" #include "src/session_p.hpp" static int uniqueRequestId = 0; namespace qi { SessionPrivate::SessionPrivate() { _networkThread = new qi::NetworkThread(); _serviceSocket = new qi::TransportSocket(); _serviceSocket->setDelegate(this); } SessionPrivate::~SessionPrivate() { _serviceSocket->disconnect(); delete _networkThread; delete _serviceSocket; } void SessionPrivate::onWriteDone(TransportSocket *client) { } void SessionPrivate::onReadyRead(TransportSocket *client, Message &msg) { } void SessionPrivate::onConnected(TransportSocket *client) { } void SessionPrivate::onDisconnected(TransportSocket *client) { } void SessionPrivate::connect(const std::string &url) { _serviceSocket->connect(url, _networkThread->getEventBase()); } std::vector<ServiceInfo> SessionPrivate::services() { std::vector<ServiceInfo> result; qi::Message msg; msg.setType(qi::Message::Type_Call); msg.setService(qi::Message::Service_ServiceDirectory); msg.setPath(qi::Message::Path_Main); msg.setFunction(qi::Message::ServiceDirectoryFunction_Services); _serviceSocket->send(msg); _serviceSocket->waitForId(msg.id()); qi::Message ans; _serviceSocket->read(msg.id(), &ans); qi::DataStream d(ans.buffer()); d >> result; return result; } qi::TransportSocket* SessionPrivate::serviceSocket(const std::string &name, unsigned int *idx, qi::Url::Protocol type) { qi::Message msg; qi::DataStream dr(msg.buffer()); dr << name; msg.setType(qi::Message::Type_Call); msg.setService(qi::Message::Service_ServiceDirectory); msg.setPath(qi::Message::Path_Main); msg.setFunction(qi::Message::ServiceDirectoryFunction_Service); _serviceSocket->send(msg); _serviceSocket->waitForId(msg.id()); qi::Message ans; _serviceSocket->read(msg.id(), &ans); qi::ServiceInfo si; qi::DataStream d(ans.buffer()); d >> si; *idx = si.serviceId(); for (std::vector<std::string>::const_iterator it = si.endpoints().begin(); it != si.endpoints().end(); ++it) { qi::Url url(*it); if (type == qi::Url::Protocol_Any || type == url.protocol()) { qi::TransportSocket* ts = NULL; ts = new qi::TransportSocket(); ts->setDelegate(this); ts->connect(url, _networkThread->getEventBase()); ts->waitForConnected(); return ts; } } return 0; } qi::Object* SessionPrivate::service(const std::string &service, qi::Url::Protocol type) { qi::Object *obj; unsigned int serviceId = 0; qi::TransportSocket *ts = serviceSocket(service, &serviceId, type); if (ts == 0) { return 0; } qi::Message msg; msg.setType(qi::Message::Type_Call); msg.setService(serviceId); msg.setPath(qi::Message::Path_Main); msg.setFunction(qi::Message::Function_MetaObject); ts->send(msg); ts->waitForId(msg.id()); qi::Message ret; ts->read(msg.id(), &ret); qi::MetaObject *mo = new qi::MetaObject; qi::DataStream ds(ret.buffer()); ds >> *mo; qi::RemoteObject *robj = new qi::RemoteObject(ts, serviceId, mo); obj = robj; return obj; } // ###### Session Session::Session() : _p(new SessionPrivate()) { } Session::~Session() { delete _p; } void Session::connect(const std::string &masterAddress) { _p->connect(masterAddress); } bool Session::disconnect() { return true; } bool Session::waitForConnected(int msecs) { return _p->_serviceSocket->waitForConnected(msecs); } bool Session::waitForDisconnected(int msecs) { return _p->_serviceSocket->waitForDisconnected(msecs); } std::vector<ServiceInfo> Session::services() { return _p->services(); } qi::TransportSocket* Session::serviceSocket(const std::string &name, unsigned int *idx, qi::Url::Protocol type) { return _p->serviceSocket(name, idx, type); } qi::Object* Session::service(const std::string &service, qi::Url::Protocol type) { return _p->service(service, type); } void Session::join() { _p->_networkThread->join(); } } <|endoftext|>
<commit_before>/* * D-Bus AT-SPI, Qt Adaptor * * Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies). * * 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, see <http://www.gnu.org/licenses/>. */ #include "accessible.h" #include <QDBusPendingReply> #include <QDebug> #include <QtGui/QWidget> #include <QAccessibleValueInterface> #include "adaptor.h" #include "bridge.h" #include "cache.h" #include "generated/accessible_adaptor.h" #include "generated/action_adaptor.h" #include "generated/component_adaptor.h" #include "generated/editable_text_adaptor.h" #include "generated/event_adaptor.h" #include "generated/socket_proxy.h" #include "generated/table_adaptor.h" #include "generated/text_adaptor.h" #include "generated/value_adaptor.h" #define ACCESSIBLE_CREATION_DEBUG #define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry" QString QSpiAccessible::pathForObject(QObject *object) { Q_ASSERT(object); return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object)); } QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex) { QString path; QAccessibleInterface* interfaceWithObject = interface; while(!interfaceWithObject->object()) { QAccessibleInterface* parentInterface; interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface); Q_ASSERT(parentInterface->isValid()); int index = parentInterface->indexOfChild(interfaceWithObject); //Q_ASSERT(index >= 0); // FIXME: This should never happen! if (index < 0) { index = 999; path.prepend("/BROKEN_OBJECT_HIERARCHY"); qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object(); qDebug() << "Original interface: " << interface->object() << index; qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount(); QObject* p = parentInterface->object(); qDebug() << p->children(); QAccessibleInterface* tttt; int id = parentInterface->navigate(QAccessible::Child, 1, &tttt); qDebug() << "Nav child: " << id << tttt->object(); } path.prepend('/' + QString::number(index)); interfaceWithObject = parentInterface; } path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object()))); if (childIndex > 0) { path.append('/' + QString::number(childIndex)); } return path; } QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath) { QStringList parts = dbusPath.split('/'); Q_ASSERT(parts.size() > 5); // ignore the first /org/a11y/atspi/accessible/ QString objectString = parts.at(5); quintptr uintptr = objectString.toULongLong(); if (!uintptr) return QPair<QAccessibleInterface*, int>(0, 0); QObject* object = reinterpret_cast<QObject*>(uintptr); qDebug() << object; QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object); QAccessibleInterface* childInter; int index = 0; for (int i = 6; i < parts.size(); ++i) { index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter); if (index == 0) { delete inter; inter = childInter; } } return QPair<QAccessibleInterface*, int>(inter, index); } QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index) : QSpiAdaptor(interface, index) { QString path = pathForInterface(interface, index); QDBusObjectPath dbusPath = QDBusObjectPath(path); reference = QSpiObjectReference(spiBridge->dBusConnection(), dbusPath); #ifdef ACCESSIBLE_CREATION_DEBUG qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path() << interface->text(QAccessible::Name, index); #endif new AccessibleAdaptor(this); supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE; if ( (!interface->rect(index).isEmpty()) || (interface->object() && interface->object()->isWidgetType()) || (interface->role(index) == QAccessible::ListItem) || (interface->role(index) == QAccessible::Cell) || (interface->role(index) == QAccessible::TreeItem) || (interface->role(index) == QAccessible::Row) || (interface->object() && interface->object()->inherits("QSGItem")) ) { new ComponentAdaptor(this); supportedInterfaces << QSPI_INTERFACE_COMPONENT; if (interface->object() && interface->object()->isWidgetType()) { QWidget *w = qobject_cast<QWidget*>(interface->object()); if (w->isWindow()) { new WindowAdaptor(this); #ifdef ACCESSIBLE_CREATION_DEBUG qDebug() << " IS a window"; #endif } } } #ifdef ACCESSIBLE_CREATION_DEBUG else { qDebug() << " IS NOT a component"; } #endif new ObjectAdaptor(this); new FocusAdaptor(this); if (interface->actionInterface()) { new ActionAdaptor(this); supportedInterfaces << QSPI_INTERFACE_ACTION; } if (interface->textInterface()) { new TextAdaptor(this); supportedInterfaces << QSPI_INTERFACE_TEXT; oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount()); } if (interface->editableTextInterface()) { new EditableTextAdaptor(this); supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT; } if (interface->valueInterface()) { new ValueAdaptor(this); supportedInterfaces << QSPI_INTERFACE_VALUE; } if (interface->table2Interface()) { new TableAdaptor(this); supportedInterfaces << QSPI_INTERFACE_TABLE; } spiBridge->dBusConnection().registerObject(reference.path.path(), this, QDBusConnection::ExportAdaptors); state = interface->state(childIndex()); } QSpiObjectReference QSpiAccessible::getParentReference() const { Q_ASSERT(interface); if (interface->isValid()) { QAccessibleInterface *parentInterface = 0; interface->navigate(QAccessible::Ancestor, 1, &parentInterface); if (parentInterface) { QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object()); delete parentInterface; if (parent) return parent->getReference(); } } qWarning() << "Invalid parent: " << interface << interface->object(); return QSpiObjectReference(); } void QSpiAccessible::accessibleEvent(QAccessible::Event event) { Q_ASSERT(interface); if (!interface->isValid()) { spiBridge->removeAdaptor(this); return; } switch (event) { case QAccessible::NameChanged: { QSpiObjectReference r = getReference(); QDBusVariant data; data.setVariant(QVariant::fromValue(r)); emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference()); break; } case QAccessible::DescriptionChanged: { QSpiObjectReference r = getReference(); QDBusVariant data; data.setVariant(QVariant::fromValue(r)); emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference()); break; } case QAccessible::Focus: { qDebug() << "Focus: " << getReference().path.path() << interface->object(); QDBusVariant data; data.setVariant(QVariant::fromValue(getReference())); emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference()); emit Focus("", 0, 0, data, spiBridge->getRootReference()); break; } #if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) case QAccessible::TextUpdated: { Q_ASSERT(interface->textInterface()); // at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text qDebug() << "Text changed: " << interface->object(); QDBusVariant data; data.setVariant(QVariant::fromValue(oldText)); emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference()); QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount()); data.setVariant(QVariant::fromValue(text)); emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference()); oldText = text; QDBusVariant cursorData; int pos = interface->textInterface()->cursorPosition(); cursorData.setVariant(QVariant::fromValue(pos)); emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference()); break; } case QAccessible::TextCaretMoved: { Q_ASSERT(interface->textInterface()); qDebug() << "Text caret moved: " << interface->object(); QDBusVariant data; int pos = interface->textInterface()->cursorPosition(); data.setVariant(QVariant::fromValue(pos)); emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference()); break; } #endif case QAccessible::ValueChanged: { Q_ASSERT(interface->valueInterface()); QDBusVariant data; data.setVariant(QVariant::fromValue(getReference())); emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference()); break; } case QAccessible::ObjectShow: break; case QAccessible::ObjectHide: // TODO - send status changed // qWarning() << "Object hide"; break; case QAccessible::ObjectDestroyed: // TODO - maybe send children-changed and cache Removed // qWarning() << "Object destroyed"; break; case QAccessible::StateChanged: { QAccessible::State newState = interface->state(childIndex()); // qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState); if ((state^newState) & QAccessible::Checked) { int checked = (newState & QAccessible::Checked) ? 1 : 0; QDBusVariant data; data.setVariant(QVariant::fromValue(getReference())); emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference()); } state = newState; break; } case QAccessible::ParentChanged: // TODO - send parent changed default: // qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16) // << " obj: " << interface->object() // << (interface->isValid() ? interface->object()->objectName() : " invalid interface!"); break; } } void QSpiAccessible::windowActivated() { QDBusVariant data; data.setVariant(QString()); emit Create("", 0, 0, data, spiBridge->getRootReference()); emit Restore("", 0, 0, data, spiBridge->getRootReference()); emit Activate("", 0, 0, data, spiBridge->getRootReference()); } <commit_msg>Add comments for TableModelChanged.<commit_after>/* * D-Bus AT-SPI, Qt Adaptor * * Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies). * * 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, see <http://www.gnu.org/licenses/>. */ #include "accessible.h" #include <QDBusPendingReply> #include <QDebug> #include <QtGui/QWidget> #include <QAccessibleValueInterface> #include "adaptor.h" #include "bridge.h" #include "cache.h" #include "generated/accessible_adaptor.h" #include "generated/action_adaptor.h" #include "generated/component_adaptor.h" #include "generated/editable_text_adaptor.h" #include "generated/event_adaptor.h" #include "generated/socket_proxy.h" #include "generated/table_adaptor.h" #include "generated/text_adaptor.h" #include "generated/value_adaptor.h" #define ACCESSIBLE_CREATION_DEBUG #define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry" QString QSpiAccessible::pathForObject(QObject *object) { Q_ASSERT(object); return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object)); } QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex) { QString path; QAccessibleInterface* interfaceWithObject = interface; while(!interfaceWithObject->object()) { QAccessibleInterface* parentInterface; interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface); Q_ASSERT(parentInterface->isValid()); int index = parentInterface->indexOfChild(interfaceWithObject); //Q_ASSERT(index >= 0); // FIXME: This should never happen! if (index < 0) { index = 999; path.prepend("/BROKEN_OBJECT_HIERARCHY"); qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object(); qDebug() << "Original interface: " << interface->object() << index; qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount(); QObject* p = parentInterface->object(); qDebug() << p->children(); QAccessibleInterface* tttt; int id = parentInterface->navigate(QAccessible::Child, 1, &tttt); qDebug() << "Nav child: " << id << tttt->object(); } path.prepend('/' + QString::number(index)); interfaceWithObject = parentInterface; } path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object()))); if (childIndex > 0) { path.append('/' + QString::number(childIndex)); } return path; } QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath) { QStringList parts = dbusPath.split('/'); Q_ASSERT(parts.size() > 5); // ignore the first /org/a11y/atspi/accessible/ QString objectString = parts.at(5); quintptr uintptr = objectString.toULongLong(); if (!uintptr) return QPair<QAccessibleInterface*, int>(0, 0); QObject* object = reinterpret_cast<QObject*>(uintptr); qDebug() << object; QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object); QAccessibleInterface* childInter; int index = 0; for (int i = 6; i < parts.size(); ++i) { index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter); if (index == 0) { delete inter; inter = childInter; } } return QPair<QAccessibleInterface*, int>(inter, index); } QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index) : QSpiAdaptor(interface, index) { QString path = pathForInterface(interface, index); QDBusObjectPath dbusPath = QDBusObjectPath(path); reference = QSpiObjectReference(spiBridge->dBusConnection(), dbusPath); #ifdef ACCESSIBLE_CREATION_DEBUG qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path() << interface->text(QAccessible::Name, index); #endif new AccessibleAdaptor(this); supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE; if ( (!interface->rect(index).isEmpty()) || (interface->object() && interface->object()->isWidgetType()) || (interface->role(index) == QAccessible::ListItem) || (interface->role(index) == QAccessible::Cell) || (interface->role(index) == QAccessible::TreeItem) || (interface->role(index) == QAccessible::Row) || (interface->object() && interface->object()->inherits("QSGItem")) ) { new ComponentAdaptor(this); supportedInterfaces << QSPI_INTERFACE_COMPONENT; if (interface->object() && interface->object()->isWidgetType()) { QWidget *w = qobject_cast<QWidget*>(interface->object()); if (w->isWindow()) { new WindowAdaptor(this); #ifdef ACCESSIBLE_CREATION_DEBUG qDebug() << " IS a window"; #endif } } } #ifdef ACCESSIBLE_CREATION_DEBUG else { qDebug() << " IS NOT a component"; } #endif new ObjectAdaptor(this); new FocusAdaptor(this); if (interface->actionInterface()) { new ActionAdaptor(this); supportedInterfaces << QSPI_INTERFACE_ACTION; } if (interface->textInterface()) { new TextAdaptor(this); supportedInterfaces << QSPI_INTERFACE_TEXT; oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount()); } if (interface->editableTextInterface()) { new EditableTextAdaptor(this); supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT; } if (interface->valueInterface()) { new ValueAdaptor(this); supportedInterfaces << QSPI_INTERFACE_VALUE; } if (interface->table2Interface()) { new TableAdaptor(this); supportedInterfaces << QSPI_INTERFACE_TABLE; } spiBridge->dBusConnection().registerObject(reference.path.path(), this, QDBusConnection::ExportAdaptors); state = interface->state(childIndex()); } QSpiObjectReference QSpiAccessible::getParentReference() const { Q_ASSERT(interface); if (interface->isValid()) { QAccessibleInterface *parentInterface = 0; interface->navigate(QAccessible::Ancestor, 1, &parentInterface); if (parentInterface) { QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object()); delete parentInterface; if (parent) return parent->getReference(); } } qWarning() << "Invalid parent: " << interface << interface->object(); return QSpiObjectReference(); } void QSpiAccessible::accessibleEvent(QAccessible::Event event) { Q_ASSERT(interface); if (!interface->isValid()) { spiBridge->removeAdaptor(this); return; } switch (event) { case QAccessible::NameChanged: { QSpiObjectReference r = getReference(); QDBusVariant data; data.setVariant(QVariant::fromValue(r)); emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference()); break; } case QAccessible::DescriptionChanged: { QSpiObjectReference r = getReference(); QDBusVariant data; data.setVariant(QVariant::fromValue(r)); emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference()); break; } case QAccessible::Focus: { qDebug() << "Focus: " << getReference().path.path() << interface->object(); QDBusVariant data; data.setVariant(QVariant::fromValue(getReference())); emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference()); emit Focus("", 0, 0, data, spiBridge->getRootReference()); break; } #if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) case QAccessible::TextUpdated: { Q_ASSERT(interface->textInterface()); // at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text qDebug() << "Text changed: " << interface->object(); QDBusVariant data; data.setVariant(QVariant::fromValue(oldText)); emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference()); QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount()); data.setVariant(QVariant::fromValue(text)); emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference()); oldText = text; QDBusVariant cursorData; int pos = interface->textInterface()->cursorPosition(); cursorData.setVariant(QVariant::fromValue(pos)); emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference()); break; } case QAccessible::TextCaretMoved: { Q_ASSERT(interface->textInterface()); qDebug() << "Text caret moved: " << interface->object(); QDBusVariant data; int pos = interface->textInterface()->cursorPosition(); data.setVariant(QVariant::fromValue(pos)); emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference()); break; } #endif case QAccessible::ValueChanged: { Q_ASSERT(interface->valueInterface()); QDBusVariant data; data.setVariant(QVariant::fromValue(getReference())); emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference()); break; } case QAccessible::ObjectShow: break; case QAccessible::ObjectHide: // TODO - send status changed // qWarning() << "Object hide"; break; case QAccessible::ObjectDestroyed: // TODO - maybe send children-changed and cache Removed // qWarning() << "Object destroyed"; break; case QAccessible::StateChanged: { QAccessible::State newState = interface->state(childIndex()); // qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState); if ((state^newState) & QAccessible::Checked) { int checked = (newState & QAccessible::Checked) ? 1 : 0; QDBusVariant data; data.setVariant(QVariant::fromValue(getReference())); emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference()); } state = newState; break; } case QAccessible::TableModelChanged: { // FIXME: react to table layout changes - added rows etc // QAccessible2::TableModelChange change = interface->table2Interface()->modelChange(); // QDBusVariant data; // data.setVariant(QVariant::fromValue(getReference())); // signalChildrenChanged("add", interface->childCount(), 0, data); // // model-changed // emit ChildrenChanged(type, detail1, detail2, data, spiBridge->getRootReference()); break; } case QAccessible::ParentChanged: // TODO - send parent changed default: // qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16) // << " obj: " << interface->object() // << (interface->isValid() ? interface->object()->objectName() : " invalid interface!"); break; } } void QSpiAccessible::windowActivated() { QDBusVariant data; data.setVariant(QString()); emit Create("", 0, 0, data, spiBridge->getRootReference()); emit Restore("", 0, 0, data, spiBridge->getRootReference()); emit Activate("", 0, 0, data, spiBridge->getRootReference()); } <|endoftext|>