hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
09da727c16c4cd84060325b971f7415a4e9f8f4d
4,359
cpp
C++
jsk_rviz_plugins/src/ambient_sound_visual.cpp
ShunjiroOsada/jsk_visualization_package
f5305ccb79b41a2efc994a535cb316e7467961de
[ "MIT" ]
5
2016-07-18T02:20:30.000Z
2022-01-23T13:12:20.000Z
jsk_rviz_plugins/src/ambient_sound_visual.cpp
ShunjiroOsada/jsk_visualization_package
f5305ccb79b41a2efc994a535cb316e7467961de
[ "MIT" ]
null
null
null
jsk_rviz_plugins/src/ambient_sound_visual.cpp
ShunjiroOsada/jsk_visualization_package
f5305ccb79b41a2efc994a535cb316e7467961de
[ "MIT" ]
7
2015-11-01T13:40:30.000Z
2020-02-21T12:59:18.000Z
#include <OGRE/OgreVector3.h> #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreSceneManager.h> #include <rviz/ogre_helpers/billboard_line.h> #include <rviz/ogre_helpers/axes.h> #include "ambient_sound_visual.h" namespace jsk_rviz_plugins { // BEGIN_TUTORIAL AmbientSoundVisual::AmbientSoundVisual( Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node ): /*{{{*/ width_ (0.1), scale_ (1.0), bias_ (28), grad_ (0.4) { scene_manager_ = scene_manager; // Ogre::SceneNode s form a tree, with each node storing the // transform (position and orientation) of itself relative to its // parent. Ogre does the math of combining those transforms when it // is time to render. // // Here we create a node to store the pose of the Imu's header frame // relative to the RViz fixed frame. frame_node_ = parent_node->createChildSceneNode(); // We create the arrow object within the frame node so that we can // set its position and direction relative to its header frame. ambient_sound_power_line_ = new rviz::BillboardLine( scene_manager_, frame_node_ ); //axes_ = new rviz::Axes( scene_manager_ , frame_node_); }/*}}}*/ AmbientSoundVisual::~AmbientSoundVisual()/*{{{*/ { // Delete the arrow to make it disappear. delete ambient_sound_power_line_; //delete axes_; // Destroy the frame node since we don't need it anymore. scene_manager_->destroySceneNode( frame_node_ ); }/*}}}*/ void AmbientSoundVisual::setMessage( const jsk_hark_msgs::HarkPower::ConstPtr& msg )/*{{{*/ { int directions = msg->directions; std::vector<float> powers = msg->powers; //float powers[] = {/*{{{*/ //25,25,28,30,34,32,29,25,25,25, //25,25,25,25,25,25,25,25,25,25, //25,25,25,25,25,25,25,25,25,25, //25,25,25,25,25,25,25,25,25,25, //25,25,25,25,25,25,25,25,25,25, //25,25,25,25,25,25,25,25,25,25, //25,25,25,25,25,25,25,25,25,25, //25,25, //};/*}}}*/ if ( powers[0] == 0.0 ){ return;} //float min_elem = *std::min_element(powers.begin(),powers.end()); //axes_->setOrientation(orientation_); //axes_->setPosition(position_); ambient_sound_power_line_->clear(); ambient_sound_power_line_->setLineWidth(width_); for (int i = 0; i <= directions ; i++) { float biased_power = (powers[(i%directions)] - bias_) * grad_; if (biased_power <= 0.0) { biased_power = 0.001; } Ogre::Vector3 point = Ogre::Vector3((biased_power*scale_)*cos(i*(2*M_PI/directions)- M_PI), (biased_power*scale_)*sin(i*(2*M_PI/directions) - M_PI), 0); ambient_sound_power_line_->addPoint(orientation_ * point + position_); //std::cout << biased_power << " "; } //std::cout << std::endl; //Ogre::ColourValue color; //ambient_sound_power_line_->setColor(color.r, color.g, color.b, color.a); }/*}}}*/ // Position and orientation are passed through to the SceneNode. void AmbientSoundVisual::setFramePosition( const Ogre::Vector3& position )/*{{{*/ { //ROS_INFO_STREAM("pos: " << position); //frame_node_->setPosition( position ); //<- unnecessary position_ = position; } void AmbientSoundVisual::setFrameOrientation( const Ogre::Quaternion& orientation ) { //ROS_INFO_STREAM("orientation: " << orientation); //frame_node_->setOrientation( orientation ); //<- unnecessary orientation_ = orientation; } /*}}}*/ // Color is passed through to the Arrow object. /*{{{*/ void AmbientSoundVisual::setColor( float r, float g, float b, float a ) { ambient_sound_power_line_->setColor( r, g, b, a ); } // added by sifi void AmbientSoundVisual::setWidth( float w ) { width_ = w; } void AmbientSoundVisual::setScale( float s ) { scale_ = s; } void AmbientSoundVisual::setBias( float b ) { bias_ = b; } void AmbientSoundVisual::setGrad( float g ) { grad_ = g; } /*}}}*/ // END_TUTORIAL } // end namespace jsk_rviz_plugins
34.054688
164
0.599679
[ "render", "object", "vector", "transform" ]
09dd9d4344d8f77aa9f2e2bfecf5e513bdd3dfb7
3,358
cpp
C++
leetcode/cpp/qt_mini_parser.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
leetcode/cpp/qt_mini_parser.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
leetcode/cpp/qt_mini_parser.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
/* Given a nested list of integers represented as a string, implement a parser to deserialize it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Note: You may assume that the string is well-formed: String is non-empty. String does not contain white spaces. String contains only digits 0-9, [, - ,, ]. Example 1: Given s = "324", You should return a NestedInteger object which contains a single integer 324. Example 2: Given s = "[123,[456,[789]]]", Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789. */ /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Constructor initializes an empty nested list. * NestedInteger(); * * // Constructor initializes a single integer. * NestedInteger(int value); * * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Set this NestedInteger to hold a single integer. * void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * void add(const NestedInteger &ni); * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector<NestedInteger> &getList() const; * }; */ /***** Wrong Solution class NestedInteger { private: vector<int> nums; vector<NestedInteger> nestints; } class Solution { public: NestedInteger deserialize(string s) { NestedInteger ans; if(s[0]!='[') { if(s.size()>2) ans.nums.push_back(stoi(s.substr(1, s.size()-2))); return ans; } string str = s.substr(1, s.size()-2); int pre = 0; int cur = 0; for(int i=0; i<str.size(); i++) { if(str[pre]=='[') } return ans; } }; */ // https://discuss.leetcode.com/topic/54258/python-c-solutions class Solution { public: NestedInteger deserialize(string s) { istringstream in(s); return deserialize(in); } private: NestedInteger deserialize(istringstream &in) { int number; // 如果第一个字符是'[',那么 in>>number 执行失败, failbit被设置 if (in >> number) return NestedInteger(number); // 取消failbit标志位设置(clear() is used to unset the failbit after unexpected input) in.clear(); // get() is used to extract the first character in.get(); NestedInteger list; // peek() is used to read the first character without extraction, different with get() while (in.peek() != ']') { list.add(deserialize(in)); if (in.peek() == ',') in.get(); } // skip the ']' in.get(); return list; } };
27.983333
99
0.637582
[ "object", "vector" ]
09eaba817440dd683d286274b68024bab8e951c9
5,495
cpp
C++
example-customclass/src/ofApp.cpp
nariakiiwatani/ofxNNG
443827c4d4d6bd47c66682fdbd50ae9abf3ef7ee
[ "MIT" ]
3
2019-05-20T10:06:37.000Z
2021-08-08T02:30:23.000Z
example-customclass/src/ofApp.cpp
nariakiiwatani/ofxNNG
443827c4d4d6bd47c66682fdbd50ae9abf3ef7ee
[ "MIT" ]
null
null
null
example-customclass/src/ofApp.cpp
nariakiiwatani/ofxNNG
443827c4d4d6bd47c66682fdbd50ae9abf3ef7ee
[ "MIT" ]
null
null
null
#include "ofApp.h" #include "ofxNNGPair.h" #include "Serialize.h" // you can use any types which you define struct Memcopyable { int index; glm::vec3 pos; // if you are sure it's safe to use memcpy to pack this type into message, // you can notify that to ofxNNG by putting this macro in its scope. // typically, this means at least 1 condition of 2 below. // 1. your host is using big endian(nng uses big endian inside) // 2. both sending and receiving hosts uses same endian OFX_NNG_NOTIFY_TO_USE_MEMCPY_MEMBER }; // or you can notify same thing by this macro outside the scope. // this is useful for third-party struct. struct ThirdPartys{}; OFX_NNG_NOTIFY_TO_USE_MEMCPY(ThirdPartys); // in case there is any non-memcopyable member(ex; std::string), // you need to define conversion functions. // you can use macro for typical conversion. struct NeedConversion { std::string name; ofColor color; ofMesh mesh; ofMeshFace face; ofPoint point; ofPixels pixels; ofRectangle rectangle; ofBuffer buffer; OFX_NNG_MEMBER_CONVERTER(name,color,mesh,face,point,pixels,rectangle,buffer); }; struct ThirdParty2 {int i;}; namespace ofxNNG { // for third-party classes OFX_NNG_ADL_CONVERTER(ThirdParty2,i); // actually ofxNNG already defined converters for many of glm and of types(see ofxNNGMessageConvertFunctions.h). // but still you can override them. OFX_NNG_ADL_CONVERTER(ofColor, r,g,b); OFX_NNG_ADL_CONVERTER(glm::vec3, x,y,z); } //-------------------------------------------------------------- void ofApp::setup(){ using namespace ofxNNG; // setup socket. no matter which type to use for this example. ofxNNG::Pair socket; socket.setup(); auto listener = socket.createListener("inproc://example"); // event callbacks. // these are not necessary. listener->setEventCallback(NNG_PIPE_EV_ADD_PRE, [](nng_pipe pipe) { // called after connection but before adding to the socket. // but you cannot send any messages. ofLogNotice("event") << "add pre"; // if you wanted not to communicate with this pipe, you can close the connection explicitly. // nng_pipe_close(pipe); }); listener->setEventCallback(NNG_PIPE_EV_ADD_POST, [](nng_pipe pipe) { // called after adding to the socket. // now you can send messages. ofLogNotice("event") << "add post"; }); listener->setEventCallback(NNG_PIPE_EV_REM_POST, [](nng_pipe pipe) { // called after removal. // you no longer can send any messages. ofLogNotice("event") << "rem post"; }); listener->start(); // you can use ofxNNG::Message explicitly ofPixels pix; pix.allocate(1,1,OF_PIXELS_RGB); Message msg; msg.append(123); msg.append(456,789,"something"); msg.append(pix); msg.append(ofVec3f()); msg.append(ofPixels()); msg.append(ofMatrix4x4()); msg.append(glm::mat4()); msg.append(glm::quat()); msg.append(ofColor()); socket.send(msg); socket.send(std::move(msg)); // if you won't use this msg anymore, it'd be better to use std::move. // or you can send everything directly. // they will be converted to ofxNNG::Message internally. socket.send(42); socket.send(glm::vec3(0,0,1)); socket.send({123,456,789,"something"}); // this case it will be memcpy-ed. // remember there was OFX_NNG_NOTIFY_TO_USE_MEMCPY_MEMBER avobe. Memcopyable copyable; copyable.index = 57; copyable.pos = {1,1,1}; socket.send(copyable); // this case it will be converted to ofxNNG::Message using user-defined converter. // defined by OFX_NNG_MEMBER_CONVERTER macro NeedConversion needs; needs.name = "my name"; needs.color = ofColor::white; socket.send(needs); // to receive message with a socket, there are 2 options. // 1. callback functions socket.setCallback<int>([](int){}); socket.setCallback<std::string, int>([](const std::string&, const int&){}); socket.setCallback<Memcopyable>([](const Memcopyable&){}); // 2. reference int intval; std::string strval; NeedConversion ncval; socket.setCallback(intval, strval, ncval); // you can receive values by any type. // but be careful; receiving messages using different type will cause unexpected behaviors. } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
29.074074
113
0.602366
[ "mesh" ]
09f3b9a07d3715b719729d9980dcfaa711ccfcca
109,494
cpp
C++
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_IF_EXTENSION_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_IF_EXTENSION_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/CISCO_IF_EXTENSION_MIB.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "CISCO_IF_EXTENSION_MIB.hpp" using namespace ydk; namespace cisco_ios_xe { namespace CISCO_IF_EXTENSION_MIB { CISCOIFEXTENSIONMIB::CISCOIFEXTENSIONMIB() : ciscoifextsystemconfig(std::make_shared<CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig>()) , cieifpacketstatstable(std::make_shared<CISCOIFEXTENSIONMIB::CieIfPacketStatsTable>()) , cieifinterfacetable(std::make_shared<CISCOIFEXTENSIONMIB::CieIfInterfaceTable>()) , cieifstatuslisttable(std::make_shared<CISCOIFEXTENSIONMIB::CieIfStatusListTable>()) , cieifvlstatstable(std::make_shared<CISCOIFEXTENSIONMIB::CieIfVlStatsTable>()) , cieifindexpersistencetable(std::make_shared<CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable>()) , cieifdot1qcustomethertypetable(std::make_shared<CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable>()) , cieifutiltable(std::make_shared<CISCOIFEXTENSIONMIB::CieIfUtilTable>()) , cieifdot1dbasemappingtable(std::make_shared<CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable>()) , cieifnamemappingtable(std::make_shared<CISCOIFEXTENSIONMIB::CieIfNameMappingTable>()) { ciscoifextsystemconfig->parent = this; cieifpacketstatstable->parent = this; cieifinterfacetable->parent = this; cieifstatuslisttable->parent = this; cieifvlstatstable->parent = this; cieifindexpersistencetable->parent = this; cieifdot1qcustomethertypetable->parent = this; cieifutiltable->parent = this; cieifdot1dbasemappingtable->parent = this; cieifnamemappingtable->parent = this; yang_name = "CISCO-IF-EXTENSION-MIB"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = true; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::~CISCOIFEXTENSIONMIB() { } bool CISCOIFEXTENSIONMIB::has_data() const { if (is_presence_container) return true; return (ciscoifextsystemconfig != nullptr && ciscoifextsystemconfig->has_data()) || (cieifpacketstatstable != nullptr && cieifpacketstatstable->has_data()) || (cieifinterfacetable != nullptr && cieifinterfacetable->has_data()) || (cieifstatuslisttable != nullptr && cieifstatuslisttable->has_data()) || (cieifvlstatstable != nullptr && cieifvlstatstable->has_data()) || (cieifindexpersistencetable != nullptr && cieifindexpersistencetable->has_data()) || (cieifdot1qcustomethertypetable != nullptr && cieifdot1qcustomethertypetable->has_data()) || (cieifutiltable != nullptr && cieifutiltable->has_data()) || (cieifdot1dbasemappingtable != nullptr && cieifdot1dbasemappingtable->has_data()) || (cieifnamemappingtable != nullptr && cieifnamemappingtable->has_data()); } bool CISCOIFEXTENSIONMIB::has_operation() const { return is_set(yfilter) || (ciscoifextsystemconfig != nullptr && ciscoifextsystemconfig->has_operation()) || (cieifpacketstatstable != nullptr && cieifpacketstatstable->has_operation()) || (cieifinterfacetable != nullptr && cieifinterfacetable->has_operation()) || (cieifstatuslisttable != nullptr && cieifstatuslisttable->has_operation()) || (cieifvlstatstable != nullptr && cieifvlstatstable->has_operation()) || (cieifindexpersistencetable != nullptr && cieifindexpersistencetable->has_operation()) || (cieifdot1qcustomethertypetable != nullptr && cieifdot1qcustomethertypetable->has_operation()) || (cieifutiltable != nullptr && cieifutiltable->has_operation()) || (cieifdot1dbasemappingtable != nullptr && cieifdot1dbasemappingtable->has_operation()) || (cieifnamemappingtable != nullptr && cieifnamemappingtable->has_operation()); } std::string CISCOIFEXTENSIONMIB::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ciscoIfExtSystemConfig") { if(ciscoifextsystemconfig == nullptr) { ciscoifextsystemconfig = std::make_shared<CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig>(); } return ciscoifextsystemconfig; } if(child_yang_name == "cieIfPacketStatsTable") { if(cieifpacketstatstable == nullptr) { cieifpacketstatstable = std::make_shared<CISCOIFEXTENSIONMIB::CieIfPacketStatsTable>(); } return cieifpacketstatstable; } if(child_yang_name == "cieIfInterfaceTable") { if(cieifinterfacetable == nullptr) { cieifinterfacetable = std::make_shared<CISCOIFEXTENSIONMIB::CieIfInterfaceTable>(); } return cieifinterfacetable; } if(child_yang_name == "cieIfStatusListTable") { if(cieifstatuslisttable == nullptr) { cieifstatuslisttable = std::make_shared<CISCOIFEXTENSIONMIB::CieIfStatusListTable>(); } return cieifstatuslisttable; } if(child_yang_name == "cieIfVlStatsTable") { if(cieifvlstatstable == nullptr) { cieifvlstatstable = std::make_shared<CISCOIFEXTENSIONMIB::CieIfVlStatsTable>(); } return cieifvlstatstable; } if(child_yang_name == "cieIfIndexPersistenceTable") { if(cieifindexpersistencetable == nullptr) { cieifindexpersistencetable = std::make_shared<CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable>(); } return cieifindexpersistencetable; } if(child_yang_name == "cieIfDot1qCustomEtherTypeTable") { if(cieifdot1qcustomethertypetable == nullptr) { cieifdot1qcustomethertypetable = std::make_shared<CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable>(); } return cieifdot1qcustomethertypetable; } if(child_yang_name == "cieIfUtilTable") { if(cieifutiltable == nullptr) { cieifutiltable = std::make_shared<CISCOIFEXTENSIONMIB::CieIfUtilTable>(); } return cieifutiltable; } if(child_yang_name == "cieIfDot1dBaseMappingTable") { if(cieifdot1dbasemappingtable == nullptr) { cieifdot1dbasemappingtable = std::make_shared<CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable>(); } return cieifdot1dbasemappingtable; } if(child_yang_name == "cieIfNameMappingTable") { if(cieifnamemappingtable == nullptr) { cieifnamemappingtable = std::make_shared<CISCOIFEXTENSIONMIB::CieIfNameMappingTable>(); } return cieifnamemappingtable; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(ciscoifextsystemconfig != nullptr) { _children["ciscoIfExtSystemConfig"] = ciscoifextsystemconfig; } if(cieifpacketstatstable != nullptr) { _children["cieIfPacketStatsTable"] = cieifpacketstatstable; } if(cieifinterfacetable != nullptr) { _children["cieIfInterfaceTable"] = cieifinterfacetable; } if(cieifstatuslisttable != nullptr) { _children["cieIfStatusListTable"] = cieifstatuslisttable; } if(cieifvlstatstable != nullptr) { _children["cieIfVlStatsTable"] = cieifvlstatstable; } if(cieifindexpersistencetable != nullptr) { _children["cieIfIndexPersistenceTable"] = cieifindexpersistencetable; } if(cieifdot1qcustomethertypetable != nullptr) { _children["cieIfDot1qCustomEtherTypeTable"] = cieifdot1qcustomethertypetable; } if(cieifutiltable != nullptr) { _children["cieIfUtilTable"] = cieifutiltable; } if(cieifdot1dbasemappingtable != nullptr) { _children["cieIfDot1dBaseMappingTable"] = cieifdot1dbasemappingtable; } if(cieifnamemappingtable != nullptr) { _children["cieIfNameMappingTable"] = cieifnamemappingtable; } return _children; } void CISCOIFEXTENSIONMIB::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::clone_ptr() const { return std::make_shared<CISCOIFEXTENSIONMIB>(); } std::string CISCOIFEXTENSIONMIB::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string CISCOIFEXTENSIONMIB::get_bundle_name() const { return "cisco_ios_xe"; } augment_capabilities_function CISCOIFEXTENSIONMIB::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> CISCOIFEXTENSIONMIB::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool CISCOIFEXTENSIONMIB::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ciscoIfExtSystemConfig" || name == "cieIfPacketStatsTable" || name == "cieIfInterfaceTable" || name == "cieIfStatusListTable" || name == "cieIfVlStatsTable" || name == "cieIfIndexPersistenceTable" || name == "cieIfDot1qCustomEtherTypeTable" || name == "cieIfUtilTable" || name == "cieIfDot1dBaseMappingTable" || name == "cieIfNameMappingTable") return true; return false; } CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::CiscoIfExtSystemConfig() : ciesystemmtu{YType::int32, "cieSystemMtu"}, cielinkupdownenable{YType::bits, "cieLinkUpDownEnable"}, ciestandardlinkupdownvarbinds{YType::enumeration, "cieStandardLinkUpDownVarbinds"}, cieifindexpersistence{YType::boolean, "cieIfIndexPersistence"}, ciedelayedlinkupdownnotifenable{YType::boolean, "cieDelayedLinkUpDownNotifEnable"}, ciedelayedlinkupdownnotifdelay{YType::uint32, "cieDelayedLinkUpDownNotifDelay"}, cieifindexglobalpersistence{YType::enumeration, "cieIfIndexGlobalPersistence"}, cielinkupdownconfig{YType::bits, "cieLinkUpDownConfig"} { yang_name = "ciscoIfExtSystemConfig"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::~CiscoIfExtSystemConfig() { } bool CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::has_data() const { if (is_presence_container) return true; return ciesystemmtu.is_set || cielinkupdownenable.is_set || ciestandardlinkupdownvarbinds.is_set || cieifindexpersistence.is_set || ciedelayedlinkupdownnotifenable.is_set || ciedelayedlinkupdownnotifdelay.is_set || cieifindexglobalpersistence.is_set || cielinkupdownconfig.is_set; } bool CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::has_operation() const { return is_set(yfilter) || ydk::is_set(ciesystemmtu.yfilter) || ydk::is_set(cielinkupdownenable.yfilter) || ydk::is_set(ciestandardlinkupdownvarbinds.yfilter) || ydk::is_set(cieifindexpersistence.yfilter) || ydk::is_set(ciedelayedlinkupdownnotifenable.yfilter) || ydk::is_set(ciedelayedlinkupdownnotifdelay.yfilter) || ydk::is_set(cieifindexglobalpersistence.yfilter) || ydk::is_set(cielinkupdownconfig.yfilter); } std::string CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ciscoIfExtSystemConfig"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ciesystemmtu.is_set || is_set(ciesystemmtu.yfilter)) leaf_name_data.push_back(ciesystemmtu.get_name_leafdata()); if (cielinkupdownenable.is_set || is_set(cielinkupdownenable.yfilter)) leaf_name_data.push_back(cielinkupdownenable.get_name_leafdata()); if (ciestandardlinkupdownvarbinds.is_set || is_set(ciestandardlinkupdownvarbinds.yfilter)) leaf_name_data.push_back(ciestandardlinkupdownvarbinds.get_name_leafdata()); if (cieifindexpersistence.is_set || is_set(cieifindexpersistence.yfilter)) leaf_name_data.push_back(cieifindexpersistence.get_name_leafdata()); if (ciedelayedlinkupdownnotifenable.is_set || is_set(ciedelayedlinkupdownnotifenable.yfilter)) leaf_name_data.push_back(ciedelayedlinkupdownnotifenable.get_name_leafdata()); if (ciedelayedlinkupdownnotifdelay.is_set || is_set(ciedelayedlinkupdownnotifdelay.yfilter)) leaf_name_data.push_back(ciedelayedlinkupdownnotifdelay.get_name_leafdata()); if (cieifindexglobalpersistence.is_set || is_set(cieifindexglobalpersistence.yfilter)) leaf_name_data.push_back(cieifindexglobalpersistence.get_name_leafdata()); if (cielinkupdownconfig.is_set || is_set(cielinkupdownconfig.yfilter)) leaf_name_data.push_back(cielinkupdownconfig.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "cieSystemMtu") { ciesystemmtu = value; ciesystemmtu.value_namespace = name_space; ciesystemmtu.value_namespace_prefix = name_space_prefix; } if(value_path == "cieLinkUpDownEnable") { cielinkupdownenable[value] = true; } if(value_path == "cieStandardLinkUpDownVarbinds") { ciestandardlinkupdownvarbinds = value; ciestandardlinkupdownvarbinds.value_namespace = name_space; ciestandardlinkupdownvarbinds.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfIndexPersistence") { cieifindexpersistence = value; cieifindexpersistence.value_namespace = name_space; cieifindexpersistence.value_namespace_prefix = name_space_prefix; } if(value_path == "cieDelayedLinkUpDownNotifEnable") { ciedelayedlinkupdownnotifenable = value; ciedelayedlinkupdownnotifenable.value_namespace = name_space; ciedelayedlinkupdownnotifenable.value_namespace_prefix = name_space_prefix; } if(value_path == "cieDelayedLinkUpDownNotifDelay") { ciedelayedlinkupdownnotifdelay = value; ciedelayedlinkupdownnotifdelay.value_namespace = name_space; ciedelayedlinkupdownnotifdelay.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfIndexGlobalPersistence") { cieifindexglobalpersistence = value; cieifindexglobalpersistence.value_namespace = name_space; cieifindexglobalpersistence.value_namespace_prefix = name_space_prefix; } if(value_path == "cieLinkUpDownConfig") { cielinkupdownconfig[value] = true; } } void CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "cieSystemMtu") { ciesystemmtu.yfilter = yfilter; } if(value_path == "cieLinkUpDownEnable") { cielinkupdownenable.yfilter = yfilter; } if(value_path == "cieStandardLinkUpDownVarbinds") { ciestandardlinkupdownvarbinds.yfilter = yfilter; } if(value_path == "cieIfIndexPersistence") { cieifindexpersistence.yfilter = yfilter; } if(value_path == "cieDelayedLinkUpDownNotifEnable") { ciedelayedlinkupdownnotifenable.yfilter = yfilter; } if(value_path == "cieDelayedLinkUpDownNotifDelay") { ciedelayedlinkupdownnotifdelay.yfilter = yfilter; } if(value_path == "cieIfIndexGlobalPersistence") { cieifindexglobalpersistence.yfilter = yfilter; } if(value_path == "cieLinkUpDownConfig") { cielinkupdownconfig.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieSystemMtu" || name == "cieLinkUpDownEnable" || name == "cieStandardLinkUpDownVarbinds" || name == "cieIfIndexPersistence" || name == "cieDelayedLinkUpDownNotifEnable" || name == "cieDelayedLinkUpDownNotifDelay" || name == "cieIfIndexGlobalPersistence" || name == "cieLinkUpDownConfig") return true; return false; } CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsTable() : cieifpacketstatsentry(this, {"ifindex"}) { yang_name = "cieIfPacketStatsTable"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::~CieIfPacketStatsTable() { } bool CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cieifpacketstatsentry.len(); index++) { if(cieifpacketstatsentry[index]->has_data()) return true; } return false; } bool CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::has_operation() const { for (std::size_t index=0; index<cieifpacketstatsentry.len(); index++) { if(cieifpacketstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfPacketStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cieIfPacketStatsEntry") { auto ent_ = std::make_shared<CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry>(); ent_->parent = this; cieifpacketstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cieifpacketstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfPacketStatsEntry") return true; return false; } CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::CieIfPacketStatsEntry() : ifindex{YType::str, "ifIndex"}, cieiflastintime{YType::uint32, "cieIfLastInTime"}, cieiflastouttime{YType::uint32, "cieIfLastOutTime"}, cieiflastouthangtime{YType::uint32, "cieIfLastOutHangTime"}, cieifinruntserrs{YType::uint32, "cieIfInRuntsErrs"}, cieifingiantserrs{YType::uint32, "cieIfInGiantsErrs"}, cieifinframingerrs{YType::uint32, "cieIfInFramingErrs"}, cieifinoverrunerrs{YType::uint32, "cieIfInOverrunErrs"}, cieifinignored{YType::uint32, "cieIfInIgnored"}, cieifinaborterrs{YType::uint32, "cieIfInAbortErrs"}, cieifinputqueuedrops{YType::uint32, "cieIfInputQueueDrops"}, cieifoutputqueuedrops{YType::uint32, "cieIfOutputQueueDrops"}, cieifpacketdiscontinuitytime{YType::uint32, "cieIfPacketDiscontinuityTime"} { yang_name = "cieIfPacketStatsEntry"; yang_parent_name = "cieIfPacketStatsTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::~CieIfPacketStatsEntry() { } bool CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::has_data() const { if (is_presence_container) return true; return ifindex.is_set || cieiflastintime.is_set || cieiflastouttime.is_set || cieiflastouthangtime.is_set || cieifinruntserrs.is_set || cieifingiantserrs.is_set || cieifinframingerrs.is_set || cieifinoverrunerrs.is_set || cieifinignored.is_set || cieifinaborterrs.is_set || cieifinputqueuedrops.is_set || cieifoutputqueuedrops.is_set || cieifpacketdiscontinuitytime.is_set; } bool CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ifindex.yfilter) || ydk::is_set(cieiflastintime.yfilter) || ydk::is_set(cieiflastouttime.yfilter) || ydk::is_set(cieiflastouthangtime.yfilter) || ydk::is_set(cieifinruntserrs.yfilter) || ydk::is_set(cieifingiantserrs.yfilter) || ydk::is_set(cieifinframingerrs.yfilter) || ydk::is_set(cieifinoverrunerrs.yfilter) || ydk::is_set(cieifinignored.yfilter) || ydk::is_set(cieifinaborterrs.yfilter) || ydk::is_set(cieifinputqueuedrops.yfilter) || ydk::is_set(cieifoutputqueuedrops.yfilter) || ydk::is_set(cieifpacketdiscontinuitytime.yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/cieIfPacketStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfPacketStatsEntry"; ADD_KEY_TOKEN(ifindex, "ifIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata()); if (cieiflastintime.is_set || is_set(cieiflastintime.yfilter)) leaf_name_data.push_back(cieiflastintime.get_name_leafdata()); if (cieiflastouttime.is_set || is_set(cieiflastouttime.yfilter)) leaf_name_data.push_back(cieiflastouttime.get_name_leafdata()); if (cieiflastouthangtime.is_set || is_set(cieiflastouthangtime.yfilter)) leaf_name_data.push_back(cieiflastouthangtime.get_name_leafdata()); if (cieifinruntserrs.is_set || is_set(cieifinruntserrs.yfilter)) leaf_name_data.push_back(cieifinruntserrs.get_name_leafdata()); if (cieifingiantserrs.is_set || is_set(cieifingiantserrs.yfilter)) leaf_name_data.push_back(cieifingiantserrs.get_name_leafdata()); if (cieifinframingerrs.is_set || is_set(cieifinframingerrs.yfilter)) leaf_name_data.push_back(cieifinframingerrs.get_name_leafdata()); if (cieifinoverrunerrs.is_set || is_set(cieifinoverrunerrs.yfilter)) leaf_name_data.push_back(cieifinoverrunerrs.get_name_leafdata()); if (cieifinignored.is_set || is_set(cieifinignored.yfilter)) leaf_name_data.push_back(cieifinignored.get_name_leafdata()); if (cieifinaborterrs.is_set || is_set(cieifinaborterrs.yfilter)) leaf_name_data.push_back(cieifinaborterrs.get_name_leafdata()); if (cieifinputqueuedrops.is_set || is_set(cieifinputqueuedrops.yfilter)) leaf_name_data.push_back(cieifinputqueuedrops.get_name_leafdata()); if (cieifoutputqueuedrops.is_set || is_set(cieifoutputqueuedrops.yfilter)) leaf_name_data.push_back(cieifoutputqueuedrops.get_name_leafdata()); if (cieifpacketdiscontinuitytime.is_set || is_set(cieifpacketdiscontinuitytime.yfilter)) leaf_name_data.push_back(cieifpacketdiscontinuitytime.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ifIndex") { ifindex = value; ifindex.value_namespace = name_space; ifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfLastInTime") { cieiflastintime = value; cieiflastintime.value_namespace = name_space; cieiflastintime.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfLastOutTime") { cieiflastouttime = value; cieiflastouttime.value_namespace = name_space; cieiflastouttime.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfLastOutHangTime") { cieiflastouthangtime = value; cieiflastouthangtime.value_namespace = name_space; cieiflastouthangtime.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInRuntsErrs") { cieifinruntserrs = value; cieifinruntserrs.value_namespace = name_space; cieifinruntserrs.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInGiantsErrs") { cieifingiantserrs = value; cieifingiantserrs.value_namespace = name_space; cieifingiantserrs.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInFramingErrs") { cieifinframingerrs = value; cieifinframingerrs.value_namespace = name_space; cieifinframingerrs.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInOverrunErrs") { cieifinoverrunerrs = value; cieifinoverrunerrs.value_namespace = name_space; cieifinoverrunerrs.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInIgnored") { cieifinignored = value; cieifinignored.value_namespace = name_space; cieifinignored.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInAbortErrs") { cieifinaborterrs = value; cieifinaborterrs.value_namespace = name_space; cieifinaborterrs.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInputQueueDrops") { cieifinputqueuedrops = value; cieifinputqueuedrops.value_namespace = name_space; cieifinputqueuedrops.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfOutputQueueDrops") { cieifoutputqueuedrops = value; cieifoutputqueuedrops.value_namespace = name_space; cieifoutputqueuedrops.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfPacketDiscontinuityTime") { cieifpacketdiscontinuitytime = value; cieifpacketdiscontinuitytime.value_namespace = name_space; cieifpacketdiscontinuitytime.value_namespace_prefix = name_space_prefix; } } void CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ifIndex") { ifindex.yfilter = yfilter; } if(value_path == "cieIfLastInTime") { cieiflastintime.yfilter = yfilter; } if(value_path == "cieIfLastOutTime") { cieiflastouttime.yfilter = yfilter; } if(value_path == "cieIfLastOutHangTime") { cieiflastouthangtime.yfilter = yfilter; } if(value_path == "cieIfInRuntsErrs") { cieifinruntserrs.yfilter = yfilter; } if(value_path == "cieIfInGiantsErrs") { cieifingiantserrs.yfilter = yfilter; } if(value_path == "cieIfInFramingErrs") { cieifinframingerrs.yfilter = yfilter; } if(value_path == "cieIfInOverrunErrs") { cieifinoverrunerrs.yfilter = yfilter; } if(value_path == "cieIfInIgnored") { cieifinignored.yfilter = yfilter; } if(value_path == "cieIfInAbortErrs") { cieifinaborterrs.yfilter = yfilter; } if(value_path == "cieIfInputQueueDrops") { cieifinputqueuedrops.yfilter = yfilter; } if(value_path == "cieIfOutputQueueDrops") { cieifoutputqueuedrops.yfilter = yfilter; } if(value_path == "cieIfPacketDiscontinuityTime") { cieifpacketdiscontinuitytime.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CieIfPacketStatsTable::CieIfPacketStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ifIndex" || name == "cieIfLastInTime" || name == "cieIfLastOutTime" || name == "cieIfLastOutHangTime" || name == "cieIfInRuntsErrs" || name == "cieIfInGiantsErrs" || name == "cieIfInFramingErrs" || name == "cieIfInOverrunErrs" || name == "cieIfInIgnored" || name == "cieIfInAbortErrs" || name == "cieIfInputQueueDrops" || name == "cieIfOutputQueueDrops" || name == "cieIfPacketDiscontinuityTime") return true; return false; } CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceTable() : cieifinterfaceentry(this, {"ifindex"}) { yang_name = "cieIfInterfaceTable"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfInterfaceTable::~CieIfInterfaceTable() { } bool CISCOIFEXTENSIONMIB::CieIfInterfaceTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cieifinterfaceentry.len(); index++) { if(cieifinterfaceentry[index]->has_data()) return true; } return false; } bool CISCOIFEXTENSIONMIB::CieIfInterfaceTable::has_operation() const { for (std::size_t index=0; index<cieifinterfaceentry.len(); index++) { if(cieifinterfaceentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfInterfaceTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfInterfaceTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfInterfaceTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfInterfaceTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfInterfaceTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cieIfInterfaceEntry") { auto ent_ = std::make_shared<CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry>(); ent_->parent = this; cieifinterfaceentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfInterfaceTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cieifinterfaceentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOIFEXTENSIONMIB::CieIfInterfaceTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::CieIfInterfaceTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOIFEXTENSIONMIB::CieIfInterfaceTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfInterfaceEntry") return true; return false; } CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfInterfaceEntry() : ifindex{YType::str, "ifIndex"}, cieifresetcount{YType::uint32, "cieIfResetCount"}, cieifkeepaliveenabled{YType::boolean, "cieIfKeepAliveEnabled"}, cieifstatechangereason{YType::str, "cieIfStateChangeReason"}, cieifcarriertransitioncount{YType::uint32, "cieIfCarrierTransitionCount"}, cieifinterfacediscontinuitytime{YType::uint32, "cieIfInterfaceDiscontinuityTime"}, cieifdhcpmode{YType::boolean, "cieIfDhcpMode"}, cieifmtu{YType::int32, "cieIfMtu"}, cieifcontextname{YType::str, "cieIfContextName"}, cieifoperstatuscause{YType::enumeration, "cieIfOperStatusCause"}, cieifoperstatuscausedescr{YType::str, "cieIfOperStatusCauseDescr"}, cieifspeedreceive{YType::uint32, "cieIfSpeedReceive"}, cieifhighspeedreceive{YType::uint32, "cieIfHighSpeedReceive"}, cieifowner{YType::str, "cieIfOwner"}, cieifsharedconfig{YType::enumeration, "cieIfSharedConfig"}, cieifspeedgroupconfig{YType::enumeration, "cieIfSpeedGroupConfig"}, cieiftransceiverfrequencyconfig{YType::enumeration, "cieIfTransceiverFrequencyConfig"}, cieiffillpatternconfig{YType::enumeration, "cieIfFillPatternConfig"}, cieifignorebiterrorsconfig{YType::boolean, "cieIfIgnoreBitErrorsConfig"}, cieifignoreinterruptthresholdconfig{YType::boolean, "cieIfIgnoreInterruptThresholdConfig"} { yang_name = "cieIfInterfaceEntry"; yang_parent_name = "cieIfInterfaceTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::~CieIfInterfaceEntry() { } bool CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::has_data() const { if (is_presence_container) return true; return ifindex.is_set || cieifresetcount.is_set || cieifkeepaliveenabled.is_set || cieifstatechangereason.is_set || cieifcarriertransitioncount.is_set || cieifinterfacediscontinuitytime.is_set || cieifdhcpmode.is_set || cieifmtu.is_set || cieifcontextname.is_set || cieifoperstatuscause.is_set || cieifoperstatuscausedescr.is_set || cieifspeedreceive.is_set || cieifhighspeedreceive.is_set || cieifowner.is_set || cieifsharedconfig.is_set || cieifspeedgroupconfig.is_set || cieiftransceiverfrequencyconfig.is_set || cieiffillpatternconfig.is_set || cieifignorebiterrorsconfig.is_set || cieifignoreinterruptthresholdconfig.is_set; } bool CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ifindex.yfilter) || ydk::is_set(cieifresetcount.yfilter) || ydk::is_set(cieifkeepaliveenabled.yfilter) || ydk::is_set(cieifstatechangereason.yfilter) || ydk::is_set(cieifcarriertransitioncount.yfilter) || ydk::is_set(cieifinterfacediscontinuitytime.yfilter) || ydk::is_set(cieifdhcpmode.yfilter) || ydk::is_set(cieifmtu.yfilter) || ydk::is_set(cieifcontextname.yfilter) || ydk::is_set(cieifoperstatuscause.yfilter) || ydk::is_set(cieifoperstatuscausedescr.yfilter) || ydk::is_set(cieifspeedreceive.yfilter) || ydk::is_set(cieifhighspeedreceive.yfilter) || ydk::is_set(cieifowner.yfilter) || ydk::is_set(cieifsharedconfig.yfilter) || ydk::is_set(cieifspeedgroupconfig.yfilter) || ydk::is_set(cieiftransceiverfrequencyconfig.yfilter) || ydk::is_set(cieiffillpatternconfig.yfilter) || ydk::is_set(cieifignorebiterrorsconfig.yfilter) || ydk::is_set(cieifignoreinterruptthresholdconfig.yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/cieIfInterfaceTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfInterfaceEntry"; ADD_KEY_TOKEN(ifindex, "ifIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata()); if (cieifresetcount.is_set || is_set(cieifresetcount.yfilter)) leaf_name_data.push_back(cieifresetcount.get_name_leafdata()); if (cieifkeepaliveenabled.is_set || is_set(cieifkeepaliveenabled.yfilter)) leaf_name_data.push_back(cieifkeepaliveenabled.get_name_leafdata()); if (cieifstatechangereason.is_set || is_set(cieifstatechangereason.yfilter)) leaf_name_data.push_back(cieifstatechangereason.get_name_leafdata()); if (cieifcarriertransitioncount.is_set || is_set(cieifcarriertransitioncount.yfilter)) leaf_name_data.push_back(cieifcarriertransitioncount.get_name_leafdata()); if (cieifinterfacediscontinuitytime.is_set || is_set(cieifinterfacediscontinuitytime.yfilter)) leaf_name_data.push_back(cieifinterfacediscontinuitytime.get_name_leafdata()); if (cieifdhcpmode.is_set || is_set(cieifdhcpmode.yfilter)) leaf_name_data.push_back(cieifdhcpmode.get_name_leafdata()); if (cieifmtu.is_set || is_set(cieifmtu.yfilter)) leaf_name_data.push_back(cieifmtu.get_name_leafdata()); if (cieifcontextname.is_set || is_set(cieifcontextname.yfilter)) leaf_name_data.push_back(cieifcontextname.get_name_leafdata()); if (cieifoperstatuscause.is_set || is_set(cieifoperstatuscause.yfilter)) leaf_name_data.push_back(cieifoperstatuscause.get_name_leafdata()); if (cieifoperstatuscausedescr.is_set || is_set(cieifoperstatuscausedescr.yfilter)) leaf_name_data.push_back(cieifoperstatuscausedescr.get_name_leafdata()); if (cieifspeedreceive.is_set || is_set(cieifspeedreceive.yfilter)) leaf_name_data.push_back(cieifspeedreceive.get_name_leafdata()); if (cieifhighspeedreceive.is_set || is_set(cieifhighspeedreceive.yfilter)) leaf_name_data.push_back(cieifhighspeedreceive.get_name_leafdata()); if (cieifowner.is_set || is_set(cieifowner.yfilter)) leaf_name_data.push_back(cieifowner.get_name_leafdata()); if (cieifsharedconfig.is_set || is_set(cieifsharedconfig.yfilter)) leaf_name_data.push_back(cieifsharedconfig.get_name_leafdata()); if (cieifspeedgroupconfig.is_set || is_set(cieifspeedgroupconfig.yfilter)) leaf_name_data.push_back(cieifspeedgroupconfig.get_name_leafdata()); if (cieiftransceiverfrequencyconfig.is_set || is_set(cieiftransceiverfrequencyconfig.yfilter)) leaf_name_data.push_back(cieiftransceiverfrequencyconfig.get_name_leafdata()); if (cieiffillpatternconfig.is_set || is_set(cieiffillpatternconfig.yfilter)) leaf_name_data.push_back(cieiffillpatternconfig.get_name_leafdata()); if (cieifignorebiterrorsconfig.is_set || is_set(cieifignorebiterrorsconfig.yfilter)) leaf_name_data.push_back(cieifignorebiterrorsconfig.get_name_leafdata()); if (cieifignoreinterruptthresholdconfig.is_set || is_set(cieifignoreinterruptthresholdconfig.yfilter)) leaf_name_data.push_back(cieifignoreinterruptthresholdconfig.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ifIndex") { ifindex = value; ifindex.value_namespace = name_space; ifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfResetCount") { cieifresetcount = value; cieifresetcount.value_namespace = name_space; cieifresetcount.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfKeepAliveEnabled") { cieifkeepaliveenabled = value; cieifkeepaliveenabled.value_namespace = name_space; cieifkeepaliveenabled.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfStateChangeReason") { cieifstatechangereason = value; cieifstatechangereason.value_namespace = name_space; cieifstatechangereason.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfCarrierTransitionCount") { cieifcarriertransitioncount = value; cieifcarriertransitioncount.value_namespace = name_space; cieifcarriertransitioncount.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInterfaceDiscontinuityTime") { cieifinterfacediscontinuitytime = value; cieifinterfacediscontinuitytime.value_namespace = name_space; cieifinterfacediscontinuitytime.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfDhcpMode") { cieifdhcpmode = value; cieifdhcpmode.value_namespace = name_space; cieifdhcpmode.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfMtu") { cieifmtu = value; cieifmtu.value_namespace = name_space; cieifmtu.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfContextName") { cieifcontextname = value; cieifcontextname.value_namespace = name_space; cieifcontextname.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfOperStatusCause") { cieifoperstatuscause = value; cieifoperstatuscause.value_namespace = name_space; cieifoperstatuscause.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfOperStatusCauseDescr") { cieifoperstatuscausedescr = value; cieifoperstatuscausedescr.value_namespace = name_space; cieifoperstatuscausedescr.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfSpeedReceive") { cieifspeedreceive = value; cieifspeedreceive.value_namespace = name_space; cieifspeedreceive.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfHighSpeedReceive") { cieifhighspeedreceive = value; cieifhighspeedreceive.value_namespace = name_space; cieifhighspeedreceive.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfOwner") { cieifowner = value; cieifowner.value_namespace = name_space; cieifowner.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfSharedConfig") { cieifsharedconfig = value; cieifsharedconfig.value_namespace = name_space; cieifsharedconfig.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfSpeedGroupConfig") { cieifspeedgroupconfig = value; cieifspeedgroupconfig.value_namespace = name_space; cieifspeedgroupconfig.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfTransceiverFrequencyConfig") { cieiftransceiverfrequencyconfig = value; cieiftransceiverfrequencyconfig.value_namespace = name_space; cieiftransceiverfrequencyconfig.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfFillPatternConfig") { cieiffillpatternconfig = value; cieiffillpatternconfig.value_namespace = name_space; cieiffillpatternconfig.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfIgnoreBitErrorsConfig") { cieifignorebiterrorsconfig = value; cieifignorebiterrorsconfig.value_namespace = name_space; cieifignorebiterrorsconfig.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfIgnoreInterruptThresholdConfig") { cieifignoreinterruptthresholdconfig = value; cieifignoreinterruptthresholdconfig.value_namespace = name_space; cieifignoreinterruptthresholdconfig.value_namespace_prefix = name_space_prefix; } } void CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ifIndex") { ifindex.yfilter = yfilter; } if(value_path == "cieIfResetCount") { cieifresetcount.yfilter = yfilter; } if(value_path == "cieIfKeepAliveEnabled") { cieifkeepaliveenabled.yfilter = yfilter; } if(value_path == "cieIfStateChangeReason") { cieifstatechangereason.yfilter = yfilter; } if(value_path == "cieIfCarrierTransitionCount") { cieifcarriertransitioncount.yfilter = yfilter; } if(value_path == "cieIfInterfaceDiscontinuityTime") { cieifinterfacediscontinuitytime.yfilter = yfilter; } if(value_path == "cieIfDhcpMode") { cieifdhcpmode.yfilter = yfilter; } if(value_path == "cieIfMtu") { cieifmtu.yfilter = yfilter; } if(value_path == "cieIfContextName") { cieifcontextname.yfilter = yfilter; } if(value_path == "cieIfOperStatusCause") { cieifoperstatuscause.yfilter = yfilter; } if(value_path == "cieIfOperStatusCauseDescr") { cieifoperstatuscausedescr.yfilter = yfilter; } if(value_path == "cieIfSpeedReceive") { cieifspeedreceive.yfilter = yfilter; } if(value_path == "cieIfHighSpeedReceive") { cieifhighspeedreceive.yfilter = yfilter; } if(value_path == "cieIfOwner") { cieifowner.yfilter = yfilter; } if(value_path == "cieIfSharedConfig") { cieifsharedconfig.yfilter = yfilter; } if(value_path == "cieIfSpeedGroupConfig") { cieifspeedgroupconfig.yfilter = yfilter; } if(value_path == "cieIfTransceiverFrequencyConfig") { cieiftransceiverfrequencyconfig.yfilter = yfilter; } if(value_path == "cieIfFillPatternConfig") { cieiffillpatternconfig.yfilter = yfilter; } if(value_path == "cieIfIgnoreBitErrorsConfig") { cieifignorebiterrorsconfig.yfilter = yfilter; } if(value_path == "cieIfIgnoreInterruptThresholdConfig") { cieifignoreinterruptthresholdconfig.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ifIndex" || name == "cieIfResetCount" || name == "cieIfKeepAliveEnabled" || name == "cieIfStateChangeReason" || name == "cieIfCarrierTransitionCount" || name == "cieIfInterfaceDiscontinuityTime" || name == "cieIfDhcpMode" || name == "cieIfMtu" || name == "cieIfContextName" || name == "cieIfOperStatusCause" || name == "cieIfOperStatusCauseDescr" || name == "cieIfSpeedReceive" || name == "cieIfHighSpeedReceive" || name == "cieIfOwner" || name == "cieIfSharedConfig" || name == "cieIfSpeedGroupConfig" || name == "cieIfTransceiverFrequencyConfig" || name == "cieIfFillPatternConfig" || name == "cieIfIgnoreBitErrorsConfig" || name == "cieIfIgnoreInterruptThresholdConfig") return true; return false; } CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListTable() : cieifstatuslistentry(this, {"entphysicalindex", "cieifstatuslistindex"}) { yang_name = "cieIfStatusListTable"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfStatusListTable::~CieIfStatusListTable() { } bool CISCOIFEXTENSIONMIB::CieIfStatusListTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cieifstatuslistentry.len(); index++) { if(cieifstatuslistentry[index]->has_data()) return true; } return false; } bool CISCOIFEXTENSIONMIB::CieIfStatusListTable::has_operation() const { for (std::size_t index=0; index<cieifstatuslistentry.len(); index++) { if(cieifstatuslistentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfStatusListTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfStatusListTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfStatusListTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfStatusListTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfStatusListTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cieIfStatusListEntry") { auto ent_ = std::make_shared<CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry>(); ent_->parent = this; cieifstatuslistentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfStatusListTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cieifstatuslistentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOIFEXTENSIONMIB::CieIfStatusListTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::CieIfStatusListTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOIFEXTENSIONMIB::CieIfStatusListTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfStatusListEntry") return true; return false; } CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::CieIfStatusListEntry() : entphysicalindex{YType::str, "entPhysicalIndex"}, cieifstatuslistindex{YType::uint32, "cieIfStatusListIndex"}, cieinterfacesindex{YType::str, "cieInterfacesIndex"}, cieinterfacesopermode{YType::str, "cieInterfacesOperMode"}, cieinterfacesopercause{YType::str, "cieInterfacesOperCause"}, cieinterfaceownershipbitmap{YType::str, "cieInterfaceOwnershipBitmap"} { yang_name = "cieIfStatusListEntry"; yang_parent_name = "cieIfStatusListTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::~CieIfStatusListEntry() { } bool CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::has_data() const { if (is_presence_container) return true; return entphysicalindex.is_set || cieifstatuslistindex.is_set || cieinterfacesindex.is_set || cieinterfacesopermode.is_set || cieinterfacesopercause.is_set || cieinterfaceownershipbitmap.is_set; } bool CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(entphysicalindex.yfilter) || ydk::is_set(cieifstatuslistindex.yfilter) || ydk::is_set(cieinterfacesindex.yfilter) || ydk::is_set(cieinterfacesopermode.yfilter) || ydk::is_set(cieinterfacesopercause.yfilter) || ydk::is_set(cieinterfaceownershipbitmap.yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/cieIfStatusListTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfStatusListEntry"; ADD_KEY_TOKEN(entphysicalindex, "entPhysicalIndex"); ADD_KEY_TOKEN(cieifstatuslistindex, "cieIfStatusListIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (entphysicalindex.is_set || is_set(entphysicalindex.yfilter)) leaf_name_data.push_back(entphysicalindex.get_name_leafdata()); if (cieifstatuslistindex.is_set || is_set(cieifstatuslistindex.yfilter)) leaf_name_data.push_back(cieifstatuslistindex.get_name_leafdata()); if (cieinterfacesindex.is_set || is_set(cieinterfacesindex.yfilter)) leaf_name_data.push_back(cieinterfacesindex.get_name_leafdata()); if (cieinterfacesopermode.is_set || is_set(cieinterfacesopermode.yfilter)) leaf_name_data.push_back(cieinterfacesopermode.get_name_leafdata()); if (cieinterfacesopercause.is_set || is_set(cieinterfacesopercause.yfilter)) leaf_name_data.push_back(cieinterfacesopercause.get_name_leafdata()); if (cieinterfaceownershipbitmap.is_set || is_set(cieinterfaceownershipbitmap.yfilter)) leaf_name_data.push_back(cieinterfaceownershipbitmap.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "entPhysicalIndex") { entphysicalindex = value; entphysicalindex.value_namespace = name_space; entphysicalindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfStatusListIndex") { cieifstatuslistindex = value; cieifstatuslistindex.value_namespace = name_space; cieifstatuslistindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieInterfacesIndex") { cieinterfacesindex = value; cieinterfacesindex.value_namespace = name_space; cieinterfacesindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieInterfacesOperMode") { cieinterfacesopermode = value; cieinterfacesopermode.value_namespace = name_space; cieinterfacesopermode.value_namespace_prefix = name_space_prefix; } if(value_path == "cieInterfacesOperCause") { cieinterfacesopercause = value; cieinterfacesopercause.value_namespace = name_space; cieinterfacesopercause.value_namespace_prefix = name_space_prefix; } if(value_path == "cieInterfaceOwnershipBitmap") { cieinterfaceownershipbitmap = value; cieinterfaceownershipbitmap.value_namespace = name_space; cieinterfaceownershipbitmap.value_namespace_prefix = name_space_prefix; } } void CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "entPhysicalIndex") { entphysicalindex.yfilter = yfilter; } if(value_path == "cieIfStatusListIndex") { cieifstatuslistindex.yfilter = yfilter; } if(value_path == "cieInterfacesIndex") { cieinterfacesindex.yfilter = yfilter; } if(value_path == "cieInterfacesOperMode") { cieinterfacesopermode.yfilter = yfilter; } if(value_path == "cieInterfacesOperCause") { cieinterfacesopercause.yfilter = yfilter; } if(value_path == "cieInterfaceOwnershipBitmap") { cieinterfaceownershipbitmap.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CieIfStatusListTable::CieIfStatusListEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "entPhysicalIndex" || name == "cieIfStatusListIndex" || name == "cieInterfacesIndex" || name == "cieInterfacesOperMode" || name == "cieInterfacesOperCause" || name == "cieInterfaceOwnershipBitmap") return true; return false; } CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsTable() : cieifvlstatsentry(this, {"ifindex"}) { yang_name = "cieIfVlStatsTable"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfVlStatsTable::~CieIfVlStatsTable() { } bool CISCOIFEXTENSIONMIB::CieIfVlStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cieifvlstatsentry.len(); index++) { if(cieifvlstatsentry[index]->has_data()) return true; } return false; } bool CISCOIFEXTENSIONMIB::CieIfVlStatsTable::has_operation() const { for (std::size_t index=0; index<cieifvlstatsentry.len(); index++) { if(cieifvlstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfVlStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfVlStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfVlStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfVlStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfVlStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cieIfVlStatsEntry") { auto ent_ = std::make_shared<CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry>(); ent_->parent = this; cieifvlstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfVlStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cieifvlstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOIFEXTENSIONMIB::CieIfVlStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::CieIfVlStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOIFEXTENSIONMIB::CieIfVlStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfVlStatsEntry") return true; return false; } CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::CieIfVlStatsEntry() : ifindex{YType::str, "ifIndex"}, cieifnodropvlinpkts{YType::uint64, "cieIfNoDropVlInPkts"}, cieifnodropvlinoctets{YType::uint64, "cieIfNoDropVlInOctets"}, cieifnodropvloutpkts{YType::uint64, "cieIfNoDropVlOutPkts"}, cieifnodropvloutoctets{YType::uint64, "cieIfNoDropVlOutOctets"}, cieifdropvlinpkts{YType::uint64, "cieIfDropVlInPkts"}, cieifdropvlinoctets{YType::uint64, "cieIfDropVlInOctets"}, cieifdropvloutpkts{YType::uint64, "cieIfDropVlOutPkts"}, cieifdropvloutoctets{YType::uint64, "cieIfDropVlOutOctets"} { yang_name = "cieIfVlStatsEntry"; yang_parent_name = "cieIfVlStatsTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::~CieIfVlStatsEntry() { } bool CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::has_data() const { if (is_presence_container) return true; return ifindex.is_set || cieifnodropvlinpkts.is_set || cieifnodropvlinoctets.is_set || cieifnodropvloutpkts.is_set || cieifnodropvloutoctets.is_set || cieifdropvlinpkts.is_set || cieifdropvlinoctets.is_set || cieifdropvloutpkts.is_set || cieifdropvloutoctets.is_set; } bool CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ifindex.yfilter) || ydk::is_set(cieifnodropvlinpkts.yfilter) || ydk::is_set(cieifnodropvlinoctets.yfilter) || ydk::is_set(cieifnodropvloutpkts.yfilter) || ydk::is_set(cieifnodropvloutoctets.yfilter) || ydk::is_set(cieifdropvlinpkts.yfilter) || ydk::is_set(cieifdropvlinoctets.yfilter) || ydk::is_set(cieifdropvloutpkts.yfilter) || ydk::is_set(cieifdropvloutoctets.yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/cieIfVlStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfVlStatsEntry"; ADD_KEY_TOKEN(ifindex, "ifIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata()); if (cieifnodropvlinpkts.is_set || is_set(cieifnodropvlinpkts.yfilter)) leaf_name_data.push_back(cieifnodropvlinpkts.get_name_leafdata()); if (cieifnodropvlinoctets.is_set || is_set(cieifnodropvlinoctets.yfilter)) leaf_name_data.push_back(cieifnodropvlinoctets.get_name_leafdata()); if (cieifnodropvloutpkts.is_set || is_set(cieifnodropvloutpkts.yfilter)) leaf_name_data.push_back(cieifnodropvloutpkts.get_name_leafdata()); if (cieifnodropvloutoctets.is_set || is_set(cieifnodropvloutoctets.yfilter)) leaf_name_data.push_back(cieifnodropvloutoctets.get_name_leafdata()); if (cieifdropvlinpkts.is_set || is_set(cieifdropvlinpkts.yfilter)) leaf_name_data.push_back(cieifdropvlinpkts.get_name_leafdata()); if (cieifdropvlinoctets.is_set || is_set(cieifdropvlinoctets.yfilter)) leaf_name_data.push_back(cieifdropvlinoctets.get_name_leafdata()); if (cieifdropvloutpkts.is_set || is_set(cieifdropvloutpkts.yfilter)) leaf_name_data.push_back(cieifdropvloutpkts.get_name_leafdata()); if (cieifdropvloutoctets.is_set || is_set(cieifdropvloutoctets.yfilter)) leaf_name_data.push_back(cieifdropvloutoctets.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ifIndex") { ifindex = value; ifindex.value_namespace = name_space; ifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfNoDropVlInPkts") { cieifnodropvlinpkts = value; cieifnodropvlinpkts.value_namespace = name_space; cieifnodropvlinpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfNoDropVlInOctets") { cieifnodropvlinoctets = value; cieifnodropvlinoctets.value_namespace = name_space; cieifnodropvlinoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfNoDropVlOutPkts") { cieifnodropvloutpkts = value; cieifnodropvloutpkts.value_namespace = name_space; cieifnodropvloutpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfNoDropVlOutOctets") { cieifnodropvloutoctets = value; cieifnodropvloutoctets.value_namespace = name_space; cieifnodropvloutoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfDropVlInPkts") { cieifdropvlinpkts = value; cieifdropvlinpkts.value_namespace = name_space; cieifdropvlinpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfDropVlInOctets") { cieifdropvlinoctets = value; cieifdropvlinoctets.value_namespace = name_space; cieifdropvlinoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfDropVlOutPkts") { cieifdropvloutpkts = value; cieifdropvloutpkts.value_namespace = name_space; cieifdropvloutpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfDropVlOutOctets") { cieifdropvloutoctets = value; cieifdropvloutoctets.value_namespace = name_space; cieifdropvloutoctets.value_namespace_prefix = name_space_prefix; } } void CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ifIndex") { ifindex.yfilter = yfilter; } if(value_path == "cieIfNoDropVlInPkts") { cieifnodropvlinpkts.yfilter = yfilter; } if(value_path == "cieIfNoDropVlInOctets") { cieifnodropvlinoctets.yfilter = yfilter; } if(value_path == "cieIfNoDropVlOutPkts") { cieifnodropvloutpkts.yfilter = yfilter; } if(value_path == "cieIfNoDropVlOutOctets") { cieifnodropvloutoctets.yfilter = yfilter; } if(value_path == "cieIfDropVlInPkts") { cieifdropvlinpkts.yfilter = yfilter; } if(value_path == "cieIfDropVlInOctets") { cieifdropvlinoctets.yfilter = yfilter; } if(value_path == "cieIfDropVlOutPkts") { cieifdropvloutpkts.yfilter = yfilter; } if(value_path == "cieIfDropVlOutOctets") { cieifdropvloutoctets.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CieIfVlStatsTable::CieIfVlStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ifIndex" || name == "cieIfNoDropVlInPkts" || name == "cieIfNoDropVlInOctets" || name == "cieIfNoDropVlOutPkts" || name == "cieIfNoDropVlOutOctets" || name == "cieIfDropVlInPkts" || name == "cieIfDropVlInOctets" || name == "cieIfDropVlOutPkts" || name == "cieIfDropVlOutOctets") return true; return false; } CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceTable() : cieifindexpersistenceentry(this, {"ifindex"}) { yang_name = "cieIfIndexPersistenceTable"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::~CieIfIndexPersistenceTable() { } bool CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cieifindexpersistenceentry.len(); index++) { if(cieifindexpersistenceentry[index]->has_data()) return true; } return false; } bool CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::has_operation() const { for (std::size_t index=0; index<cieifindexpersistenceentry.len(); index++) { if(cieifindexpersistenceentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfIndexPersistenceTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cieIfIndexPersistenceEntry") { auto ent_ = std::make_shared<CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry>(); ent_->parent = this; cieifindexpersistenceentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cieifindexpersistenceentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfIndexPersistenceEntry") return true; return false; } CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::CieIfIndexPersistenceEntry() : ifindex{YType::str, "ifIndex"}, cieifindexpersistenceenabled{YType::boolean, "cieIfIndexPersistenceEnabled"}, cieifindexpersistencecontrol{YType::enumeration, "cieIfIndexPersistenceControl"} { yang_name = "cieIfIndexPersistenceEntry"; yang_parent_name = "cieIfIndexPersistenceTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::~CieIfIndexPersistenceEntry() { } bool CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::has_data() const { if (is_presence_container) return true; return ifindex.is_set || cieifindexpersistenceenabled.is_set || cieifindexpersistencecontrol.is_set; } bool CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ifindex.yfilter) || ydk::is_set(cieifindexpersistenceenabled.yfilter) || ydk::is_set(cieifindexpersistencecontrol.yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/cieIfIndexPersistenceTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfIndexPersistenceEntry"; ADD_KEY_TOKEN(ifindex, "ifIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata()); if (cieifindexpersistenceenabled.is_set || is_set(cieifindexpersistenceenabled.yfilter)) leaf_name_data.push_back(cieifindexpersistenceenabled.get_name_leafdata()); if (cieifindexpersistencecontrol.is_set || is_set(cieifindexpersistencecontrol.yfilter)) leaf_name_data.push_back(cieifindexpersistencecontrol.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ifIndex") { ifindex = value; ifindex.value_namespace = name_space; ifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfIndexPersistenceEnabled") { cieifindexpersistenceenabled = value; cieifindexpersistenceenabled.value_namespace = name_space; cieifindexpersistenceenabled.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfIndexPersistenceControl") { cieifindexpersistencecontrol = value; cieifindexpersistencecontrol.value_namespace = name_space; cieifindexpersistencecontrol.value_namespace_prefix = name_space_prefix; } } void CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ifIndex") { ifindex.yfilter = yfilter; } if(value_path == "cieIfIndexPersistenceEnabled") { cieifindexpersistenceenabled.yfilter = yfilter; } if(value_path == "cieIfIndexPersistenceControl") { cieifindexpersistencecontrol.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CieIfIndexPersistenceTable::CieIfIndexPersistenceEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ifIndex" || name == "cieIfIndexPersistenceEnabled" || name == "cieIfIndexPersistenceControl") return true; return false; } CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeTable() : cieifdot1qcustomethertypeentry(this, {"ifindex"}) { yang_name = "cieIfDot1qCustomEtherTypeTable"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::~CieIfDot1qCustomEtherTypeTable() { } bool CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cieifdot1qcustomethertypeentry.len(); index++) { if(cieifdot1qcustomethertypeentry[index]->has_data()) return true; } return false; } bool CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::has_operation() const { for (std::size_t index=0; index<cieifdot1qcustomethertypeentry.len(); index++) { if(cieifdot1qcustomethertypeentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfDot1qCustomEtherTypeTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cieIfDot1qCustomEtherTypeEntry") { auto ent_ = std::make_shared<CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry>(); ent_->parent = this; cieifdot1qcustomethertypeentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cieifdot1qcustomethertypeentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfDot1qCustomEtherTypeEntry") return true; return false; } CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::CieIfDot1qCustomEtherTypeEntry() : ifindex{YType::str, "ifIndex"}, cieifdot1qcustomadminethertype{YType::int32, "cieIfDot1qCustomAdminEtherType"}, cieifdot1qcustomoperethertype{YType::int32, "cieIfDot1qCustomOperEtherType"} { yang_name = "cieIfDot1qCustomEtherTypeEntry"; yang_parent_name = "cieIfDot1qCustomEtherTypeTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::~CieIfDot1qCustomEtherTypeEntry() { } bool CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::has_data() const { if (is_presence_container) return true; return ifindex.is_set || cieifdot1qcustomadminethertype.is_set || cieifdot1qcustomoperethertype.is_set; } bool CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ifindex.yfilter) || ydk::is_set(cieifdot1qcustomadminethertype.yfilter) || ydk::is_set(cieifdot1qcustomoperethertype.yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/cieIfDot1qCustomEtherTypeTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfDot1qCustomEtherTypeEntry"; ADD_KEY_TOKEN(ifindex, "ifIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata()); if (cieifdot1qcustomadminethertype.is_set || is_set(cieifdot1qcustomadminethertype.yfilter)) leaf_name_data.push_back(cieifdot1qcustomadminethertype.get_name_leafdata()); if (cieifdot1qcustomoperethertype.is_set || is_set(cieifdot1qcustomoperethertype.yfilter)) leaf_name_data.push_back(cieifdot1qcustomoperethertype.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ifIndex") { ifindex = value; ifindex.value_namespace = name_space; ifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfDot1qCustomAdminEtherType") { cieifdot1qcustomadminethertype = value; cieifdot1qcustomadminethertype.value_namespace = name_space; cieifdot1qcustomadminethertype.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfDot1qCustomOperEtherType") { cieifdot1qcustomoperethertype = value; cieifdot1qcustomoperethertype.value_namespace = name_space; cieifdot1qcustomoperethertype.value_namespace_prefix = name_space_prefix; } } void CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ifIndex") { ifindex.yfilter = yfilter; } if(value_path == "cieIfDot1qCustomAdminEtherType") { cieifdot1qcustomadminethertype.yfilter = yfilter; } if(value_path == "cieIfDot1qCustomOperEtherType") { cieifdot1qcustomoperethertype.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CieIfDot1qCustomEtherTypeTable::CieIfDot1qCustomEtherTypeEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ifIndex" || name == "cieIfDot1qCustomAdminEtherType" || name == "cieIfDot1qCustomOperEtherType") return true; return false; } CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilTable() : cieifutilentry(this, {"ifindex"}) { yang_name = "cieIfUtilTable"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfUtilTable::~CieIfUtilTable() { } bool CISCOIFEXTENSIONMIB::CieIfUtilTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cieifutilentry.len(); index++) { if(cieifutilentry[index]->has_data()) return true; } return false; } bool CISCOIFEXTENSIONMIB::CieIfUtilTable::has_operation() const { for (std::size_t index=0; index<cieifutilentry.len(); index++) { if(cieifutilentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfUtilTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfUtilTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfUtilTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfUtilTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfUtilTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cieIfUtilEntry") { auto ent_ = std::make_shared<CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry>(); ent_->parent = this; cieifutilentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfUtilTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cieifutilentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOIFEXTENSIONMIB::CieIfUtilTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::CieIfUtilTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOIFEXTENSIONMIB::CieIfUtilTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfUtilEntry") return true; return false; } CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::CieIfUtilEntry() : ifindex{YType::str, "ifIndex"}, cieifinpktrate{YType::uint64, "cieIfInPktRate"}, cieifinoctetrate{YType::uint64, "cieIfInOctetRate"}, cieifoutpktrate{YType::uint64, "cieIfOutPktRate"}, cieifoutoctetrate{YType::uint64, "cieIfOutOctetRate"}, cieifinterval{YType::uint32, "cieIfInterval"} { yang_name = "cieIfUtilEntry"; yang_parent_name = "cieIfUtilTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::~CieIfUtilEntry() { } bool CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::has_data() const { if (is_presence_container) return true; return ifindex.is_set || cieifinpktrate.is_set || cieifinoctetrate.is_set || cieifoutpktrate.is_set || cieifoutoctetrate.is_set || cieifinterval.is_set; } bool CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ifindex.yfilter) || ydk::is_set(cieifinpktrate.yfilter) || ydk::is_set(cieifinoctetrate.yfilter) || ydk::is_set(cieifoutpktrate.yfilter) || ydk::is_set(cieifoutoctetrate.yfilter) || ydk::is_set(cieifinterval.yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/cieIfUtilTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfUtilEntry"; ADD_KEY_TOKEN(ifindex, "ifIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata()); if (cieifinpktrate.is_set || is_set(cieifinpktrate.yfilter)) leaf_name_data.push_back(cieifinpktrate.get_name_leafdata()); if (cieifinoctetrate.is_set || is_set(cieifinoctetrate.yfilter)) leaf_name_data.push_back(cieifinoctetrate.get_name_leafdata()); if (cieifoutpktrate.is_set || is_set(cieifoutpktrate.yfilter)) leaf_name_data.push_back(cieifoutpktrate.get_name_leafdata()); if (cieifoutoctetrate.is_set || is_set(cieifoutoctetrate.yfilter)) leaf_name_data.push_back(cieifoutoctetrate.get_name_leafdata()); if (cieifinterval.is_set || is_set(cieifinterval.yfilter)) leaf_name_data.push_back(cieifinterval.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ifIndex") { ifindex = value; ifindex.value_namespace = name_space; ifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInPktRate") { cieifinpktrate = value; cieifinpktrate.value_namespace = name_space; cieifinpktrate.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInOctetRate") { cieifinoctetrate = value; cieifinoctetrate.value_namespace = name_space; cieifinoctetrate.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfOutPktRate") { cieifoutpktrate = value; cieifoutpktrate.value_namespace = name_space; cieifoutpktrate.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfOutOctetRate") { cieifoutoctetrate = value; cieifoutoctetrate.value_namespace = name_space; cieifoutoctetrate.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfInterval") { cieifinterval = value; cieifinterval.value_namespace = name_space; cieifinterval.value_namespace_prefix = name_space_prefix; } } void CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ifIndex") { ifindex.yfilter = yfilter; } if(value_path == "cieIfInPktRate") { cieifinpktrate.yfilter = yfilter; } if(value_path == "cieIfInOctetRate") { cieifinoctetrate.yfilter = yfilter; } if(value_path == "cieIfOutPktRate") { cieifoutpktrate.yfilter = yfilter; } if(value_path == "cieIfOutOctetRate") { cieifoutoctetrate.yfilter = yfilter; } if(value_path == "cieIfInterval") { cieifinterval.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CieIfUtilTable::CieIfUtilEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ifIndex" || name == "cieIfInPktRate" || name == "cieIfInOctetRate" || name == "cieIfOutPktRate" || name == "cieIfOutOctetRate" || name == "cieIfInterval") return true; return false; } CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingTable() : cieifdot1dbasemappingentry(this, {"ifindex"}) { yang_name = "cieIfDot1dBaseMappingTable"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::~CieIfDot1dBaseMappingTable() { } bool CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cieifdot1dbasemappingentry.len(); index++) { if(cieifdot1dbasemappingentry[index]->has_data()) return true; } return false; } bool CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::has_operation() const { for (std::size_t index=0; index<cieifdot1dbasemappingentry.len(); index++) { if(cieifdot1dbasemappingentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfDot1dBaseMappingTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cieIfDot1dBaseMappingEntry") { auto ent_ = std::make_shared<CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry>(); ent_->parent = this; cieifdot1dbasemappingentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cieifdot1dbasemappingentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfDot1dBaseMappingEntry") return true; return false; } CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::CieIfDot1dBaseMappingEntry() : ifindex{YType::str, "ifIndex"}, cieifdot1dbasemappingport{YType::int32, "cieIfDot1dBaseMappingPort"} { yang_name = "cieIfDot1dBaseMappingEntry"; yang_parent_name = "cieIfDot1dBaseMappingTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::~CieIfDot1dBaseMappingEntry() { } bool CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::has_data() const { if (is_presence_container) return true; return ifindex.is_set || cieifdot1dbasemappingport.is_set; } bool CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ifindex.yfilter) || ydk::is_set(cieifdot1dbasemappingport.yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/cieIfDot1dBaseMappingTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfDot1dBaseMappingEntry"; ADD_KEY_TOKEN(ifindex, "ifIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ifindex.is_set || is_set(ifindex.yfilter)) leaf_name_data.push_back(ifindex.get_name_leafdata()); if (cieifdot1dbasemappingport.is_set || is_set(cieifdot1dbasemappingport.yfilter)) leaf_name_data.push_back(cieifdot1dbasemappingport.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ifIndex") { ifindex = value; ifindex.value_namespace = name_space; ifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfDot1dBaseMappingPort") { cieifdot1dbasemappingport = value; cieifdot1dbasemappingport.value_namespace = name_space; cieifdot1dbasemappingport.value_namespace_prefix = name_space_prefix; } } void CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ifIndex") { ifindex.yfilter = yfilter; } if(value_path == "cieIfDot1dBaseMappingPort") { cieifdot1dbasemappingport.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CieIfDot1dBaseMappingTable::CieIfDot1dBaseMappingEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ifIndex" || name == "cieIfDot1dBaseMappingPort") return true; return false; } CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingTable() : cieifnamemappingentry(this, {"cieifname"}) { yang_name = "cieIfNameMappingTable"; yang_parent_name = "CISCO-IF-EXTENSION-MIB"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfNameMappingTable::~CieIfNameMappingTable() { } bool CISCOIFEXTENSIONMIB::CieIfNameMappingTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<cieifnamemappingentry.len(); index++) { if(cieifnamemappingentry[index]->has_data()) return true; } return false; } bool CISCOIFEXTENSIONMIB::CieIfNameMappingTable::has_operation() const { for (std::size_t index=0; index<cieifnamemappingentry.len(); index++) { if(cieifnamemappingentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfNameMappingTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfNameMappingTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfNameMappingTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfNameMappingTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfNameMappingTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "cieIfNameMappingEntry") { auto ent_ = std::make_shared<CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry>(); ent_->parent = this; cieifnamemappingentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfNameMappingTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : cieifnamemappingentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void CISCOIFEXTENSIONMIB::CieIfNameMappingTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void CISCOIFEXTENSIONMIB::CieIfNameMappingTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool CISCOIFEXTENSIONMIB::CieIfNameMappingTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfNameMappingEntry") return true; return false; } CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::CieIfNameMappingEntry() : cieifname{YType::str, "cieIfName"}, cieifindex{YType::int32, "cieIfIndex"} { yang_name = "cieIfNameMappingEntry"; yang_parent_name = "cieIfNameMappingTable"; is_top_level_class = false; has_list_ancestor = false; } CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::~CieIfNameMappingEntry() { } bool CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::has_data() const { if (is_presence_container) return true; return cieifname.is_set || cieifindex.is_set; } bool CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(cieifname.yfilter) || ydk::is_set(cieifindex.yfilter); } std::string CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "CISCO-IF-EXTENSION-MIB:CISCO-IF-EXTENSION-MIB/cieIfNameMappingTable/" << get_segment_path(); return path_buffer.str(); } std::string CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "cieIfNameMappingEntry"; ADD_KEY_TOKEN(cieifname, "cieIfName"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (cieifname.is_set || is_set(cieifname.yfilter)) leaf_name_data.push_back(cieifname.get_name_leafdata()); if (cieifindex.is_set || is_set(cieifindex.yfilter)) leaf_name_data.push_back(cieifindex.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "cieIfName") { cieifname = value; cieifname.value_namespace = name_space; cieifname.value_namespace_prefix = name_space_prefix; } if(value_path == "cieIfIndex") { cieifindex = value; cieifindex.value_namespace = name_space; cieifindex.value_namespace_prefix = name_space_prefix; } } void CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "cieIfName") { cieifname.yfilter = yfilter; } if(value_path == "cieIfIndex") { cieifindex.yfilter = yfilter; } } bool CISCOIFEXTENSIONMIB::CieIfNameMappingTable::CieIfNameMappingEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "cieIfName" || name == "cieIfIndex") return true; return false; } const Enum::YLeaf IfIndexPersistenceState::disable {1, "disable"}; const Enum::YLeaf IfIndexPersistenceState::enable {2, "enable"}; const Enum::YLeaf IfIndexPersistenceState::global {3, "global"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::CieStandardLinkUpDownVarbinds::standard {1, "standard"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::CieStandardLinkUpDownVarbinds::additional {2, "additional"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CiscoIfExtSystemConfig::CieStandardLinkUpDownVarbinds::other {3, "other"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfSharedConfig::notApplicable {1, "notApplicable"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfSharedConfig::ownerDedicated {2, "ownerDedicated"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfSharedConfig::ownerShared {3, "ownerShared"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfSharedConfig::sharedOnly {4, "sharedOnly"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfSpeedGroupConfig::notApplicable {1, "notApplicable"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfSpeedGroupConfig::tenG {2, "tenG"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfSpeedGroupConfig::oneTwoFourEightG {3, "oneTwoFourEightG"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfSpeedGroupConfig::twoFourEightSixteenG {4, "twoFourEightSixteenG"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfTransceiverFrequencyConfig::notApplicable {1, "notApplicable"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfTransceiverFrequencyConfig::fibreChannel {2, "fibreChannel"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfTransceiverFrequencyConfig::ethernet {3, "ethernet"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfFillPatternConfig::arbff8G {1, "arbff8G"}; const Enum::YLeaf CISCOIFEXTENSIONMIB::CieIfInterfaceTable::CieIfInterfaceEntry::CieIfFillPatternConfig::idle8G {2, "idle8G"}; } }
37.293597
689
0.741694
[ "vector" ]
09fea2ccc2c50cc7eaf42280fdebaac234ebcb44
1,011
cxx
C++
languages/python/opa/pythonmodules.cxx
ouroboros-project/ouroboros
0edce6600f570a901a818161f77db9792f120e11
[ "Zlib" ]
1
2020-12-24T14:37:31.000Z
2020-12-24T14:37:31.000Z
languages/python/opa/pythonmodules.cxx
ouroboros-project/ouroboros
0edce6600f570a901a818161f77db9792f120e11
[ "Zlib" ]
null
null
null
languages/python/opa/pythonmodules.cxx
ouroboros-project/ouroboros
0edce6600f570a901a818161f77db9792f120e11
[ "Zlib" ]
null
null
null
#include <python/opa/modules.h> #include <vector> #include <cstdio> #include <opa/module.h> #include <python/opa/pythonmachine.h> namespace opa { namespace python { typedef std::vector< Module<inittype> > PythonModuleList; static PythonModuleList& get_module_list() { static PythonModuleList lua_modules; return lua_modules; } void AddModule(const Module<inittype> & module) { get_module_list().push_back(module); } void RegisterModules(PythonMachine* machine) { PythonModuleList& lua_modules = get_module_list(); for(PythonModuleList::const_iterator it = lua_modules.begin(); it != lua_modules.end(); ++it) { if(!machine->RegisterModule(*it)) { fprintf(stderr, "[%s] Load module '%s': >>ERROR<<\n", machine->lang_name().c_str(), it->name().c_str()); } else { #ifdef DEBUG fprintf(stderr, "[%s] Load module '%s': ok\n", machine->lang_name().c_str(), it->name().c_str()); #endif } } } } /* namespace python */ } /* namespace opa */
26.605263
116
0.661721
[ "vector" ]
6700c659199e16bc1ae11ed08fad03945afbbbac
645
cpp
C++
entity.cpp
rapucadyil/Rogue-Engine
08e8312641da796074e67015248dce117e52dae0
[ "BSD-3-Clause" ]
null
null
null
entity.cpp
rapucadyil/Rogue-Engine
08e8312641da796074e67015248dce117e52dae0
[ "BSD-3-Clause" ]
null
null
null
entity.cpp
rapucadyil/Rogue-Engine
08e8312641da796074e67015248dce117e52dae0
[ "BSD-3-Clause" ]
null
null
null
#include "entity.h" /* ENTITY CLASS */ Entity::Entity() { this->entity_id = 0; this->entity_name = "entity"; this->active = true; } Entity::Entity(u32 id, const str name, bool active) { this->entity_id = id; this->entity_name = name; this->active = active; } Entity::~Entity() { delete[] this->entity_name; //check this? this->entity_id = 0; } void Entity::update() { cout << "Updating..." << endl; } void Entity::render() { cout << "Rendering entity..." << endl; } void Entity::tick() { cout << "Ticking...but this is private" << endl; } /* ITEM CLASS */ void Item::update() {} void Item::render() {} void Item::tick() {}
16.538462
53
0.613953
[ "render" ]
670487b0556907422966eec9d99e7763a56ce0ee
7,034
cpp
C++
src/coherence/net/cache/BundlingNamedCache.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
src/coherence/net/cache/BundlingNamedCache.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
src/coherence/net/cache/BundlingNamedCache.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "coherence/net/cache/BundlingNamedCache.hpp" COH_OPEN_NAMESPACE3(coherence,net,cache) BundlingNamedCache::BundlingNamedCache(NamedCache::Handle hCache) : super(hCache), m_hGetBundler(self()), m_hPutBundler(self()), m_hRemoveBundler(self()) { } // ----- initiators --------------------------------------------------------- AbstractBundler::Handle BundlingNamedCache::ensureGetBundler(int32_t cBundleThreshold) { COH_SYNCHRONIZED(this) { if (cBundleThreshold > 0) { GetBundler::Handle hBundler = m_hGetBundler; if (hBundler == NULL) { m_hGetBundler = hBundler = GetBundler::create(this); } hBundler->setSizeThreshold(cBundleThreshold); return hBundler; } else { return m_hGetBundler = NULL; } } } AbstractBundler::Handle BundlingNamedCache::ensurePutBundler(int32_t cBundleThreshold) { COH_SYNCHRONIZED(this) { if (cBundleThreshold > 0) { PutBundler::Handle hBundler = m_hPutBundler; if (hBundler == NULL) { m_hPutBundler = hBundler = PutBundler::create(this); } hBundler->setSizeThreshold(cBundleThreshold); return hBundler; } else { return m_hPutBundler = NULL; } } } AbstractBundler::Handle BundlingNamedCache::ensureRemoveBundler(int32_t cBundleThreshold) { COH_SYNCHRONIZED(this) { if (cBundleThreshold > 0) { RemoveBundler::Handle hBundler = m_hRemoveBundler; if (hBundler == NULL) { m_hRemoveBundler = hBundler = RemoveBundler::create(this); } hBundler->setSizeThreshold(cBundleThreshold); return hBundler; } else { return m_hRemoveBundler = NULL; } } } // ----- accessors ---------------------------------------------------------- AbstractBundler::Handle BundlingNamedCache::getGetBundler() { return m_hGetBundler; } AbstractBundler::Handle BundlingNamedCache::getPutBundler() { return m_hPutBundler; } AbstractBundler::Handle BundlingNamedCache::getRemoveBundler() { return m_hRemoveBundler; } // ----- various bundleable NamedCache methods ------------------------------ Object::Holder BundlingNamedCache::get(Object::View vKey) { GetBundler::Handle hBundler = m_hGetBundler; return hBundler == NULL ? super::get(vKey) : hBundler->process(vKey); } Map::View BundlingNamedCache::getAll(Collection::View vColKeys) { GetBundler::Handle hBundler = m_hGetBundler; return hBundler == NULL ? super::getAll(vColKeys) : hBundler->processAll(vColKeys); } Object::Holder BundlingNamedCache::put(Object::View vKey, Object::Holder ohValue) { PutBundler::Handle hBundler = m_hPutBundler; if (hBundler == NULL) { super::putAll(Collections::singletonMap(vKey, ohValue)); } else { hBundler->process(vKey, ohValue); } return NULL; } void BundlingNamedCache::putAll(Map::View vMap) { PutBundler::Handle hBundler = m_hPutBundler; if (hBundler == NULL) { super::putAll(vMap); } else { hBundler->processAll(vMap); } } Object::Holder BundlingNamedCache::remove(Object::View vKey) { RemoveBundler::Handle hBundler = m_hRemoveBundler; if (hBundler == NULL) { super::remove(vKey); } else { hBundler->process(vKey); } return NULL; } // ----- NamedCache interface ----------------------------------------------- void BundlingNamedCache::release() { super::release(); m_hGetBundler = NULL; m_hPutBundler = NULL; m_hRemoveBundler = NULL; } void BundlingNamedCache::destroy() { super::destroy(); m_hGetBundler = NULL; m_hPutBundler = NULL; m_hRemoveBundler = NULL; } // ----- inner classes -------------------------------------------------- BundlingNamedCache::GetBundler::GetBundler(BundlingNamedCache::Handle hBundlingNamedCache) : f_hBundlingNamedCache(self(), hBundlingNamedCache) { AbstractBundler::Bundle::Handle hBundle = instantiateBundle(); init(hBundle); } Map::View BundlingNamedCache::GetBundler::bundle(Collection::View vColKeys) { return getBundlingNamedCache()->BundlingNamedCache::super::getAll(vColKeys); } Object::Holder BundlingNamedCache::GetBundler::unbundle(Object::View vKey) const { return getBundlingNamedCache()->BundlingNamedCache::super::get(vKey); } Object::Holder BundlingNamedCache::GetBundler::unbundle(Object::View vKey) { return getBundlingNamedCache()->BundlingNamedCache::super::get(vKey); } BundlingNamedCache::Handle BundlingNamedCache::GetBundler::getBundlingNamedCache() { return f_hBundlingNamedCache; } BundlingNamedCache::View BundlingNamedCache::GetBundler::getBundlingNamedCache() const { return f_hBundlingNamedCache; } BundlingNamedCache::PutBundler::PutBundler(BundlingNamedCache::Handle hBundlingNamedCache) : f_hBundlingNamedCache(self(), hBundlingNamedCache) { AbstractBundler::Bundle::Handle hBundle = instantiateBundle(); init(hBundle); } void BundlingNamedCache::PutBundler::bundle(Map::View vMap) { getBundlingNamedCache()->BundlingNamedCache::super::putAll(vMap); } BundlingNamedCache::Handle BundlingNamedCache::PutBundler::getBundlingNamedCache() { return f_hBundlingNamedCache; } BundlingNamedCache::View BundlingNamedCache::PutBundler::getBundlingNamedCache() const { return f_hBundlingNamedCache; } BundlingNamedCache::RemoveBundler::RemoveBundler(BundlingNamedCache::Handle hBundlingNamedCache) : f_hBundlingNamedCache(self(), hBundlingNamedCache) { AbstractBundler::Bundle::Handle hBundle = instantiateBundle(); init(hBundle); } Map::View BundlingNamedCache::RemoveBundler::bundle(Collection::View vColKeys) { getBundlingNamedCache()->keySet()->removeAll(vColKeys); return NULL; } Object::Holder BundlingNamedCache::RemoveBundler::unbundle(Object::View vKey) { getBundlingNamedCache()->keySet()->remove(vKey); return NULL; } BundlingNamedCache::Handle BundlingNamedCache::RemoveBundler::getBundlingNamedCache() { return f_hBundlingNamedCache; } BundlingNamedCache::View BundlingNamedCache::RemoveBundler::getBundlingNamedCache() const { return f_hBundlingNamedCache; } COH_CLOSE_NAMESPACE3
27.053846
96
0.623969
[ "object" ]
670585da94d4f0225231ed08799f78e46399d244
396
hh
C++
src/parser/grammar/grammar.hh
Turanic/WESH
0ff939415861b86ada705bcffd0e2eef6c841104
[ "Unlicense" ]
3
2015-08-07T18:29:10.000Z
2016-07-28T16:41:30.000Z
src/parser/grammar/grammar.hh
Turanic/wesh
0ff939415861b86ada705bcffd0e2eef6c841104
[ "Unlicense" ]
2
2015-09-27T09:30:11.000Z
2015-10-14T20:41:55.000Z
src/parser/grammar/grammar.hh
Turanic/WESH
0ff939415861b86ada705bcffd0e2eef6c841104
[ "Unlicense" ]
1
2017-10-18T19:41:45.000Z
2017-10-18T19:41:45.000Z
#pragma once #include <vector> #include <ast/ast.hh> #include <boost/spirit/home/x3.hpp> namespace parser { namespace grammar { using boost::spirit::x3::rule; struct wesh_rule_class; using wesh_rule_type = rule<wesh_rule_class, ast::ast_root>; using wesh_rule_id = wesh_rule_type::id; BOOST_SPIRIT_DECLARE(wesh_rule_type) } // grammar const grammar::wesh_rule_type& rule_get(); } // parser
17.217391
60
0.762626
[ "vector" ]
6707518cd804de4c28c908b4153f5822c35b3933
12,450
hpp
C++
include/pcp/algorithm/estimate_normals.hpp
Q-Minh/octree
0c3fd5a791d660b37461daf968a68ffb1c80b965
[ "BSL-1.0" ]
2
2021-03-10T09:57:45.000Z
2021-04-13T21:19:57.000Z
include/pcp/algorithm/estimate_normals.hpp
Q-Minh/octree
0c3fd5a791d660b37461daf968a68ffb1c80b965
[ "BSL-1.0" ]
22
2020-12-07T20:09:39.000Z
2021-04-12T20:42:59.000Z
include/pcp/algorithm/estimate_normals.hpp
Q-Minh/octree
0c3fd5a791d660b37461daf968a68ffb1c80b965
[ "BSL-1.0" ]
null
null
null
#ifndef PCP_ALGORITHM_ESTIMATE_NORMALS_HPP #define PCP_ALGORITHM_ESTIMATE_NORMALS_HPP /** * @file * @ingroup algorithm */ #include "pcp/common/norm.hpp" #include "pcp/common/normals/normal.hpp" #include "pcp/common/normals/normal_estimation.hpp" #include "pcp/common/points/point.hpp" #include "pcp/common/vector3d_queries.hpp" #include "pcp/graph/knn_adjacency_list.hpp" #include "pcp/graph/search.hpp" #include "pcp/traits/knn_map.hpp" #include "pcp/traits/normal_traits.hpp" #include "pcp/traits/point_traits.hpp" #include <execution> #include <iterator> #include <utility> namespace pcp { namespace algorithm { /** * @ingroup normals-estimation * @brief * Performs normal estimation on each k nearest neighborhood of the given sequence * of elements using tangent plane estimation through PCA. Results are stored * in the out sequence through op. * @tparam ForwardIter1 Type of input sequence iterator * @tparam ForwardIter2 Type of output sequence iterator * @tparam PointViewMap Type satisfying PointViewMap concept * @tparam KnnMap Callable type returning k neighborhood of input element * @tparam TransformOp Callable type returning an output element with parameters (input element, * normal) * @tparam Normal Type of normal * @tparam ExecutionPolicy Type of STL execution policy * @param policy The execution policy * @param begin Iterator to start of input sequence of elements * @param end Iterator to one past the end of input sequence of elements * @param out_begin Start iterator of output sequence * @param point_map The point view map property map * @param knn_map The callable object to query k nearest neighbors * @param op Transformation callable object taking an input element and its computed normal and * returning an output sequence element */ template < class ExecutionPolicy, class ForwardIter1, class ForwardIter2, class PointViewMap, class KnnMap, class TransformOp, class Normal = pcp::normal_t> void estimate_normals( ExecutionPolicy&& policy, ForwardIter1 begin, ForwardIter1 end, ForwardIter2 out_begin, PointViewMap const& point_map, KnnMap&& knn_map, TransformOp&& op) { using value_type = typename std::iterator_traits<ForwardIter1>::value_type; static_assert(traits::is_knn_map_v<KnnMap, value_type>, "knn_map must satisfy KnnMap concept"); using normal_type = Normal; static_assert(traits::is_normal_v<normal_type>, "Normal must satisfy Normal concept"); using result_type = typename std::iterator_traits<ForwardIter2>::value_type; static_assert( std::is_invocable_r_v<result_type, TransformOp, value_type, normal_type>, "op must be callable by result = op(Normal, *begin) where type of result is same as " "dereferencing out_begin decltype(*out_begin)"); auto const transform_op = [&, knn = std::forward<KnnMap>(knn_map), op = std::forward<TransformOp>(op)](value_type const& v) { auto const neighbor_points = knn(v); using iterator_type = decltype(neighbor_points.begin()); auto normal = pcp::estimate_normal<iterator_type, PointViewMap, normal_type>( std::begin(neighbor_points), std::end(neighbor_points), point_map); return op(v, normal); }; std::transform(std::forward<ExecutionPolicy>(policy), begin, end, out_begin, transform_op); } /** * @ingroup normals-estimation * @brief * Performs normal estimation on each k nearest neighborhood of the given sequence * of elements using tangent plane estimation through PCA. Results are stored * in the out sequence through op. * @tparam ForwardIter1 Type of input sequence iterator * @tparam ForwardIter2 Type of output sequence iterator * @tparam PointViewMap Type satisfying PointViewMap concept * @tparam KnnMap Callable type returning k neighborhood of input element * @tparam TransformOp Callable type returning an output element with parameters (input element, * normal) * @tparam Normal Type of normal * @param begin Iterator to start of input sequence of elements * @param end Iterator to one past the end of input sequence of elements * @param out_begin Start iterator of output sequence * @param point_map The point view map property map * @param knn_map The callable object to query k nearest neighbors * @param op Transformation callable object taking an input element and its computed normal and * returning an output sequence element */ template < class ForwardIter1, class ForwardIter2, class PointViewMap, class KnnMap, class TransformOp, class Normal = pcp::normal_t> void estimate_normals( ForwardIter1 begin, ForwardIter1 end, ForwardIter2 out_begin, PointViewMap const& point_map, KnnMap&& knn_map, TransformOp&& op) { /** * Ideally, we would just want to delegate the call to the version of estimate_normals * that uses an execution policy, and simply give it the sequenced policy, but doing so * does not support std::back_inserter. STL execution policies only work with at least * forward iterators, which back_inserter is not. For this reason, we have to duplicate * the normals estimation implementation. */ using value_type = typename std::iterator_traits<ForwardIter1>::value_type; static_assert(traits::is_knn_map_v<KnnMap, value_type>, "knn_map must satisfy KnnMap concept"); using normal_type = Normal; static_assert(traits::is_normal_v<normal_type>, "Normal must satisfy Normal concept"); using result_type = typename std::iterator_traits<ForwardIter2>::value_type; static_assert( std::is_invocable_r_v<result_type, TransformOp, value_type, normal_type>, "op must be callable by result = op(Normal, *begin) where type of result is same as " "dereferencing out_begin decltype(*out_begin)"); auto const transform_op = [&, knn = std::forward<KnnMap>(knn_map), op = std::forward<TransformOp>(op)](value_type const& v) { auto const neighbor_points = knn(v); using iterator_type = decltype(neighbor_points.begin()); auto normal = pcp::estimate_normal<iterator_type, PointViewMap, normal_type>( std::begin(neighbor_points), std::end(neighbor_points), point_map); return op(v, normal); }; std::transform(begin, end, out_begin, transform_op); } /** * @ingroup normals-estimation * @brief * Adjusts the orientations of a point cloud's normals using a minimum spanning tree * of the KNN graph of the point cloud, and propagating the MST's root's normal * through the MST. * * @tparam ForwardIter1 Type of input sequence iterator * @tparam IndexMap Type satisfying IndexMap concept * @tparam KnnMap Callable type computing the k neighborhood of an input element * @tparam PointViewMap Callable type returning a point from an input element * @tparam NormalMap Callable type returning a normal from an input element * @tparam TransformOp Callable type taking an input element and its oriented normal * @param begin * @param end * @param index_map The index map property map * @param knn_map Callable query object for k neighborhoods * @param point_map Callable object to get a point from an input element * @param normal_map Callable object to get a normal from an input element * @param op Transformation callable object taking an input element and its computed normal */ template < class ForwardIter1, class IndexMap, class KnnMap, class PointViewMap, class NormalMap, class TransformOp> void propagate_normal_orientations( ForwardIter1 begin, ForwardIter1 end, IndexMap const& index_map, KnnMap&& knn_map, PointViewMap&& point_map, NormalMap& normal_map, TransformOp&& op) { using input_element_type = typename std::iterator_traits<ForwardIter1>::value_type; static_assert( traits::is_knn_map_v<KnnMap, input_element_type>, "knn_map must satisfy KnnMap concept"); static_assert( std::is_invocable_v<NormalMap, input_element_type>, "NormalMap must be able to return normal from call to NormalMap(*begin)"); using normal_type = std::remove_reference_t< std::remove_cv_t<std::invoke_result_t<NormalMap, input_element_type>>>; static_assert( std::is_invocable_v<TransformOp, input_element_type, normal_type>, "TransformOp must be callable as op(*begin, normal_map(...))"); auto graph = graph::directed_knn_graph(begin, end, std::forward<KnnMap>(knn_map), index_map); auto [vbegin, vend] = graph.vertices(); auto const is_higher = [get_point = std::forward<PointViewMap>(point_map)](auto const& v1, auto const& v2) { auto const& p1 = get_point(v1); auto const& p2 = get_point(v2); return p1.z() < p2.z(); }; auto const root = std::max_element(vbegin, vend, is_higher); using floating_point_type = typename normal_type::component_type; op(*root, normal_type{ static_cast<floating_point_type>(0.0), static_cast<floating_point_type>(0.0), static_cast<floating_point_type>(1.0)}); /** * In Hoppe '92, normal orientation adjustments use a minimum spanning tree * using a cost function that assigns low weights to similarly oriented * normals, and high weights to normals approaching orthogonality. He then * traverses the MST and flips normal orientations when their inner-product * is negative. It seems that in our case, prim's minimum spanning tree algorithm * cannot work, since our k nearest neighbour graphs are directed rather than * undirected. The reason for the MST not working is not clear. We thought that * having an undirected graph in the form a directed graph where each undirected * edge is split into two parallel and opposite directed edges would be enough * for prim's mst algorithm to work, but I think it doesn't and I believe * that that is the culprit for the normal orientation adjustments not * working when using the MST version. */ // auto const cost = [normal_map](auto const& v1, auto const& v2) { // auto const& n1 = normal_map(v1); // auto const& n2 = normal_map(v2); // auto const prod = common::inner_product(n1, n2); // using floating_point_type = decltype(prod); // auto const one = static_cast<floating_point_type>(1.0); // return one - std::abs(prod); //}; // // auto [mst, get_root] = graph::prim_minimum_spanning_tree(graph, cost, root); // auto mst_root = get_root(mst); // graph::depth_first_search( // mst, // mst_root, // [op = std::forward<TransformOp>(op), normal_map](auto const& v1, auto const& v2) { // auto const& n1 = normal_map(v1); // auto const& n2 = normal_map(v2); // auto const prod = common::inner_product(n1, n2); // using floating_point_type = decltype(prod); // auto const zero = static_cast<floating_point_type>(0.0); // // flip normal orientation if // // the angle between n1, n2 is // // > 90 degrees // if (prod < zero) // { // op(v2, -n2); // } // }); /** * Use BFS (Breadth First Search) instead of Hoppe '92 MST propagation */ graph::breadth_first_search( graph, root, index_map, [op = std::forward<TransformOp>(op), normal_map](auto const& v1, auto const& v2) { auto const& n1 = normal_map(v1); auto const& n2 = normal_map(v2); auto const prod = common::inner_product(n1, n2); auto const zero = static_cast<floating_point_type>(0.0); // flip normal orientation if // the angle between n1, n2 is // > 90 degrees if (prod < zero && !common::floating_point_equals(prod, zero)) { op(v2, -n2); } }); } } // namespace algorithm } // namespace pcp #endif // PCP_ALGORITHM_ESTIMATE_NORMALS_HPP
40.553746
100
0.682008
[ "object", "transform" ]
67082bfb26ae830190d2e42400175b95a7fbbdbf
1,771
cpp
C++
sample/intrinsic/03_load_add/load_add.cpp
termoshtt/xbyak_aarch64_handson
bf8c318a4025077d52af91df7a61c5c12ca449fe
[ "MIT" ]
15
2021-11-18T07:17:24.000Z
2022-01-10T09:57:07.000Z
sample/intrinsic/03_load_add/load_add.cpp
termoshtt/xbyak_aarch64_handson
bf8c318a4025077d52af91df7a61c5c12ca449fe
[ "MIT" ]
2
2021-11-27T07:15:55.000Z
2021-11-28T01:58:29.000Z
sample/intrinsic/03_load_add/load_add.cpp
termoshtt/xbyak_aarch64_handson
bf8c318a4025077d52af91df7a61c5c12ca449fe
[ "MIT" ]
2
2021-11-27T04:33:56.000Z
2021-11-27T13:22:49.000Z
#include <arm_sve.h> #include <cstdio> #include <iostream> #include <vector> void svshow(svfloat64_t va) { int n = svcntd(); std::vector<double> a(n); svbool_t tp = svptrue_b64(); svst1_f64(tp, a.data(), va); for (int i = 0; i < n; i++) { printf("%+.7f ", a[n - i - 1]); } printf("\n"); } void load_pat() { int n = svcntd(); std::vector<double> a(n); for (int i = 0; i < n; i++) { a[i] = (i + 1); } svbool_t tp = svptrue_b64(); svfloat64_t va = svld1_f64(tp, a.data()); svbool_t tp2 = svptrue_pat_b64(SV_VL2); svfloat64_t vb = svld1_f64(tp2, a.data()); std::cout << "va = " << std::endl; svshow(va); std::cout << "vb = " << std::endl; svshow(vb); } void add_all(svfloat64_t va, svfloat64_t vb) { svfloat64_t vc = svadd_f64_z(svptrue_b64(), va, vb); printf("va + vb (ALL) = "); svshow(vc); } int main() { double a[] = {0, 1, 2, 3, 4, 5, 6, 7}; svfloat64_t va = svld1_f64(svptrue_b64(), a); printf("va = "); svshow(va); double b[] = {1, 1, 1, 1, 1, 1, 1, 1}; svfloat64_t vb = svld1_f64(svptrue_b64(), b); printf("vb = "); svshow(vb); printf("\n"); printf("Add all\n"); printf("svadd_f64_z(svptrue_b64(), va, vb)\n"); svfloat64_t vc1 = svadd_f64_z(svptrue_b64(), va, vb); printf("va + vb = "); svshow(vc1); printf("\n"); printf("pattern VL2 with zero clear\n"); printf("svadd_f64_z(svptrue_pat_b64(SV_VL2), va, vb)\n"); svfloat64_t vc2 = svadd_f64_z(svptrue_pat_b64(SV_VL2), va, vb); printf("va + vb = "); svshow(vc2); printf("\n"); printf("pattern VL2 with merging the first input\n"); printf("svadd_f64_m(svptrue_pat_b64(SV_VL2), va, vb)\n"); svfloat64_t vc3 = svadd_f64_m(svptrue_pat_b64(SV_VL2), va, vb); printf("va + vb = "); svshow(vc3); printf("\n"); }
24.597222
65
0.59345
[ "vector" ]
670c8d19cbfee3315f15b38f66023c9f79356c43
814
hpp
C++
src/projects/repeat_resolution/mdbg_vertex_processor.hpp
fedarko/LJA
f20c85395d741b0f94f6d0172c7451d72d7c8713
[ "BSD-3-Clause" ]
null
null
null
src/projects/repeat_resolution/mdbg_vertex_processor.hpp
fedarko/LJA
f20c85395d741b0f94f6d0172c7451d72d7c8713
[ "BSD-3-Clause" ]
null
null
null
src/projects/repeat_resolution/mdbg_vertex_processor.hpp
fedarko/LJA
f20c85395d741b0f94f6d0172c7451d72d7c8713
[ "BSD-3-Clause" ]
null
null
null
// // Created by Andrey Bzikadze on 11/25/21. // #pragma once #include "mdbg.hpp" namespace repeat_resolution { class MDBGSimpleVertexProcessor { void Process0In1Pout(MultiplexDBG &graph, const RRVertexType &vertex); void Process1Pin0Out(MultiplexDBG &graph, const RRVertexType &vertex); public: void Process(MultiplexDBG &graph, const RRVertexType &vertex, uint64_t n_iter); }; class MDBGComplexVertexProcessor { std::pair<std::unordered_map<RREdgeIndexType, RRVertexType>, std::vector<RRVertexType>> SplitVertex(MultiplexDBG &graph, const RRVertexType &vertex); public: void Process(MultiplexDBG &graph, const RRVertexType &vertex, std::set<Sequence> &merged_self_loops); }; } // End namespace repeat_resolution
24.666667
74
0.700246
[ "vector" ]
e252947acbbfaab535cf068743353adc78a18257
1,901
cpp
C++
C++/13_Two_pointers/MEDIUM_3SUM.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/13_Two_pointers/MEDIUM_3SUM.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/13_Two_pointers/MEDIUM_3SUM.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
/* Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] */ // I was trying a hash table based technique, but couldn't get it to work // http://www.geeksforgeeks.org/find-a-triplet-that-sum-to-a-given-value/ // Optimal solution - O(n^2) vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > res; std::sort(num.begin(), num.end()); for (int i = 0; i < num.size(); i++) { int target = -num[i]; int front = i + 1; int back = num.size() - 1; while (front < back) { int sum = num[front] + num[back]; // Finding answer which start from number num[i] if (sum < target) front++; else if (sum > target) back--; else { vector<int> triplet(3, 0); triplet[0] = num[i]; triplet[1] = num[front]; triplet[2] = num[back]; res.push_back(triplet); // Processing duplicates of Number 2 // Rolling the front pointer to the next different number forwards while (front < back && num[front] == triplet[1]) front++; // Processing duplicates of Number 3 // Rolling the back pointer to the next different number backwards while (front < back && num[back] == triplet[2]) back--; } } // Processing duplicates of Number 1 while (i + 1 < num.size() && num[i + 1] == num[i]) i++; } return res; }
27.955882
92
0.500263
[ "vector" ]
e252f85523742ccf0b6d579885155402572c6b84
2,832
cpp
C++
src/systemif.cpp
hugoboss00/HeaterMeter
0aee2e7189753da69e73319b8684af0132f18ed5
[ "MIT" ]
2
2018-07-19T12:14:57.000Z
2018-07-19T12:14:59.000Z
src/systemif.cpp
hugoboss00/HeaterMeter
0aee2e7189753da69e73319b8684af0132f18ed5
[ "MIT" ]
null
null
null
src/systemif.cpp
hugoboss00/HeaterMeter
0aee2e7189753da69e73319b8684af0132f18ed5
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/shm.h> #include <sys/stat.h> #include <inttypes.h> #include <math.h> #include <time.h> #include "systemif.h" #include <unistd.h> #include <sys/mman.h> const char *hm_version = VERSION; #ifdef PIN_SIMULATION typedef struct { char name[16]; int value; } tSIMPIN; static tSIMPIN *simpins = NULL; int init_shm() { if (simpins == NULL) { /* the size (in bytes) of shared memory object */ const int SIZE = 4096; /* name of the shared memory object */ const char* name = "/SIMPIN"; /* shared memory file descriptor */ int shm_fd; /* pointer to shared memory obect */ void* ptr; /* create the shared memory object */ shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666); if (shm_fd <= 0) perror("shm_open"); /* configure the size of the shared memory object */ if (ftruncate(shm_fd, SIZE) < 0) { simpins = NULL; return -1; } /* memory map the shared memory object */ ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0); if (ptr == MAP_FAILED) { printf("Error to map shared memory\n"); perror("mmap"); simpins = NULL; return -1; } simpins = (tSIMPIN *)ptr; memset(ptr, 0, SIZE); } return 0; } void pinset(char *key, int value) { int index = 0; init_shm(); while ((index < 32) && (simpins[index].name[0] != 0)) { if (strncmp(simpins[index].name, key, sizeof(simpins[index].name) ) == 0) { simpins[index].value = value; return; } index++; } if (index < 32) { simpins[index].value = value; strncpy(simpins[index].name, key, sizeof(simpins[index].name)-1); return; } } int pinget(char *key) { int value = 0; int index = 0; init_shm(); while ((index < 32) && (simpins[index].name[0] != 0)) { if (strncmp(simpins[index].name, key, sizeof(simpins[index].name) ) == 0) { value = simpins[index].value; } index++; } return value; } #endif unsigned int millis (void) { long ms; // Milliseconds struct timespec spec; clock_gettime(CLOCK_MONOTONIC, &spec); ms = spec.tv_sec * 1000; ms += round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds return ms; } void delayMicroseconds(int us) { struct timespec req={0}; req.tv_sec=0; req.tv_nsec= us*1000 ; clock_nanosleep(CLOCK_MONOTONIC, 0, &req, NULL); return; #if 0 struct timespec a; a.tv_nsec=(us) * 1000L; a.tv_sec=0; if (nanosleep(&a, NULL) != 0) { perror("delay_ms error:"); } #endif #if 0 int delay = us ; if (delay == 0) delay = 1; usleep(delay); #endif } void digitalWrite(int pin, int on) { #ifdef PIN_SIMULATION char buf[20]; sprintf(buf, "gpio%d", pin); pinset(buf, on); #else #endif } void pinMode(int pin, int mode) { #ifdef PIN_SIMULATION #else #endif }
17.268293
77
0.623234
[ "object" ]
e2556cb374f8d82e29bf6b2d7b2a065ccaf5a31c
1,620
cpp
C++
Engine/Source/Manager/ColorManager.cpp
ReDEnergy/OpenGL4.5-GameEngine
79468b7807677372bbc0450ea49b48ad66bbbd41
[ "MIT" ]
11
2016-02-18T03:22:33.000Z
2021-01-21T13:05:30.000Z
Engine/Source/Manager/ColorManager.cpp
ReDEnergy/OpenGL4.5-GameEngine
79468b7807677372bbc0450ea49b48ad66bbbd41
[ "MIT" ]
3
2015-04-26T09:52:12.000Z
2015-05-13T13:06:58.000Z
Engine/Source/Manager/ColorManager.cpp
ReDEnergy/GameEngine
79468b7807677372bbc0450ea49b48ad66bbbd41
[ "MIT" ]
11
2015-03-14T13:35:22.000Z
2015-09-16T16:26:08.000Z
#include "ColorManager.h" #include <Core/GameObject.h> typedef unsigned int uint; ColorManager::ColorManager() { colorID = glm::ivec3(255, 255, 255); offset = glm::ivec3(1, 1, 1); auto size = colorID / offset; colorMap.resize(size.x + size.y * 16 + size.z * 256); } ColorManager::~ColorManager() { } unsigned int ColorManager::GetObjectUID(GameObject * object) { auto uid = colorID.x / offset.x + colorID.y * 16 / offset.y + colorID.z * 256 / offset.z; return uid; } glm::vec3 ColorManager::GetColorUID(GameObject* object) { if (colorID.z > 0) { colorID.z -= offset.z; } else { colorID.z = 255; if(colorID.y > 0) { colorID.y -= offset.y; } else { colorID.y = 255; if (colorID.x > 0) { colorID.x -= offset.x; } } } auto uid = colorID.x / offset.x + colorID.y * 16 / offset.y + colorID.z * 256 / offset.z; colorMap[uid] = object; return glm::vec3(colorID) / 255.0f; } glm::ivec3 ColorManager::GetOffsetID() const { return offset; } glm::ivec3 ColorManager::GetChannelsEncodeSize() const { return glm::ivec3(255 / offset.x, 255 / offset.y, 255 / offset.z); } GameObject* ColorManager::GetObjectByColor(const glm::ivec3 &color) const { unsigned int UID = color[0] / offset.x + color[1] * 16 / offset.y + color[2] * 256 / offset.z; if (UID < colorMap.size()) { return colorMap[UID]; } else { printf("[ColorManager][ERROR] color ID out of range\n"); return nullptr; } } GameObject* ColorManager::GetObjectByID(unsigned int ID) const { if (ID < colorMap.size()) return colorMap[ID]; printf("[ColorManager][ERROR] color ID out of range\n"); return nullptr; }
21.315789
96
0.658025
[ "object" ]
e25bde243c4f6d9a2f8f2b6b1c480bcaf7de3d69
52,530
cpp
C++
da/src/da/da_icp_laser.cpp
anpl-technion/anpl_mrbsp
973734fd2d1c7bb5e1405922300add489f088e81
[ "MIT" ]
1
2021-12-03T03:11:20.000Z
2021-12-03T03:11:20.000Z
da/src/da/da_icp_laser.cpp
anpl-technion/anpl_mrbsp
973734fd2d1c7bb5e1405922300add489f088e81
[ "MIT" ]
null
null
null
da/src/da/da_icp_laser.cpp
anpl-technion/anpl_mrbsp
973734fd2d1c7bb5e1405922300add489f088e81
[ "MIT" ]
1
2021-12-03T03:11:23.000Z
2021-12-03T03:11:23.000Z
/* --------------------------------------------------------------------------- * * Autonomous Navigation and Perception Lab (ANPL), * Technion, Israel Institute of Technology, * Faculty of Aerospace Engineering, * Haifa, Israel, 32000 * All Rights Reserved * * See LICENSE for the license information * * -------------------------------------------------------------------------- */ /** * @file: da_icp_laser.cpp * @brief: * @author: Tal Regev */ #include "da/da_icp_laser.h" #include <fstream> #include <planar_icp/planarICP.h> #include <mrbsp_msgs/GtsamFactorGraph.h> #include <mrbsp_msgs/MapData.h> #include <mrbsp_msgs/MapData3D.h> #include <mrbsp_utils/mrbsp_utils.h> #include <mrbsp_utils/gtsam_serialization.h> #include <gtsam/base/serialization.h> #include <signal.h> // defined duo to deserialization round in matlab #define MIN_ROTATION_NOISE_SIGMA 1E-6 #define MIN_TRANSLATION_NOISE_SIGMA 1E-3 using namespace MRBSP; using namespace MRBSP::Utils; void mySigintHandler(int sig) { Utils::LogTag tag = LogTag::da; FUNCTION_LOGGER(tag); std::stringstream logger_msg; logger_msg << "Shutting down " << ros::this_node::getName().substr(1) << " node"; logMessage(info, LOG_INFO_LVL, logger_msg, tag); ros::shutdown(); } int main(int argc, char** argv) { FUNCTION_LOGGER(LogTag::da); ros::init(argc, argv, "DaIcpLaser"); signal(SIGINT, mySigintHandler); ros::NodeHandle pnh("~"); DaIcpLaser da_laser(pnh); ros::AsyncSpinner spinner(4); // Use 4 threads /* * 1) Sliding window thread * 2) Loop closure thread * 3) Multi-Robot thread * 4) Memory update thread */ spinner.start(); ros::waitForShutdown(); return 0; } DaIcpLaser::DaIcpLaser(const ros::NodeHandle &nh_private) : m_privateNodeHandle(nh_private), m_is_init(false) { m_tag = LogTag::odometry; FUNCTION_LOGGER(m_tag); m_node_name = ros::this_node::getName().substr(1); if (!m_privateNodeHandle.hasParam("/scenario_folder")) { m_logger_msg << m_node_name << " node load without parameters.\n exiting node."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); ros::shutdown(); return; } initLogger(m_privateNodeHandle); loadParameter(); //m_central_prefix = "/Central/"; m_central_prefix = "/"; //m_robots_prefix = "/Robots/"; m_robots_prefix = "/"; // keyframes with pointclouds m_keyframe_init_rgbd_sub = m_privateNodeHandle.subscribe(m_robots_prefix + "Odometry/keyframe/withPointcloud", 1, &DaIcpLaser::KeyframeRgbdCallback, this); m_map_data_3D_pub = m_privateNodeHandle.advertise<mrbsp_msgs::MapData3D>(m_central_prefix + "DA/map_data/3D", 1); // keyframes without pointclouds m_keyframe_init_sub = m_privateNodeHandle.subscribe(m_robots_prefix + "Odometry/keyframe", 1, &DaIcpLaser::KeyframeCallback, this); m_map_data_2D_pub = m_privateNodeHandle.advertise<mrbsp_msgs::MapData>(m_central_prefix + "DA/map_data/2D", 1); m_updated_values_sub = m_privateNodeHandle.subscribe(m_central_prefix + "Belief/memory_update", 1, &DaIcpLaser::updateMemoryCallback, this); m_loop_closure_pub = m_privateNodeHandle.advertise<mrbsp_msgs::Keyframe>(m_central_prefix + "DA/LoopClosure", 5); m_loop_closure_sub = m_privateNodeHandle.subscribe(m_central_prefix + "DA/LoopClosure", 1, &DaIcpLaser::loopClosureCallback, this); m_multirobot_pub = m_privateNodeHandle.advertise<mrbsp_msgs::Keyframe>(m_central_prefix + "DA/MultiRobot", 5); m_multirobot_sub = m_privateNodeHandle.subscribe(m_central_prefix + "DA/MultiRobot", 1, &DaIcpLaser::multiRobotCallback, this); m_factors_and_values_pub = m_privateNodeHandle.advertise<mrbsp_msgs::GtsamFactorGraph>(m_central_prefix + "belief_input", 1); m_da_check_last_index = m_privateNodeHandle.advertiseService(m_central_prefix + "da_check_last_index", &DaIcpLaser::daCheckLastIndex, this); m_is_init = true; m_da_init_check_service = m_privateNodeHandle.advertiseService(m_central_prefix + "da_init_check", &DaIcpLaser::daInitCheck, this); m_logger_msg << "da node initialized..."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } void DaIcpLaser::loadParameter() { FUNCTION_LOGGER(m_tag); m_logger_msg << m_node_name << " node parameters:"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "====================="; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); // get parameters for loop closure detection and multi robot factors m_privateNodeHandle.param("loop_closure/perform", m_perform_lc, true); m_privateNodeHandle.param("loop_closure/parallel", m_parallel_lc, true); m_privateNodeHandle.param("loop_closure/min_index_range", m_lc_min_idx_range, 10.0); m_privateNodeHandle.param("loop_closure/spatial_search_range", m_lc_spatial_search_range, 5.0); m_privateNodeHandle.param("multi_robot/perform", m_perform_mr, true); m_privateNodeHandle.param("multi_robot/parallel", m_parallel_mr, true); m_privateNodeHandle.param("multi_robot/spatial_search_range", m_mr_spatial_search_range, 2.0); m_privateNodeHandle.param("enforce_perfect_DA", m_enforcing_perfect_DA, false); // get icp thresholds parameters m_privateNodeHandle.param("icp/max_iters", m_icp_max_iters, 50); m_privateNodeHandle.param("icp/stopping_thresh", m_icp_stopping_thresh, 0.000001); // [m] m_privateNodeHandle.param("icp/inlier_thresh_sq", m_icp_inlier_thresh_sq, 0.5); // [m] m_privateNodeHandle.param("icp/nn_matching_percentage/sliding_window", m_icp_window_nn_pct_thresh, 0.0); // [%] m_privateNodeHandle.param("icp/nn_matching_percentage/loop_closure", m_icp_lc_nn_pct_thresh, 0.0); // [%] m_privateNodeHandle.param("icp/nn_matching_percentage/multi_robot", m_icp_mr_nn_pct_thresh, 0.0); // [%] // get noise model parameters double sigma_yaw_prior; double sigma_pitch_prior; double sigma_roll_prior; double sigma_x_prior; double sigma_y_prior; double sigma_z_prior; double sigma_yaw_odom; double sigma_pitch_odom; double sigma_roll_odom; double sigma_x_odom; double sigma_y_odom; double sigma_z_odom; double sigma_yaw_icp; double sigma_pitch_icp; double sigma_roll_icp; double sigma_x_icp; double sigma_y_icp; double sigma_z_icp; // prior noise model m_privateNodeHandle.param("noise_model/prior/sigma_yaw", sigma_yaw_prior, 0.000001); m_privateNodeHandle.param("noise_model/prior/sigma_pitch", sigma_pitch_prior, 0.000001); m_privateNodeHandle.param("noise_model/prior/sigma_roll", sigma_roll_prior, 0.000001); m_privateNodeHandle.param("noise_model/prior/sigma_x", sigma_x_prior, 0.001); m_privateNodeHandle.param("noise_model/prior/sigma_y", sigma_y_prior, 0.001); m_privateNodeHandle.param("noise_model/prior/sigma_z", sigma_z_prior, 0.001); m_prior_model = gtsam::noiseModel::Diagonal::Sigmas ((gtsam::Vector(6) << sigma_yaw_prior, sigma_pitch_prior, sigma_roll_prior, sigma_x_prior, sigma_y_prior, sigma_z_prior).finished()); // odom noise model m_privateNodeHandle.param("noise_model/odom/sigma_yaw", sigma_yaw_odom, 0.085); // 0.085rad = 5deg m_privateNodeHandle.param("noise_model/odom/sigma_pitch", sigma_pitch_odom, 0.085); m_privateNodeHandle.param("noise_model/odom/sigma_roll", sigma_roll_odom, 0.085); m_privateNodeHandle.param("noise_model/odom/sigma_x", sigma_x_odom, 0.1); m_privateNodeHandle.param("noise_model/odom/sigma_y", sigma_y_odom, 0.1); m_privateNodeHandle.param("noise_model/odom/sigma_z", sigma_z_odom, 0.1); m_odom_model = gtsam::noiseModel::Diagonal::Sigmas ((gtsam::Vector(6) << sigma_yaw_prior, sigma_pitch_prior, sigma_roll_prior, sigma_x_prior, sigma_y_prior, sigma_z_prior).finished()); // icp noise model m_privateNodeHandle.param("noise_model/icp/dynamic_error_percentage", m_error_dynamic_percentage, 0.1); // if <=0 -> const noise m_privateNodeHandle.param("noise_model/icp/sigma_yaw", sigma_yaw_icp, 0.085); m_privateNodeHandle.param("noise_model/icp/sigma_pitch", sigma_pitch_icp, 0.085); m_privateNodeHandle.param("noise_model/icp/sigma_roll", sigma_roll_icp, 0.085); m_privateNodeHandle.param("noise_model/icp/sigma_x", sigma_x_icp, 0.1); m_privateNodeHandle.param("noise_model/icp/sigma_y", sigma_y_icp, 0.1); m_privateNodeHandle.param("noise_model/icp/sigma_z", sigma_z_icp, 0.1); m_icp_model = gtsam::noiseModel::Diagonal::Sigmas ((gtsam::Vector(6) << sigma_yaw_prior, sigma_pitch_prior, sigma_roll_prior, sigma_x_prior, sigma_y_prior, sigma_z_prior).finished()); m_privateNodeHandle.param("range_max", m_range_max, 10.0); m_logger_msg << "loop_closure/perform: " << m_perform_lc; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "loop_closure/parallel: " << m_parallel_lc; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "loop_closure/min_index_range: " << m_lc_min_idx_range; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "loop_closure/spatial_search_range: " << m_lc_spatial_search_range; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "multi_robot/perform: " << m_perform_mr; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "multi_robot/parallel: " << m_parallel_mr; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "multi_robot/spatial_search_range: " << m_mr_spatial_search_range; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "enforce_perfect_DA: " << m_enforcing_perfect_DA; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "icp/max_iters: " << m_icp_max_iters; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "icp/stopping_thresh[m]: " << m_icp_stopping_thresh; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "icp/inlier_thresh_sq[m]: " << m_icp_inlier_thresh_sq; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "icp/nn_matching_percentage/sliding_window: " << m_icp_window_nn_pct_thresh; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "icp/nn_matching_percentage/loop_closure: " << m_icp_lc_nn_pct_thresh; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "icp/nn_matching_percentage/multi_robot: " << m_icp_mr_nn_pct_thresh; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/prior/sigma_yaw[rad]: " << sigma_yaw_prior; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/prior/sigma_pitch[rad]: " << sigma_pitch_prior; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/prior/sigma_roll[rad]: " << sigma_roll_prior; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/prior/sigma_x[m]: " << sigma_x_prior; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/prior/sigma_y[m]: " << sigma_y_prior; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/prior/sigma_z[m]: " << sigma_z_prior; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/odom/sigma_yaw[rad]: " << sigma_yaw_odom; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/odom/sigma_pitch[rad]: " << sigma_pitch_odom; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/odom/sigma_roll[rad]: " << sigma_roll_odom; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/odom/sigma_x[m]: " << sigma_x_odom; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/odom/sigma_y[m]: " << sigma_y_odom; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/odom/sigma_z[m]: " << sigma_z_odom; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/icp/dynamic_error_percentage: " << m_error_dynamic_percentage; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/icp/sigma_yaw[rad]: " << sigma_yaw_icp; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/icp/sigma_pitch[rad]: " << sigma_pitch_icp; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/icp/sigma_roll[rad]: " << sigma_roll_icp; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/icp/sigma_x[m]: " << sigma_x_icp; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/icp/sigma_y[m]: " << sigma_y_icp; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "noise_model/icp/sigma_z[m]: " << sigma_z_icp; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "range_max: " << m_range_max; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "====================="; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } bool DaIcpLaser::daInitCheck(mrbsp_msgs::InitCheck::Request& req, mrbsp_msgs::InitCheck::Response& res) { FUNCTION_LOGGER(m_tag); res.init_check_answer = static_cast<unsigned char>(m_is_init); return true; } bool DaIcpLaser::daCheckLastIndex(mrbsp_msgs::LastIndexInDa::Request& req, mrbsp_msgs::LastIndexInDa::Response& res) { FUNCTION_LOGGER(m_tag); char robot_id = req.robot_id.at(0); if(m_all_keyframes.find(robot_id) != m_all_keyframes.end()) { res.last_index = m_all_keyframes.at(robot_id).size() - 1; } else { res.last_index = -1; } return true; } std::vector<NewFactorsAndValues> DaIcpLaser::getKeyframes(std::vector<std::vector<Keyframe>>& robots_keyframes) { FUNCTION_LOGGER(m_tag); m_is_rosbag = true; double number_of_robots = robots_keyframes.size(); std::vector<unsigned int> robot_keyframe_idx(robots_keyframes.size(), 0); std::vector<double> robot_current_time(robots_keyframes.size(), 0); while(number_of_robots > 0) { number_of_robots = robots_keyframes.size(); for (unsigned int i_robot = 0; i_robot < robots_keyframes.size(); ++i_robot) { try { robot_current_time.at(i_robot) = std::get<1>(robots_keyframes.at(i_robot).at(robot_keyframe_idx.at(i_robot))); } catch(const std::out_of_range& e) { robot_current_time.at(i_robot) = std::numeric_limits<double>::max(); --number_of_robots; } } if (number_of_robots == 0) { break; } unsigned int current_robot; current_robot = (unsigned int) std::distance(robot_current_time.begin(), std::min_element(robot_current_time.begin(), robot_current_time.end())); robot_keyframe_idx[current_robot]++; } m_logger_msg << "\n" << "Summery:" << "\n" << "--------------------------------------------" << "\n" << "Detected robots:" << "\n" << "\n"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); for (auto iter = m_all_keyframes.begin(); iter != m_all_keyframes.end(); ++iter) { m_logger_msg << "Robot ID: " << iter->first << ", Number of keyframes: " << iter->second.size() << "\n"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); gtsam::Pose3 final_pose = iter->second.rbegin()->second.second; m_logger_msg << "Final position: " << final_pose.x() << ", " << final_pose.y() << ", " << final_pose.z() << "\n"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } return m_all_factors_and_values; } void DaIcpLaser::KeyframeCallback(const mrbsp_msgs::KeyframeConstPtr& keyframe_init_msg) { FUNCTION_LOGGER(m_tag); m_logger_msg << "receive new 2D keyframe information..."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_is_3D_vis = false; Keyframe keyframe_init; KeyframeMsgParser(keyframe_init_msg, keyframe_init); m_is_rosbag = false; matchInSlidingWindow(keyframe_init); if(m_perform_lc) { if(m_parallel_lc) { m_loop_closure_pub.publish(keyframe_init_msg); } else { detectLoopClosures(keyframe_init); } } if(m_perform_mr) { if(m_parallel_mr) { m_multirobot_pub.publish(keyframe_init_msg); } else { detectMultiRobotFactors(keyframe_init); } } } void DaIcpLaser::KeyframeRgbdCallback(const mrbsp_msgs::KeyframeRgbdConstPtr& keyframe_init_rgbd_msg) { FUNCTION_LOGGER(m_tag); m_logger_msg << "receive new 3D keyframe information..."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_is_3D_vis = true; Keyframe keyframe_init; mrbsp_msgs::Keyframe keyframe_init_msg; keyframe_init_msg.header = keyframe_init_rgbd_msg->header; keyframe_init_msg.ser_odom_from_prev_keyframe = keyframe_init_rgbd_msg->ser_odom_from_prev_keyframe; keyframe_init_msg.ser_symbol = keyframe_init_rgbd_msg->ser_symbol; keyframe_init_msg.laser_scan = keyframe_init_rgbd_msg->laser_scan; m_current_pointcloud_msg = keyframe_init_rgbd_msg->pointcloud; mrbsp_msgs::KeyframeConstPtr keyframe_init_msg_const(new mrbsp_msgs::Keyframe(keyframe_init_msg)); KeyframeMsgParser(keyframe_init_msg_const, keyframe_init); m_is_rosbag = false; matchInSlidingWindow(keyframe_init); if(m_perform_lc) { if(m_parallel_lc) { m_loop_closure_pub.publish(keyframe_init_msg); } else { detectLoopClosures(keyframe_init); } } if(m_perform_mr) { if(m_parallel_mr) { m_multirobot_pub.publish(keyframe_init_msg); } else { detectMultiRobotFactors(keyframe_init); } } } void DaIcpLaser::KeyframeMsgParser(const mrbsp_msgs::KeyframeConstPtr& keyframe_init_msg, Keyframe &keyframe_init) { FUNCTION_LOGGER(m_tag); gtsam::Symbol current_symbol; gtsam::deserialize(keyframe_init_msg->ser_symbol, current_symbol); sensor_msgs::LaserScan laser_scan(keyframe_init_msg->laser_scan); gtsam::Pose3 odom_from_prev_keyframe; gtsam::deserialize(keyframe_init_msg->ser_odom_from_prev_keyframe, odom_from_prev_keyframe); std::string keyframe_idx(std::string(1,current_symbol.chr()) + std::to_string(current_symbol.index())); double current_time = keyframe_init_msg->header.stamp.toSec(); keyframe_init = std::make_tuple(keyframe_idx, current_time, laser_scan, odom_from_prev_keyframe, keyframe_init_msg->ground_truth_pose); } void DaIcpLaser::matchInSlidingWindow(Keyframe &keyframe_init) { FUNCTION_LOGGER(m_tag); // gtsam facor graph initialization gtsam::NonlinearFactorGraph graph; gtsam::Values values; // extract new data; std::string current_index; double current_time; sensor_msgs::LaserScan current_scan_msg; std::vector<gtsam::Point2> current_scan; gtsam::Pose3 current_odom; gtsam::Pose3 current_pose; geometry_msgs::Pose ground_truth_pose; std::tie(current_index, current_time, current_scan_msg, current_odom, ground_truth_pose) = keyframe_init; // set gtsam symbol char index_char = current_index.at(0); int index_num = std::stoi(current_index.substr(1)); gtsam::Symbol current_key(index_char, index_num); m_logger_msg << "DA: Robot " << index_char << ", index " << index_num << ": Matching in sliding window"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); // cast laser msg to vector of gtsam point2 objects - for csm icp rosLaserToCsmGtsam(current_scan_msg, current_scan); // initialize pose for the new keyframe if(index_num == 0) { // new robot detected m_logger_msg << "Add new robot, ID " << index_char; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); SingleRobotKeyframe single_robot_keyframes; m_all_keyframes.emplace(index_char, single_robot_keyframes); current_pose = current_odom; // odom of the first keyframe is the initial pose of the robot gtsam::PriorFactor<gtsam::Pose3> f_prior(current_key, current_pose, m_prior_model); graph.push_back(f_prior); //current_pose.print("Current pose:\n"); } else { // calculate current pose with previous scan from this robot std::vector<gtsam::Point2> previous_scan(m_all_keyframes.at(index_char).at(index_num - 1).first); gtsam::Pose3 previous_pose(m_all_keyframes.at(index_char).at(index_num - 1).second); gtsam::Symbol previous_key(index_char, index_num - 1); gtsam::Pose3 icp_transformation; //bool use_icp = false; std::string indexes(current_index + "," + std::string(1, index_char) + std::to_string(index_num - 1)); if (performCsmIcp(current_scan, previous_scan, current_odom, icp_transformation, m_icp_window_nn_pct_thresh, indexes)) { //if(use_icp) { // use icp result gtsam::noiseModel::Diagonal::shared_ptr icp_dynamic_model(getDynamicModel(icp_transformation)); gtsam::BetweenFactor<gtsam::Pose3> f_icp(previous_key, current_key, icp_transformation, icp_dynamic_model); graph.push_back(f_icp); current_pose = previous_pose.compose(icp_transformation); //current_pose.print("Current pose:\n"); if (current_odom.equals(icp_transformation, 0.5)) { } else { m_logger_msg << "DA: Big difference between initial guess and icp results, temp index " << index_num; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); //current_odom.print("current odom:\n"); m_logger_msg << "DA: current odom:\n" << current_odom; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); //icp_transformation.print("icp:\n"); m_logger_msg << "DA: Icp transformation:\n" << icp_transformation; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } } else { // use odometry m_logger_msg << "Icp failed to converge, use odomety instead."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); gtsam::noiseModel::Diagonal::shared_ptr odom_dynamic_model(getDynamicModel(current_odom)); gtsam::BetweenFactor<gtsam::Pose3> f_odom(previous_key, current_key, current_odom, odom_dynamic_model); graph.push_back(f_odom); current_pose = previous_pose.compose(current_odom); //current_pose.print("Current pose:\n"); } } values.insert(current_key, current_pose); m_logger_msg << "DA: Robot " << index_char << ", keyframe " << index_num << " initialized..."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); KeyframeData keyframe_data = std::make_pair(current_scan, current_pose); m_all_keyframes.at(index_char).emplace(index_num, keyframe_data); if(m_is_3D_vis) { MapData3D current_map_data = std::make_pair(m_current_pointcloud_msg, current_pose); m_all_map_data_3d.emplace(current_index, current_map_data); } else { MapData current_map_data = std::make_pair(current_scan_msg, current_pose); m_all_map_data.emplace(current_index, current_map_data); } NewFactorsAndValues new_factors_and_values = std::make_pair(graph, values); m_all_factors_and_values.push_back(new_factors_and_values); m_last_factors_and_values = new_factors_and_values; if(!m_is_rosbag) { m_logger_msg << "DA: Publish sliding window data."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); publishDataToBelief(graph, values); if(m_is_3D_vis) { publishDataToMap3D(m_current_pointcloud_msg, values); } else { publishDataToMap(current_scan_msg, values); } } } void DaIcpLaser::loopClosureCallback(const mrbsp_msgs::KeyframeConstPtr& keyframe_init_msg) { FUNCTION_LOGGER(m_tag); Keyframe keyframe_init; KeyframeMsgParser(keyframe_init_msg, keyframe_init); detectLoopClosures(keyframe_init); } void DaIcpLaser::detectLoopClosures(Keyframe &keyframe_init) { FUNCTION_LOGGER(m_tag); // gtsam facor graph initialization gtsam::NonlinearFactorGraph graph; gtsam::Values values; // extract new data; std::string current_index; double current_time; sensor_msgs::LaserScan current_scan_msg; std::vector<gtsam::Point2> current_scan; gtsam::Pose3 current_odom; geometry_msgs::Pose ground_truth_pose; std::tie(current_index, current_time, current_scan_msg, current_odom, ground_truth_pose) = keyframe_init; // set gtsam symbol char index_char = current_index.at(0); int index_num = std::stoi(current_index.substr(1)); gtsam::Symbol current_key(index_char, index_num); gtsam::Pose3 current_pose(m_all_keyframes.at(index_char).at(index_num).second); m_logger_msg << "DA: Robot " << index_char << ", index " << index_num << ": Searching for loop closure"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); // cast laser msg to vector of gtsam point2 objects - for csm icp rosLaserToCsmGtsam(current_scan_msg, current_scan); // detect loop closures factors //size_t last_lc_detection_index = -m_lc_min_idx_range; for(auto lc_iter = m_all_keyframes.at(index_char).begin(); lc_iter != m_all_keyframes.at(index_char).end(); ++lc_iter) { size_t temp_index = lc_iter->first; if(index_num - temp_index < m_lc_min_idx_range) { break; } std::vector<gtsam::Point2> temp_scan(m_all_keyframes.at(index_char).at(temp_index).first); gtsam::Pose3 temp_pose(m_all_keyframes.at(index_char).at(temp_index).second); gtsam::Symbol temp_key(index_char, temp_index); gtsam::Pose3 temp_odom(temp_pose.between(current_pose)); m_logger_msg << "DA: Search for loop closure, Robot " << index_char << " indexes: " << index_num << ", " << temp_index; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "DA: temp_pose: X = " << temp_pose.x() << ", Y = " << temp_pose.y() << ", Z = " << temp_pose.z(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "DA: current_pose: X = " << current_pose.x() << ", Y = " << current_pose.y() << ", Z = " << current_pose.z(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "DA: temp_odom: X = " << temp_odom.x() << ", Y = " << temp_odom.y() << ", Z = " << temp_odom.z(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "DA: range: " << temp_odom.range(gtsam::Pose3()) << ", angle difference: : " << fabs(temp_odom.rotation().yaw()); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); //if(temp_odom.range(gtsam::Pose3()) < m_lc_spatial_search_range && fabs(temp_odom.rotation().yaw()) < M_PI_4) { if(temp_odom.range(gtsam::Pose3()) < m_lc_spatial_search_range) { gtsam::Pose3 lc_icp_transformation; std::string indexes(current_index + "," + std::string(1, index_char) + std::to_string(temp_index)); if (performCsmIcpLc(current_scan, temp_scan, temp_odom, lc_icp_transformation, m_icp_lc_nn_pct_thresh, indexes)) { /*bool save_lc_scan(true); if(save_lc_scan) { }*/ bool DA_consistent; if (m_enforcing_perfect_DA) { gtsam::Pose3 gtsam_gt_pose(gtsam::Rot3(gtsam::Quaternion(ground_truth_pose.orientation.w, ground_truth_pose.orientation.x, ground_truth_pose.orientation.y, ground_truth_pose.orientation.z)), gtsam::Point3(ground_truth_pose.position.x, ground_truth_pose.position.y, ground_truth_pose.position.z)); gtsam::Pose3 icp_current_pose = temp_pose.compose(lc_icp_transformation); gtsam::Pose3 absolute_error = gtsam_gt_pose.between(icp_current_pose); DA_consistent = absolute_error.translation().isApproxToConstant(0, 0.5) && absolute_error.rotation().pitch() < 0.1 && absolute_error.rotation().roll() < 0.1 && absolute_error.rotation().yaw() < 0.3; } else DA_consistent = (temp_odom.translation()-lc_icp_transformation.translation()).isApproxToConstant(0, 1); // tollerance on displacement 1 m if(DA_consistent) { m_logger_msg << "DA: Loop closure detected, Robot " << index_char << " indexes: " << index_num << ", " << temp_index; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); gtsam::noiseModel::Diagonal::shared_ptr icp_dynamic_model( getDynamicModel(lc_icp_transformation)); gtsam::BetweenFactor<gtsam::Pose3> f_icp(temp_key, current_key, lc_icp_transformation, icp_dynamic_model); graph.push_back(f_icp); } else { m_logger_msg << "DA: loop closure : Big difference between initial guess/GT and icp results, temp index. Skipping this factor. " << temp_index; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } if(temp_index + m_lc_min_idx_range >= m_all_keyframes.at(index_char).size()) { break; } else { std::advance(lc_iter, m_lc_min_idx_range - 1); } } } } if(!m_is_rosbag && graph.size() > 0) { m_logger_msg << "DA: Publish loop closure data."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); publishDataToBelief(graph, values); } } void DaIcpLaser::multiRobotCallback(const mrbsp_msgs::KeyframeConstPtr& keyframe_init_msg) { FUNCTION_LOGGER(m_tag); Keyframe keyframe_init; KeyframeMsgParser(keyframe_init_msg, keyframe_init); detectMultiRobotFactors(keyframe_init); } void DaIcpLaser::detectMultiRobotFactors(Keyframe &keyframe_init) { FUNCTION_LOGGER(m_tag); // gtsam facor graph initialization gtsam::NonlinearFactorGraph graph; gtsam::Values values; // extract new data; std::string current_index; double current_time; sensor_msgs::LaserScan current_scan_msg; std::vector<gtsam::Point2> current_scan; gtsam::Pose3 current_odom; geometry_msgs::Pose ground_truth_pose; std::tie(current_index, current_time, current_scan_msg, current_odom, ground_truth_pose) = keyframe_init; // set gtsam symbol char index_char = current_index.at(0); int index_num = std::stoi(current_index.substr(1)); gtsam::Symbol current_key(index_char, index_num); gtsam::Pose3 current_pose(m_all_keyframes.at(index_char).at(index_num).second); m_logger_msg << "DA: Robot " << index_char << ", index " << index_num << ": Searching for multirobot factors"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); // cast laser msg to vector of gtsam point2 objects - for csm icp rosLaserToCsmGtsam(current_scan_msg, current_scan); // detect multi-robot factors for(auto robot_id_iter = m_all_keyframes.begin(); robot_id_iter != m_all_keyframes.end(); ++robot_id_iter) { char temp_id = robot_id_iter->first; if(temp_id != index_char) { for(auto mr_iter = robot_id_iter->second.begin(); mr_iter != robot_id_iter->second.end(); ++mr_iter) { size_t temp_index = mr_iter->first; std::vector<gtsam::Point2> temp_scan(m_all_keyframes.at(temp_id).at(temp_index).first); gtsam::Pose3 temp_pose(m_all_keyframes.at(temp_id).at(temp_index).second); gtsam::Symbol temp_key(temp_id, temp_index); gtsam::Pose3 temp_odom(temp_pose.between(current_pose)); if (temp_odom.range(gtsam::Pose3()) < m_mr_spatial_search_range) { gtsam::Pose3 mr_icp_transformation; std::string indexes(current_index + "," + std::string(1, temp_id) + std::to_string(temp_index)); if (performCsmIcpMr(current_scan, temp_scan, temp_odom, mr_icp_transformation, m_icp_mr_nn_pct_thresh, indexes)) { gtsam::noiseModel::Diagonal::shared_ptr icp_dynamic_model( getDynamicModel(mr_icp_transformation)); gtsam::BetweenFactor<gtsam::Pose3> f_icp(temp_key, current_key, mr_icp_transformation, icp_dynamic_model); graph.push_back(f_icp); if(temp_index + m_lc_min_idx_range >= robot_id_iter->second.size()) { break; } else { std::advance(mr_iter, m_lc_min_idx_range - 1); } if(temp_odom.equals(mr_icp_transformation, 1)) { m_logger_msg << "DA: Multi robot factors detected," << " Robot " << index_char << "index" << index_num << " Robot " << temp_id << "index" << temp_index; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } else { m_logger_msg << "DA: Multi robot factors : Big difference between initial guess and icp results," << " Robot " << index_char << "index" << index_num << " Robot " << temp_id << "index" << temp_index; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } } } } } } if(!m_is_rosbag && graph.size() > 0) { m_logger_msg << "DA: Publish multi-robot data."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); publishDataToBelief(graph, values); } } void DaIcpLaser::publishDataToBelief(const gtsam::NonlinearFactorGraph& graph, const gtsam::Values& values) { FUNCTION_LOGGER(m_tag); m_logger_msg << "DA: Number of new factors: " << graph.size() << "Number of new values: " << values.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); // publish factors and values to belief mrbsp_msgs::GtsamFactorGraph factor_graph; factor_graph.ser_factors = gtsam::serialize(graph); factor_graph.ser_values = gtsam::serialize(values); m_factors_and_values_pub.publish(factor_graph); } void DaIcpLaser::publishDataToMap(const sensor_msgs::LaserScan& scan, const gtsam::Values& values) { FUNCTION_LOGGER(m_tag); // publish new scan to the map node mrbsp_msgs::MapData map_data; map_data.header.stamp = ros::Time::now(); map_data.laser_scan = scan; map_data.ser_values = gtsam::serialize(values); map_data.is_new_scan = 1; m_map_data_2D_pub.publish(map_data); m_logger_msg << "DA: Publish 2D map data, new scan. number of values: " << values.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } void DaIcpLaser::publishDataToMap3D(const sensor_msgs::PointCloud2& pointcloud, const gtsam::Values& values) { FUNCTION_LOGGER(m_tag); // publish new scan to the map node mrbsp_msgs::MapData3D map_data3D; map_data3D.header.stamp = ros::Time::now(); map_data3D.pointcloud = pointcloud; map_data3D.ser_values = gtsam::serialize(values); map_data3D.is_new_scan = 1; m_map_data_3D_pub.publish(map_data3D); m_logger_msg << "DA: Publish 3D map data, new scan. number of values: " << values.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } void DaIcpLaser::rosLaserToCsmGtsam(sensor_msgs::LaserScan& laser_msg, std::vector<gtsam::Point2>& current_scan) { FUNCTION_LOGGER(m_tag); current_scan.clear(); std::vector<float> ranges = laser_msg.ranges; float current_angle = laser_msg.angle_min; for (auto &&range : ranges) { if ((range > laser_msg.range_min) && (range < m_range_max) && (current_angle >= laser_msg.angle_min) && (current_angle <= laser_msg.angle_max)) { double x = range * cos(current_angle); double y = range * sin(current_angle); gtsam::Point2 scan(x, y); current_scan.push_back(scan); } current_angle += laser_msg.angle_increment; } } bool DaIcpLaser::performCsmIcp(std::vector<gtsam::Point2>& current_measurement, std::vector<gtsam::Point2>& prev_measurement, const gtsam::Pose3& initial_guess, gtsam::Pose3& icp_transformation, const double nn_matching_threshold, std::string indexes/*= std::string()*/) { FUNCTION_LOGGER(m_tag); if(current_measurement.empty() || prev_measurement.empty()) { return false; } if(!indexes.empty()) { m_logger_msg << "PLANNAR_ICP: Matching scans between indexes: " << indexes; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } /// ICP thresholds const int maxIters = m_icp_max_iters; const double stoppingThresh = m_icp_stopping_thresh; const double inlierThreshSq = m_icp_inlier_thresh_sq; gtsam::Pose2 initial_guess_pose2(initial_guess.x(), initial_guess.y(), initial_guess.rotation().yaw()); ReturnValue return_value = laserScanICP(prev_measurement, current_measurement, initial_guess_pose2, maxIters, stoppingThresh, inlierThreshSq); icp_transformation = gtsam::Pose3(return_value.getDelta()); double status = return_value.getStatus(); double scan_size_ratio = double(prev_measurement.size()) / double(current_measurement.size()); double scan_size_ratio_threshold = 0.95; if(scan_size_ratio < scan_size_ratio_threshold || scan_size_ratio > 1/scan_size_ratio_threshold) { m_logger_msg << "PLANNAR_ICP: prev_measurement.size() = " << prev_measurement.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "PLANNAR_ICP: current_measurement.size() = " << current_measurement.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "PLANNAR_ICP: Scans size ratio = " << scan_size_ratio << ", check inverse matching"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); ReturnValue return_value_rev = laserScanICP(current_measurement, prev_measurement, initial_guess_pose2.inverse(), maxIters, stoppingThresh, inlierThreshSq); // assign lowest status value if(status > return_value_rev.getStatus()) { status = return_value_rev.getStatus(); } } bool print_icp_results(true); if(print_icp_results) { m_logger_msg << "PLANNAR_ICP:\n" << "delta: X = " << return_value.getDelta().x() << ", Y = " << return_value.getDelta().y() << ", Yaw = " << return_value.getDelta().rotation().theta() << "\n" << "Number of iterations: " << return_value.getNumIters() << "\n" << "Stoping threshold: " << return_value.getStopping() << "\n" << "Min status score: " << status; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } if(status > 0 && status < nn_matching_threshold) { m_logger_msg << "PLANNAR_ICP:\n" << "ICP succeeded but below nn matching threshold." << "\n" << "score: " << status << ", nn matching threshold: " << nn_matching_threshold; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } return status > nn_matching_threshold; } bool DaIcpLaser::performCsmIcpLc(std::vector<gtsam::Point2>& current_measurement, std::vector<gtsam::Point2>& prev_measurement, const gtsam::Pose3& initial_guess, gtsam::Pose3& icp_transformation, const double nn_matching_threshold, std::string indexes/*= std::string()*/) { FUNCTION_LOGGER(m_tag); if(current_measurement.empty() || prev_measurement.empty()) { return false; } if(!indexes.empty()) { m_logger_msg << "PLANNAR_ICP: Matching scans between indexes: " << indexes; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } /// ICP thresholds const int maxIters = m_icp_max_iters; const double stoppingThresh = m_icp_stopping_thresh; const double inlierThreshSq = m_icp_inlier_thresh_sq; gtsam::Pose2 initial_guess_pose2(initial_guess.x(), initial_guess.y(), initial_guess.rotation().yaw()); ReturnValue return_value = laserScanICP(prev_measurement, current_measurement, initial_guess_pose2, maxIters, stoppingThresh, inlierThreshSq); icp_transformation = gtsam::Pose3(return_value.getDelta()); double status = return_value.getStatus(); double scan_size_ratio = double(prev_measurement.size()) / double(current_measurement.size()); double scan_size_ratio_threshold = 0.95; if(scan_size_ratio < scan_size_ratio_threshold || scan_size_ratio > 1/scan_size_ratio_threshold) { m_logger_msg << "PLANNAR_ICP: prev_measurement.size() = " << prev_measurement.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "PLANNAR_ICP: current_measurement.size() = " << current_measurement.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "PLANNAR_ICP: Scans size ratio = " << scan_size_ratio << ", check inverse matching"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); ReturnValue return_value_rev = laserScanICP(current_measurement, prev_measurement, initial_guess_pose2.inverse(), maxIters, stoppingThresh, inlierThreshSq); // assign lowest status value if(status > return_value_rev.getStatus()) { status = return_value_rev.getStatus(); } } bool print_icp_results(true); if(print_icp_results) { m_logger_msg << "PLANNAR_ICP:\n" << "delta: X = " << return_value.getDelta().x() << ", Y = " << return_value.getDelta().y() << ", Yaw = " << return_value.getDelta().rotation().theta() << "\n" << "Number of iterations: " << return_value.getNumIters() << "\n" << "Stoping threshold: " << return_value.getStopping() << "\n" << "Min status score: " << status; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } if(status > 0 && status < nn_matching_threshold) { m_logger_msg << "PLANNAR_ICP:\n" << "ICP succeeded but below nn matching threshold." << "\n" << "score: " << status << ", nn matching threshold: " << nn_matching_threshold; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } return status > nn_matching_threshold; } bool DaIcpLaser::performCsmIcpMr(std::vector<gtsam::Point2>& current_measurement, std::vector<gtsam::Point2>& prev_measurement, const gtsam::Pose3& initial_guess, gtsam::Pose3& icp_transformation, const double nn_matching_threshold, std::string indexes/*= std::string()*/) { FUNCTION_LOGGER(m_tag); if(current_measurement.empty() || prev_measurement.empty()) { return false; } if(!indexes.empty()) { m_logger_msg << "PLANNAR_ICP: Matching scans between indexes: " << indexes; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } /// ICP thresholds const int maxIters = m_icp_max_iters; const double stoppingThresh = m_icp_stopping_thresh; const double inlierThreshSq = m_icp_inlier_thresh_sq; gtsam::Pose2 initial_guess_pose2(initial_guess.x(), initial_guess.y(), initial_guess.rotation().yaw()); ReturnValue return_value = laserScanICP(prev_measurement, current_measurement, initial_guess_pose2, maxIters, stoppingThresh, inlierThreshSq); icp_transformation = gtsam::Pose3(return_value.getDelta()); double status = return_value.getStatus(); double scan_size_ratio = double(prev_measurement.size()) / double(current_measurement.size()); double scan_size_ratio_threshold = 0.95; if(scan_size_ratio < scan_size_ratio_threshold || scan_size_ratio > 1/scan_size_ratio_threshold) { m_logger_msg << "PLANNAR_ICP: prev_measurement.size() = " << prev_measurement.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "PLANNAR_ICP: current_measurement.size() = " << current_measurement.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "PLANNAR_ICP: Scans size ratio = " << scan_size_ratio << ", check inverse matching"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); ReturnValue return_value_rev = laserScanICP(current_measurement, prev_measurement, initial_guess_pose2.inverse(), maxIters, stoppingThresh, inlierThreshSq); // assign lowest status value if(status > return_value_rev.getStatus()) { status = return_value_rev.getStatus(); } } bool print_icp_results(true); if(print_icp_results) { m_logger_msg << "PLANNAR_ICP:\n" << "delta: X = " << return_value.getDelta().x() << ", Y = " << return_value.getDelta().y() << ", Yaw = " << return_value.getDelta().rotation().theta() << "\n" << "Number of iterations: " << return_value.getNumIters() << "\n" << "Stoping threshold: " << return_value.getStopping() << "\n" << "Min status score: " << status; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } if(status > 0 && status < nn_matching_threshold) { m_logger_msg << "PLANNAR_ICP:\n" << "ICP succeeded but below nn matching threshold." << "\n" << "score: " << status << ", nn matching threshold: " << nn_matching_threshold; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } return status > nn_matching_threshold; } gtsam::noiseModel::Diagonal::shared_ptr DaIcpLaser::getDynamicModel(gtsam::Pose3& action) { FUNCTION_LOGGER(m_tag); if(m_error_dynamic_percentage > 0) { gtsam::Point3 translation = action.translation(); gtsam::Rot3 rotation = action.rotation(); double roll = std::max(rotation.roll() * m_error_dynamic_percentage, MIN_ROTATION_NOISE_SIGMA); double pitch = std::max(rotation.pitch() * m_error_dynamic_percentage, MIN_ROTATION_NOISE_SIGMA); double yaw = std::max(rotation.yaw() * m_error_dynamic_percentage, MIN_ROTATION_NOISE_SIGMA); double X = std::max(translation.x() * m_error_dynamic_percentage, MIN_TRANSLATION_NOISE_SIGMA); double Y = std::max(translation.y() * m_error_dynamic_percentage, MIN_TRANSLATION_NOISE_SIGMA); double Z = std::max(translation.z() * m_error_dynamic_percentage, MIN_TRANSLATION_NOISE_SIGMA); gtsam::Vector vector(6); vector << roll, pitch, yaw, X, Y, Z; return gtsam::noiseModel::Diagonal::Sigmas(vector); } else { return m_icp_model; } } void DaIcpLaser::saveScan(std::vector<gtsam::Point2>& scan, std::string& index) { FUNCTION_LOGGER(m_tag); std::fstream file; file.open(std::string("scans/scan_" + index + ".txt"), std::fstream::out); for(auto iter = scan.begin(); iter != scan.end(); ++iter) { file << iter->x() << " " << iter->y() << "\n"; } file.close(); } void DaIcpLaser::updateMemoryCallback(const mrbsp_msgs::GtsamSerValuesConstPtr& serialized_values_msg) { FUNCTION_LOGGER(m_tag); m_logger_msg << "DA: receive serialized values."; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); gtsam::Values updated_values; try { gtsam::deserialize(serialized_values_msg->ser_values, updated_values); m_logger_msg << "DA: Number of optimized values: " << updated_values.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); updateMemory(updated_values); } catch (...) { m_logger_msg << "DA: Deserialization failed!"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } } void DaIcpLaser::updateMemory(gtsam::Values& updated_values) { FUNCTION_LOGGER(m_tag); gtsam::Values vals_for_map; gtsam::KeyVector updated_keys = updated_values.keys(); for(auto key : updated_keys) { gtsam::Symbol symbol(key); char robot_id = symbol.chr(); unsigned int index = symbol.index(); // update keyframes data structure auto updated_iter = m_all_keyframes.at(robot_id).find(index); if(updated_iter != m_all_keyframes.at(robot_id).end()) { if(!updated_iter->second.second.equals(updated_values.at<gtsam::Pose3>(symbol),0.1)) { //updated_iter->second.second.print("Old value:\n"); updated_iter->second.second = updated_values.at<gtsam::Pose3>(symbol); //updated_iter->second.second.print("New value:\n"); // update map data structure std::string index_string((1, robot_id) + std::to_string(index)); auto map_iter = m_all_map_data.find(index_string); if(map_iter != m_all_map_data.end()) { map_iter->second.second = updated_values.at<gtsam::Pose3>(symbol); vals_for_map.insert(symbol, updated_values.at<gtsam::Pose3>(symbol)); } } } } if(!m_is_rosbag && vals_for_map.size() > 0) { // publish updated poses to the map node mrbsp_msgs::MapData map_data; map_data.header.stamp = ros::Time::now(); map_data.ser_values = gtsam::serialize(vals_for_map); map_data.is_new_scan = 0; m_map_data_2D_pub.publish(map_data); //m_map_data_3D_pub.publish(map_data); m_logger_msg << "DA: Publish map data, update scan poses. number of values: " << vals_for_map.size(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } // print last pose for each robot m_logger_msg << "--------------------------"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "Last poses of each robot:"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "--------------------------"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); for(auto robot_iter = m_all_keyframes.begin(); robot_iter != m_all_keyframes.end(); ++robot_iter) { char robot_id = robot_iter->first; unsigned int last_index = robot_iter->second.rbegin()->first; gtsam::Pose3 last_pose = robot_iter->second.rbegin()->second.second; m_logger_msg << "Robot id: " << robot_id << ", index: " << last_index; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); m_logger_msg << "Robot position: X = " << last_pose.x() << ", Y = " << last_pose.y() << ", Z = " << last_pose.z(); logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); } } std::map<std::string, MapData> DaIcpLaser::getMapData() { FUNCTION_LOGGER(m_tag); return m_all_map_data; } DaIcpLaser::~DaIcpLaser() { FUNCTION_LOGGER(m_tag); m_logger_msg << "Destructor " << m_node_name << " node"; logMessage(info, LOG_INFO_LVL, m_logger_msg, m_tag); }
43.413223
210
0.663031
[ "vector", "model", "3d" ]
e25ebbcbba4766d2ae5ae20cbd5789bc5858d560
3,847
cpp
C++
cvlib/src/select_texture.cpp
SeregaVM/cvclasses19
0a901171a40b4c6c91332664383f9e4f6ae7e154
[ "MIT" ]
null
null
null
cvlib/src/select_texture.cpp
SeregaVM/cvclasses19
0a901171a40b4c6c91332664383f9e4f6ae7e154
[ "MIT" ]
null
null
null
cvlib/src/select_texture.cpp
SeregaVM/cvclasses19
0a901171a40b4c6c91332664383f9e4f6ae7e154
[ "MIT" ]
null
null
null
/* Split and merge segmentation algorithm implementation. * @file * @date 2018-09-18 * @author Anonymous */ #include "cvlib.hpp" namespace { std::vector<cv::Mat> filter_kernels; std::vector<cv::Mat> feture_maps; struct Descriptor : public std::vector<double> { using std::vector<double>::vector; Descriptor operator-(const Descriptor& right) const { Descriptor temp = *this; for (size_t i = 0; i < temp.size(); ++i) { temp[i] -= right[i]; } return temp; } double norm_l1() const { double res = 0.0; for (auto v : *this) { res += std::abs(v); } return res; } double norm_l2() const { double res = 0.0; for (auto v : *this) res += v*v; res = std::sqrt(res); return res; } }; void calculateReferenceDescriptor(const cv::Mat& image, Descriptor& descr) { descr.clear(); cv::Mat response; cv::Mat mean; cv::Mat dev; for (const auto& kernel : filter_kernels) { cv::filter2D(image, response, CV_32F, kernel); cv::meanStdDev(response, mean, dev); descr.emplace_back(mean.at<double>(0)); descr.emplace_back(dev.at<double>(0)); } } void calculateDescriptorFromMaps(const cv::Rect& roi, Descriptor& descr) { descr.clear(); cv::Mat mean; cv::Mat dev; for(const auto& map : feture_maps) { cv::meanStdDev(map(roi), mean, dev); descr.emplace_back(mean.at<double>(0)); descr.emplace_back(dev.at<double>(0)); } } void calculateFeatureMaps(const cv::Mat& image) { if(filter_kernels.empty()) return; feture_maps.clear(); for (const auto& kernel : filter_kernels) { feture_maps.emplace_back(); cv::filter2D(image, feture_maps.back(), CV_32F, kernel); } } void calculateFilters(int kernel_size) { filter_kernels.clear(); const std::vector<double> lambda_vec = {1/6.*kernel_size, 1/3.*kernel_size, 1/1.*kernel_size}; const std::vector<double> gamma_vec = {0.5}; const std::vector<double> sigma_vec = {1/12.*kernel_size, 1/9.*kernel_size, 1/6.*kernel_size}; const std::vector<double> theta_vec = {0, CV_PI/4, CV_PI/2, 3*CV_PI/4}; for (auto& th : theta_vec) for(auto& lm : lambda_vec) for (auto& sig : sigma_vec) for( auto& gm : gamma_vec) filter_kernels.push_back(cv::getGaborKernel(cv::Size(kernel_size, kernel_size), sig, th, lm, gm)); } } // namespace namespace cvlib { cv::Mat select_texture(const cv::Mat& image, const cv::Rect& roi, double eps) { double num = static_cast<double>(std::min(roi.height, roi.width)) / 2.0; num = num > 31 ? 31 : num; const int kernel_size = std::floor(num) / 2 != 0 ? std::floor(num) : std::ceil(num); static int prev_kernel_size; if(prev_kernel_size != kernel_size) { calculateFilters(kernel_size); prev_kernel_size = kernel_size; std::cout << filter_kernels.size() << std::endl; } calculateFeatureMaps(image); Descriptor reference; calculateReferenceDescriptor(image(roi), reference); cv::Mat res = cv::Mat::zeros(image.size(), CV_8UC1); Descriptor test(reference.size()); cv::Rect baseROI = roi - roi.tl(); int step_h = 10; int step_w = 10; // \todo move ROI smoothly pixel-by-pixel --> imposible for (int i = 0; i < image.size().width - roi.width; i += step_w) { for (int j = 0; j < image.size().height - roi.height; j += step_h) { auto curROI = baseROI + cv::Point(i, j); calculateDescriptorFromMaps(curROI, test); res(curROI) = 255 * ((test - reference).norm_l2() <= eps); } } return res; } } // namespace cvlib
26.349315
118
0.59033
[ "vector" ]
e261e0a4fbe0399e23633adf3a7bb1020c7fef98
589
cpp
C++
lib/grid/domain_index.cpp
mdavezac/bempp
bc573062405bda107d1514e40b6153a8350d5ab5
[ "BSL-1.0" ]
null
null
null
lib/grid/domain_index.cpp
mdavezac/bempp
bc573062405bda107d1514e40b6153a8350d5ab5
[ "BSL-1.0" ]
null
null
null
lib/grid/domain_index.cpp
mdavezac/bempp
bc573062405bda107d1514e40b6153a8350d5ab5
[ "BSL-1.0" ]
null
null
null
#include "domain_index.hpp" #include "entity_pointer.hpp" #include "entity.hpp" #include "../common/acc.hpp" namespace Bempp { int DomainIndex::domain(const Entity<0> &entity) const { std::unique_ptr<EntityPointer<0>> father; const Entity<0> *level0Entity = &entity; while (level0Entity->hasFather()) { father = level0Entity->father(); level0Entity = &father->entity(); } int index = m_level0IndexSet->entityIndex(*level0Entity); return acc(m_domainIndices, index); } std::vector<int> DomainIndex::domainIndices() const { return m_domainIndices; } } // namespace
24.541667
79
0.716469
[ "vector" ]
e26a0649f1d53df6478429e88a4802eded7dd701
18,348
cpp
C++
src/main.cpp
Hubertzjz/CarND-Path-Planning-Project-master
8289fbbd8f10ff05549493abfe306970079bc592
[ "MIT" ]
null
null
null
src/main.cpp
Hubertzjz/CarND-Path-Planning-Project-master
8289fbbd8f10ff05549493abfe306970079bc592
[ "MIT" ]
null
null
null
src/main.cpp
Hubertzjz/CarND-Path-Planning-Project-master
8289fbbd8f10ff05549493abfe306970079bc592
[ "MIT" ]
null
null
null
#include <uWS/uWS.h> #include <fstream> #include <iostream> #include <string> #include <vector> #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" #include "helpers.h" #include "spline.h" #include "json.hpp" // for convenience using nlohmann::json; using std::string; using std::vector; int get_lane(float d){ // get current lane number int lane; if(d > 0 && d <= 4){ lane = 0; } else if (d > 4 && d <= 8){ lane = 1; } else if (d > 8 && d < 12){ lane = 2; } return lane; } float lane_speed(int lane, int curr_lane, float car_s, vector< vector<double> > sensor_fusion){ // get lane speed for(int i = 0; i < sensor_fusion.size(); ++i){ float d = sensor_fusion[i][6]; if(d < (4 * lane + 4) && d > (4 * lane)){ double vx = sensor_fusion[i][3]; double vy = sensor_fusion[i][4]; double speed = sqrt(vx * vx + vy * vy); double s = sensor_fusion[i][5]; if(lane == curr_lane){ // only search car ahead on our current lane if(s > car_s && (s - car_s) < 30){ //std::cout << "current lane speed: " << speed << " dist:" << (s - car_s) << std::endl; return speed; } } else { // search 50m ahead and 20m behind of ego car on other lanes if((s - car_s) < 50 && (s - car_s) > -20){ //std::cout << "lane: " << lane << " speed: " << speed << " dist:" << fabs(s - car_s) << std::endl; return speed; } } } } return -1.0; } float get_vehicle_ahead(int lane, int prev_size, vector< vector<double> > sensor_fusion, float car_s){ // search for car ahead of our future position (within 50m) float ds = 50; float inquired_car_s = -1.0; for(int i = 0; i < sensor_fusion.size(); ++i){ float d = sensor_fusion[i][6]; if(d < (4 * lane + 4) && d > (4 * lane)){ double vx = sensor_fusion[i][3]; double vy = sensor_fusion[i][4]; double check_speed = sqrt(vx * vx + vy * vy); double check_car_s = sensor_fusion[i][5]; check_car_s += ((double)prev_size * .02 * check_speed); if(check_car_s >= car_s && ((check_car_s - car_s) < ds)){ inquired_car_s = check_car_s; ds = check_car_s - car_s; } } } return inquired_car_s; } float get_vehicle_behind(int lane, int prev_size, vector< vector<double> > sensor_fusion, float car_s){ // search for car behind of our future position (within 50m) float ds = -50; float inquired_car_s = -1.0; for(int i = 0; i < sensor_fusion.size(); ++i){ float d = sensor_fusion[i][6]; if(d < (4 * lane + 4) && d > (4 * lane)){ double vx = sensor_fusion[i][3]; double vy = sensor_fusion[i][4]; double check_speed = sqrt(vx * vx + vy * vy); double check_car_s = sensor_fusion[i][5]; check_car_s += ((double)prev_size * .02 * check_speed); if(check_car_s < car_s && ((check_car_s - car_s) > ds)){ inquired_car_s = check_car_s; ds = check_car_s - car_s; } } } return inquired_car_s; } vector<string> successor_states(string state, int curr_lane, int prev_size, float car_speed, vector< vector<double> > sensor_fusion, float car_s){ // generate possible successor states from current state vector<string> states; if(state.compare("KL") == 0 && (get_vehicle_ahead(curr_lane, prev_size, sensor_fusion, car_s) != -1) && car_speed <= 45){ if(curr_lane > 0){ states.push_back("LCL"); } if(curr_lane < 2){ states.push_back("LCR"); } } // if current state is "LCL" or "LCR", return "KL" states.push_back("KL"); return states; } vector<double> realize_next_state(string& state, int curr_lane, int prev_size, vector< vector<double> > sensor_fusion, string best_next_state, float car_s, float end_path_s){ // std::cout << "current lane: " << curr_lane << std::endl; // Keep lane command float velocity = lane_speed(curr_lane, curr_lane, car_s, sensor_fusion) / 0.447; if(velocity < 0){velocity = 49.5;}; int lane = curr_lane; state = "KL"; if(prev_size == 0){ end_path_s = car_s; } if (best_next_state.compare("LCL") == 0){ // Lane change left command // get vehicle ahead and behind in the next lane float s_ahead = get_vehicle_ahead(curr_lane - 1, prev_size, sensor_fusion, end_path_s); float s_behind = get_vehicle_behind(curr_lane - 1, prev_size, sensor_fusion, end_path_s); // change lane to left when safe, speed set to lane speed if((s_ahead == -1.0 || (s_ahead - end_path_s) > 5) && (s_behind == -1.0 || (s_behind - end_path_s) < -5)){ velocity = lane_speed(curr_lane - 1, curr_lane, car_s, sensor_fusion) / 0.447; if(velocity < 0){velocity = 49.5;} lane = curr_lane - 1; state = "LCL"; } } else if (best_next_state.compare("LCR") == 0){ // Lane change right command // get vehicle ahead and behind in the next lane float s_ahead = get_vehicle_ahead(curr_lane + 1, prev_size, sensor_fusion, end_path_s); float s_behind = get_vehicle_behind(curr_lane + 1, prev_size, sensor_fusion, end_path_s); // change lane to right when safe, speed set to lane speed if((s_ahead == -1.0 || (s_ahead - end_path_s) > 5) && (s_behind == -1.0 || (s_behind - end_path_s) < -5)){ velocity = lane_speed(curr_lane + 1, curr_lane, car_s, sensor_fusion) / 0.447; if(velocity < 0){velocity = 49.5;} lane = curr_lane + 1; state = "LCR"; } } return {velocity, (double)lane}; } float calculate_cost(int curr_lane, float car_s, string possible_state, vector< vector<double> > sensor_fusion){ // calculate state cost float cost; int d_lane; if(possible_state.compare("KL") == 0){ d_lane = 0; } else if (possible_state.compare("LCL") == 0){ d_lane = -1; } else { d_lane = 1; } int next_lane = curr_lane + d_lane; // determine speed cost (if intended lane speed is high, cost is low) float final_lane_speed = lane_speed(next_lane, curr_lane, car_s, sensor_fusion); // determine adjacent car cost (if cars on intended lane are near to us, cost is high) float s_dist = 9999999; for(int i = 0; i < sensor_fusion.size(); ++i){ float d = sensor_fusion[i][6]; if(d < (4 * next_lane + 4) && d > (4 * next_lane)){ double s = sensor_fusion[i][5]; if(fabs(s - car_s) < s_dist && fabs(s - car_s) >= 1){ s_dist = fabs(s - car_s); } } } // calculate final cost if(final_lane_speed < 0){ // if no car's ahead, don't change lane cost = 0; } else { cost = (50 - final_lane_speed) / 50 / s_dist; // from 0 to 1 } return cost * 100; } vector<double> choose_next_state(int prev_size, string& state, double car_speed, float car_d, vector< vector<double> > sensor_fusion, float car_s, float end_path_s){ // choose best next state int curr_lane = get_lane(car_d); vector<string> possible_successor_states = successor_states(state, curr_lane, prev_size, car_speed, sensor_fusion, car_s); vector<float> costs; for(int i = 0; i < possible_successor_states.size(); ++i){ float cost = calculate_cost(curr_lane, car_s, possible_successor_states[i], sensor_fusion); costs.push_back(cost); } /* std::cout << "possible states: " << std::endl; for(int i = 0; i < possible_successor_states.size(); ++i){ std::cout << possible_successor_states[i] << " cost: " << costs[i] << std::endl; } */ string best_next_state = ""; float min_cost = 9999999; for(int i = 0; i < costs.size(); ++i){ if(costs[i] < min_cost){ min_cost = costs[i]; best_next_state = possible_successor_states[i]; } } //std::cout << "best next state: " << best_next_state << std::endl; return realize_next_state(state, curr_lane, prev_size, sensor_fusion, best_next_state, car_s, end_path_s); } int main() { uWS::Hub h; // Load up map values for waypoint's x,y,s and d normalized normal vectors vector<double> map_waypoints_x; vector<double> map_waypoints_y; vector<double> map_waypoints_s; vector<double> map_waypoints_dx; vector<double> map_waypoints_dy; // Waypoint map to read from string map_file_ = "../data/highway_map.csv"; // The max s value before wrapping around the track back to 0 double max_s = 6945.554; std::ifstream in_map_(map_file_.c_str(), std::ifstream::in); string line; while (getline(in_map_, line)) { std::istringstream iss(line); double x; double y; float s; float d_x; float d_y; iss >> x; iss >> y; iss >> s; iss >> d_x; iss >> d_y; map_waypoints_x.push_back(x); map_waypoints_y.push_back(y); map_waypoints_s.push_back(s); map_waypoints_dx.push_back(d_x); map_waypoints_dy.push_back(d_y); } // velocity reference mph double vel_ref = 0; // lane number int lane_nb = 1; // initial state string state = "KL"; h.onMessage([&vel_ref,&lane_nb,&state,&map_waypoints_x,&map_waypoints_y,&map_waypoints_s, &map_waypoints_dx,&map_waypoints_dy] (uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(data); if (s != "") { auto j = json::parse(s); string event = j[0].get<string>(); if (event == "telemetry") { // j[1] is the data JSON object // Main car's localization Data double car_x = j[1]["x"]; double car_y = j[1]["y"]; double car_s = j[1]["s"]; double car_d = j[1]["d"]; double car_yaw = j[1]["yaw"]; double car_speed = j[1]["speed"]; // Previous path data given to the Planner auto previous_path_x = j[1]["previous_path_x"]; auto previous_path_y = j[1]["previous_path_y"]; // Previous path's size int prev_size = previous_path_x.size(); // Previous path's end s and d values double end_path_s = j[1]["end_path_s"]; double end_path_d = j[1]["end_path_d"]; // Sensor Fusion Data, a list of all other cars on the same side // of the road. auto sensor_fusion = j[1]["sensor_fusion"]; json msgJson; /* // code from project walk through if(prev_size > 0){ car_s = end_path_s; } bool too_close = false; for(int i = 0; i < sensor_fusion.size(); ++i){ float d = sensor_fusion[i][6]; // front car is in my lane if(d < (4 * lane_nb + 4) && d > (4 * lane_nb)){ double vx = sensor_fusion[i][3]; double vy = sensor_fusion[i][4]; double check_speed = sqrt(vx * vx + vy * vy); double check_car_s = sensor_fusion[i][5]; check_car_s += ((double)prev_size * .02 * check_speed); if((check_car_s > car_s) && ((check_car_s - car_s) < 25)){ //vel_ref = check_speed / 0.447; too_close = true; if(lane_nb > 0){ lane_nb = 0; } } } } if(too_close){ vel_ref -= .224; } else if(vel_ref < 49.5){ vel_ref += .224; } */ // call FSM and returns velocity and lane number referneces vector<double> refs = choose_next_state(prev_size, state, car_speed, car_d, sensor_fusion, car_s, end_path_s); double velocity = refs[0]; int next_lane = (int)refs[1]; //std::cout << state << std::endl; //std::cout << "vel: " << velocity << " lane: " << lane_nb << std::endl; // smooth accelerate/decelerate if(vel_ref > velocity){ vel_ref -= .224; } else if(vel_ref < velocity){ vel_ref += .224; } // make another action after finished last action (prevent wandering around between lanes) int curr_lane = get_lane(car_d); if(lane_nb == curr_lane){ lane_nb = next_lane; } // anchor points vector for spline vector<double> ptsx; vector<double> ptsy; double ref_x = car_x; double ref_y = car_y; double ref_yaw = deg2rad(car_yaw); // add two points into the vector if(prev_size < 2){ // find tangent previous points double prev_car_x = car_x - cos(car_yaw); double prev_car_y = car_y - sin(car_yaw); ptsx.push_back(prev_car_x); ptsx.push_back(car_x); ptsy.push_back(prev_car_y); ptsy.push_back(car_y); } else{ // take last two waypoints from previous path ref_x = previous_path_x[prev_size-1]; ref_y = previous_path_y[prev_size-1]; double ref_x_prev = previous_path_x[prev_size-2]; double ref_y_prev = previous_path_y[prev_size-2]; ref_yaw = atan2(ref_y - ref_y_prev, ref_x - ref_x_prev); ptsx.push_back(ref_x_prev); ptsx.push_back(ref_x); ptsy.push_back(ref_y_prev); ptsy.push_back(ref_y); } // Add 35m spaced points in frenet vector<double> next_wp0 = getXY(car_s + 35, (2 + 4*lane_nb), map_waypoints_s, map_waypoints_x, map_waypoints_y); vector<double> next_wp1 = getXY(car_s + 70, (2 + 4*lane_nb), map_waypoints_s, map_waypoints_x, map_waypoints_y); vector<double> next_wp2 = getXY(car_s + 105, (2 + 4*lane_nb), map_waypoints_s, map_waypoints_x, map_waypoints_y); ptsx.push_back(next_wp0[0]); ptsx.push_back(next_wp1[0]); ptsx.push_back(next_wp2[0]); ptsy.push_back(next_wp0[1]); ptsy.push_back(next_wp1[1]); ptsy.push_back(next_wp2[1]); // shift the coordinate to the car's frame for(int i = 0; i < ptsx.size(); ++i){ double shift_x = ptsx[i] - ref_x; double shift_y = ptsy[i] - ref_y; ptsx[i] = (shift_x * cos(-ref_yaw) - shift_y * sin(-ref_yaw)); ptsy[i] = (shift_x * sin(-ref_yaw) + shift_y * cos(-ref_yaw)); } // set spline points tk::spline s; s.set_points(ptsx, ptsy); // path points going into simualtor vector<double> next_x_vals; vector<double> next_y_vals; // copy from previous path for continuity for(int i = 0; i < prev_size; ++i){ next_x_vals.push_back(previous_path_x[i]); next_y_vals.push_back(previous_path_y[i]); } // get spline value and extend path double target_x = 30.0; double target_y = s(target_x); double target_dist = sqrt(target_x * target_x + target_y * target_y); double x_prime = 0; for (int i = 0; i < 50 - prev_size; ++i) { double N = target_dist / (.02 * vel_ref * 0.447); double x_point = x_prime + target_x / N; double y_point = s(x_point); x_prime = x_point; double x_ref = x_point; double y_ref = y_point; // transform back to map coordiante x_point = (x_ref * cos(ref_yaw) - y_ref * sin(ref_yaw)); y_point = (x_ref * sin(ref_yaw) + y_ref * cos(ref_yaw)); x_point += ref_x; y_point += ref_y; next_x_vals.push_back(x_point); next_y_vals.push_back(y_point); } msgJson["next_x"] = next_x_vals; msgJson["next_y"] = next_y_vals; auto msg = "42[\"control\","+ msgJson.dump()+"]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } // end "telemetry" if } else { // Manual driving std::string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } // end websocket if }); // end h.onMessage h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
34.040816
174
0.530794
[ "object", "vector", "transform" ]
e276e62011aebbd6214821cccd7338c69661b97b
12,521
cc
C++
external/netdef_models/lmbspecialops/src/flowwarp.cc
zhuhu00/MOTSFusion_modify
190224a7c3fbded69fedf9645a0ebbf08227fb6d
[ "MIT" ]
null
null
null
external/netdef_models/lmbspecialops/src/flowwarp.cc
zhuhu00/MOTSFusion_modify
190224a7c3fbded69fedf9645a0ebbf08227fb6d
[ "MIT" ]
null
null
null
external/netdef_models/lmbspecialops/src/flowwarp.cc
zhuhu00/MOTSFusion_modify
190224a7c3fbded69fedf9645a0ebbf08227fb6d
[ "MIT" ]
null
null
null
// // lmbspecialops - a collection of tensorflow ops // Copyright (C) 2017 Oezguen Cicek, Eddy Ilg // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // 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, see <http://www.gnu.org/licenses/>. // #include "config.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/op_kernel.h" #include <math.h> #define min(a,b) ((a<b)?(a):(b)) #define max(a,b) ((a>b)?(a):(b)) using namespace tensorflow; REGISTER_OP("FlowWarp") .Attr("T: {float}") .Attr("fill_parameter: {'zero', 'not_a_number'} = 'zero'") .Input("image: T") .Input("flow: T") .Output("warped: T") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { // check if both inputs have rank 4 using namespace ::tensorflow::shape_inference; ShapeHandle image_shape, flow_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &image_shape)); TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 4, &flow_shape)); // check if width and height are compatible ShapeHandle image_shape2d; c->Subshape(image_shape, -2, &image_shape2d); ShapeHandle flow_shape2d; c->Subshape(flow_shape, -2, &flow_shape2d); ShapeHandle merged_shape2d; TF_RETURN_IF_ERROR(c->Merge(image_shape2d, flow_shape2d, &merged_shape2d)); // check if N is compatible for both inputs DimensionHandle image_first_dim = c->Dim(image_shape, 0); DimensionHandle flow_first_dim = c->Dim(flow_shape, 0); DimensionHandle d_first; TF_RETURN_IF_ERROR(c->Merge(image_first_dim, flow_first_dim, &d_first)); // check if C == 2 for the flow DimensionHandle d_c; TF_RETURN_IF_ERROR(c->WithValue(c->Dim(c->input(1), 1), 2, &d_c)); // make sure warped has the same size as image c->set_output(0, c->input(0)); return Status::OK(); }) .Doc(R"doc( Warps the image with the given flow. image: Input tensor of rank 4 and data format "NCHW". flow: Input tensor of rank 4 and data format "NCHW". warped: A tensor of rank 4 and data format "NCHW" for the warped image. )doc"); template<class T> class FlowWarpOp : public OpKernel { public: explicit FlowWarpOp(OpKernelConstruction* construction) :OpKernel(construction) { std::string fill_parameter_str; OP_REQUIRES_OK(construction, construction->GetAttr("fill_parameter", &fill_parameter_str)); if( fill_parameter_str == "zero" ) fill_parameter = ZERO; else fill_parameter = NOT_A_NUMBER; } void Compute(OpKernelContext* context) override { // Get the inputs const Tensor& image_tensor = context->input(0); const Tensor& flow_tensor = context->input(1); // Get the shapes const TensorShape image_shape(image_tensor.shape()); // Allocate the memory for the warped image Tensor* warped_tensor = 0; OP_REQUIRES_OK(context, context->allocate_output(0, image_shape, &warped_tensor)); // Prepare for warping auto image = image_tensor.flat<T>(); auto flow = flow_tensor.flat<T>(); auto warped = warped_tensor->flat<T>(); int num = image_shape.dim_size(0); int channels = image_shape.dim_size(1); int height = image_shape.dim_size(2); int width = image_shape.dim_size(3); FlowWarp_CPU(warped.data(), image.data(), flow.data(), num, channels, height, width); } void FlowWarp_CPU( T* warped, const T* image, const T* flow, const int num, const int channels, const int height, const int width ) { const int wh_size = width * height; const int whc_size = width * height * channels; float fill_value = fill_parameter == ZERO ? 0 : NAN; for(int n=0; n<num; n++) { int off = whc_size * n; for(int x=0; x<width; x++) for(int y=0; y<height; y++) { float fx = flow[2*wh_size*n + y*width + x]; float fy = flow[2*wh_size*n + wh_size + y*width + x]; float x2 = float(x) + fx; float y2 = float(y) + fy; if(x2>=0 && y2>=0 && x2<width && y2<height) { int ix2_L = int(x2); int iy2_T = int(y2); int ix2_R = min(ix2_L+1, width-1); int iy2_B = min(iy2_T+1, height-1); float alpha=x2-ix2_L; float beta=y2-iy2_T; for(int c=0; c<channels; c++) { float TL = image[off + c*wh_size + iy2_T*width + ix2_L]; float TR = image[off + c*wh_size + iy2_T*width + ix2_R]; float BL = image[off + c*wh_size + iy2_B*width + ix2_L]; float BR = image[off + c*wh_size + iy2_B*width + ix2_R]; warped[off + c*wh_size + y*width + x] = (1-alpha)*(1-beta)*TL + alpha*(1-beta)*TR + (1-alpha)*beta*BL + alpha*beta*BR; } } else { for(int c=0; c<channels; c++) warped[off + c*wh_size + y*width + x] = fill_value; } } } } private: enum FillParameter {ZERO = 1, NOT_A_NUMBER = 2}; FillParameter fill_parameter; }; #define REG_KB(type) \ REGISTER_KERNEL_BUILDER( \ Name("FlowWarp") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ FlowWarpOp<type>); REG_KB(float) #undef REG_KB REGISTER_OP("FlowWarpGrad") .Attr("T: {float}") .Input("image: T") .Input("flow: T") .Input("gradient: T") .Output("image_grad: T") .Output("flow_grad: T") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { c->set_output(0, c->input(0)); c->set_output(1, c->input(1)); return Status::OK(); }) .Doc(R"doc( This computes the gradient for the op 'FlowWarp'. )doc"); template <class T> class FlowWarpGradOp : public OpKernel { public: explicit FlowWarpGradOp(OpKernelConstruction* construction) :OpKernel(construction) {} void Compute( OpKernelContext* context ) override { // Get the inputs const Tensor& image_tensor = context->input(0); const Tensor& flow_tensor = context->input(1); const Tensor& gradient_tensor = context->input(2); // Get the shapes const TensorShape image_shape(image_tensor.shape()); const TensorShape flow_shape(flow_tensor.shape()); // Allocate the memory for the output Tensor* image_grad_tensor; OP_REQUIRES_OK(context, context->allocate_output(0, image_shape, &image_grad_tensor)); Tensor* flow_grad_tensor; OP_REQUIRES_OK(context, context->allocate_output(1, flow_shape, &flow_grad_tensor)); // Prepare for gradient computation auto flow = flow_tensor.flat<T>(); auto image = image_tensor.flat<T>(); auto gradient = gradient_tensor.flat<T>(); auto image_grad = image_grad_tensor->flat<T>(); auto flow_grad = flow_grad_tensor->flat<T>(); int num = image_shape.dim_size(0); int channels = image_shape.dim_size(1); int height = image_shape.dim_size(2); int width = image_shape.dim_size(3); FlowWarpGrad_CPU(image_grad.data(), flow_grad.data(), image.data(), flow.data(), gradient.data(), num, channels, height, width); } void FlowWarpGrad_CPU( T* image_grad, T* flow_grad, const T* image, const T* flow, const T* gradient, const int num, const int channels, const int height, const int width ) { const int wh_size = width * height; const int whc_size = width * height * channels; for(int i=0; i<num*whc_size; i++) image_grad[i] = 0 ; for(int i=0; i<num*whc_size; i++) flow_grad[i] = 0 ; for(int n=0; n<num; n++) { int off = whc_size * n; for(int x=0; x<width; x++) for(int y=0; y<height; y++) { float fx = flow[2*wh_size*n + y*width + x]; float fy = flow[2*wh_size*n + wh_size + y*width + x]; float x2 = float(x) + fx; float y2 = float(y) + fy; if(x2>=0 && y2>=0 && x2<width && y2<height) { int ix2_L = int(x2); int iy2_T = int(y2); int ix2_R = min(ix2_L+1, width-1); int iy2_B = min(iy2_T+1, height-1); float alpha=x2-ix2_L; float beta=y2-iy2_T; for(int c=0; c<channels; c++) { float warped_diff_value = gradient[off + c*wh_size + y*width + x]; image_grad[off + c*wh_size + iy2_T*width + ix2_L] += warped_diff_value * (1-alpha)*(1-beta); image_grad[off + c*wh_size + iy2_T*width + ix2_R] += warped_diff_value * alpha*(1-beta); image_grad[off + c*wh_size + iy2_B*width + ix2_L] += warped_diff_value * (1-alpha)*beta; image_grad[off + c*wh_size + iy2_B*width + ix2_R] += warped_diff_value * alpha*beta; } float gamma = iy2_B - y2; float bot_diff = 0; for(int c=0; c<channels; c++) { float temp = 0; temp += gamma * (image[off + c*wh_size + iy2_T*width + ix2_R] - image[off + c*wh_size + iy2_T*width + ix2_L]); temp += (1-gamma) * (image[off + c*wh_size + iy2_B*width + ix2_R] - image[off + c*wh_size + iy2_B*width + ix2_L]); bot_diff += gradient[off + c*wh_size + y*width + x] * temp; } flow_grad[2*wh_size*n + y*width + x] = bot_diff; gamma = ix2_R - x2; bot_diff = 0; for(int c=0; c<channels; c++) { float temp = 0; temp += gamma * (image[off + c*wh_size + iy2_B*width + ix2_L] - image[off + c*wh_size + iy2_T*width + ix2_L]); temp += (1-gamma) * (image[off + c*wh_size + iy2_B*width + ix2_R] - image[off + c*wh_size + iy2_T*width + ix2_R]); bot_diff += gradient[off + c*wh_size + y*width + x] * temp; } flow_grad[2*wh_size*n + wh_size + y*width + x] = bot_diff; } } } } }; #define REG_KB(type) \ REGISTER_KERNEL_BUILDER( \ Name("FlowWarpGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ FlowWarpGradOp<type>); REG_KB(float) #undef REG_KB
37.376119
138
0.516173
[ "shape" ]
e27740a8aac9a079c34671c8e4b3df7cb90cff9c
3,388
cpp
C++
src/LogicalProcessorObjectInstanceSubscribed.cpp
hnrck/seaplanes
1455dd8854b4a0555c04268c10c8c5c02458ddd0
[ "MIT" ]
null
null
null
src/LogicalProcessorObjectInstanceSubscribed.cpp
hnrck/seaplanes
1455dd8854b4a0555c04268c10c8c5c02458ddd0
[ "MIT" ]
null
null
null
src/LogicalProcessorObjectInstanceSubscribed.cpp
hnrck/seaplanes
1455dd8854b4a0555c04268c10c8c5c02458ddd0
[ "MIT" ]
null
null
null
//! \file SeaplanesObjectInstanceSubscribed.cc //! \author Henrick Deschamps (henrick.deschamps [at] isae-supaero [dot] fr) //! \version 1.0.0 //! \date July, 2016 //! \brief Rosace Subscribed object instance manipulation implementation. #include <LogicalProcessorObjectInstanceSubscribed.h> using std::make_unique; namespace Seaplanes { #if !USE_CERTI_MESSAGE_BUFFER // If the CERTI message buffer is not used, a buffer is declared for reception. #define MESSAGE_BUFFER_LENGTH 256 char messageBuffer[MESSAGE_BUFFER_LENGTH]; #endif // USE_CERTI_MESSAGE_BUFFER ObjectInstanceSubscribed::ObjectInstanceSubscribed(Name name, SpObject sp_object) : ObjectInstance(move(name), move(sp_object)), __map_sp_attributes_(MapHandleSpAttribute()) {} UpObjectInstanceSubscribed ObjectInstanceSubscribed::create(Name name, SpObject sp_object) { return make_unique<ObjectInstanceSubscribed>(move(name), sp_object); } void ObjectInstanceSubscribed::initAttributesMap() { for (auto &sp_attribute : __sp_attributes_) { __map_sp_attributes_[sp_attribute->getHandle()] = sp_attribute; } } void ObjectInstanceSubscribed::subscribeObjectClassAttributes( RTI::RTIambassador *rtiAmb) { rtiAmb->subscribeObjectClassAttributes(__sp_object_->getHandle(), *__up_instance_attributes_); } void ObjectInstanceSubscribed::waitRegistering(RTI::RTIambassador *rtiAmb) { while (!getDiscovered()) { rtiAmb->tick2(); } } void ObjectInstanceSubscribed::unsubscribe(RTI::RTIambassador *rtiAmb) { rtiAmb->unsubscribeObjectClass(__sp_object_->getHandle()); } void ObjectInstanceSubscribed::tryToDiscover( const Name &name, const RTI::ObjectClassHandle &objectClassHandle, const RTI::ObjectHandle &objectHandle) { if (objectClassHandle == __sp_object_->getHandle()) { // if (name_.compare(objectName) == 0) { if (__name_ == name) { setHandle(objectHandle); setDiscovered(); } } } void ObjectInstanceSubscribed::reflectAttributeValues( const RTI::AttributeHandleValuePairSet &receivedAttributes) { RTI::ULong valueLength; RTI::AttributeHandle attributeHandle; #if USE_CERTI_MESSAGE_BUFFER libhla::MessageBuffer buffer; #endif // USE_CERTI_MESSAGE_BUFFER for (auto i = 0U; i < receivedAttributes.size(); ++i) { attributeHandle = receivedAttributes.getHandle(i); valueLength = receivedAttributes.getValueLength(i); #if USE_CERTI_MESSAGE_BUFFER buffer.resize(valueLength); buffer.reset(); receivedAttributes.getValue(i, static_cast<char *>(buffer(0)), valueLength); buffer.assumeSizeFromReservedBytes(); #else // USE_CERTI_MESSAGE_BUFFER receivedAttributes.getValue(i, static_cast<char *>(messageBuffer), valueLength); #endif // USE_CERTI_MESSAGE_BUFFER #if USE_CERTI_MESSAGE_BUFFER const double value = buffer.read_double(); // buffer.read_doubles(&value, 0); mapped_attributes_[attributeHandle]->setValue(value); #else // USE_CERTI_MESSAGE_BUFFER // generic. auto *const p_value = reinterpret_cast<double *>(messageBuffer); __map_sp_attributes_[attributeHandle]->setValue(*p_value); #endif // USE_CERTI_MESSAGE_BUFFER } } } // namespace Seaplanes
34.571429
81
0.7134
[ "object" ]
e284a938c2c3d301833e4c323076e34ca090aff1
719
cpp
C++
Algorithmic Toolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.cpp
linroid/my_practice
74490cf296d6373fe04304c9d7d4827e0aea8741
[ "MIT" ]
3
2016-11-29T06:13:05.000Z
2021-03-12T17:56:21.000Z
Algorithmic Toolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.cpp
linroid/my_practice
74490cf296d6373fe04304c9d7d4827e0aea8741
[ "MIT" ]
null
null
null
Algorithmic Toolbox/week2_algorithmic_warmup/8_last_digit_of_the_sum_of_squares_of_fibonacci_numbers/fibonacci_sum_squares.cpp
linroid/my_practice
74490cf296d6373fe04304c9d7d4827e0aea8741
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> const int kPeriodLength = 60; int fibonacci_sum_squares(long long n) { if (n <= 1) { return n; } long long sum = 0; long long previous = 0; long long current = 1; std::vector<int> last_digits(kPeriodLength); last_digits[0] = 0; last_digits[1] = 1; for (int i = 2; i < kPeriodLength; ++i) { long long tmp_previous = previous; previous = current; current = (tmp_previous + current) % 10; last_digits[i] = current; } // (F(n) * F(n + 1)) % 10 return (last_digits[n % kPeriodLength] * last_digits[(n + 1) % kPeriodLength]) % 10; } int main() { long long n = 0; std::cin >> n; std::cout << fibonacci_sum_squares(n) << std::endl; }
21.787879
86
0.613352
[ "vector" ]
e288377800d1d470e5eff0577718915f7095d3c8
3,023
cc
C++
RAVL2/Math/Optimisation/FitHomog2dPoints.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Optimisation/FitHomog2dPoints.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Optimisation/FitHomog2dPoints.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2002, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here //! rcsid="$Id: FitHomog2dPoints.cc 3073 2003-06-13 07:18:32Z craftit $" //! lib=RavlOptimise //! file="Ravl/Math/Optimisation/FitHomog2dPoints.cc" #include "Ravl/FitHomog2dPoints.hh" #include "Ravl/StateVectorHomog2d.hh" #include "Ravl/ObservationHomog2dPoint.hh" #include "Ravl/ObservationImpHomog2dPoint.hh" #include "Ravl/Matrix3d.hh" namespace RavlN { //: Constructor. FitHomog2dPointsBodyC::FitHomog2dPointsBodyC(RealT nzh1, RealT nzh2) { zh1 = nzh1; zh2 = nzh2; } //: Constructor. FitHomog2dPointsBodyC::FitHomog2dPointsBodyC() { zh1 = zh2 = 1.0; } //: Fit parameters to sample of observations StateVectorC FitHomog2dPointsBodyC::FitModel(DListC<ObservationC> sample) { // we need at least four points to fit a 2D line if ( sample.Size() < 4 ) throw ExceptionC("Sample size too small in FitHomog2dPointsBodyC::FitToSample(). "); if ( sample.Size() == 4 ) { // initialise homography P by fitting to four point pairs, assuming that // bottom-right element P[2][2] is not zero. // Construct 8x8 matrix of linear equations MatrixC A(8,8); A.Fill(0.0); VectorC b(8); // distinguish between explicit and implicit forms of point observations IntT i=0; for(DLIterC<ObservationC> it(sample);it;it++, i++) { const ObservationC &obs = it.Data(); RealT x1, y1, x2, y2; if ( dynamic_cast<const ObservationExplicitBodyC *>(&obs.Body()) != 0 ) { // explicit form of point observation const ObservationHomog2dPointC &eobs = obs; x1=eobs.GetZ1()[0]; y1=eobs.GetZ1()[1]; x2=eobs.GetZ()[0]; y2=eobs.GetZ()[1]; } else { // implicit form of point observation const ObservationImpHomog2dPointC &iobs = obs; x1=iobs.GetZ()[0]; y1=iobs.GetZ()[1]; x2=iobs.GetZ()[2]; y2=iobs.GetZ()[3]; } A[i*2][0] = x1*zh2; A[i*2][1] = y1*zh2; A[i*2][2] = zh1*zh2; A[i*2][6] = -x1*x2; A[i*2][7] = -y1*x2; b[i*2] = zh1*x2; A[i*2+1][3] = x1*zh2; A[i*2+1][4] = y1*zh2; A[i*2+1][5] = zh1*zh2; A[i*2+1][6] = -x1*y2; A[i*2+1][7] = -y1*y2; b[i*2+1] = zh1*y2; } // solve for solution vector if(!SolveIP(A,b)) throw ExceptionNumericalC("Dependent linear equations in FitHomog2dPointsBodyC::FitModel(DListC<ObservationC>). "); Matrix3dC P(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], 1.0); return StateVectorHomog2dC (P,zh1,zh2); } // compute solution for homography parameters using symmetric eigensystem // method throw ExceptionC("Null-space method not implemented in FitHomog2dPointsBodyC::FitToSample(). "); Matrix3dC P(1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0); StateVectorHomog2dC sv(P,zh1,zh2); return sv; } }
32.159574
116
0.652994
[ "vector" ]
e28af36e00178c85a82a1f662a09a30357183e28
474
cpp
C++
Leetcode Problems/645.SetMismatch.cpp
rishusingh022/My-Journey-of-Data-Structures-and-Algorithms
28a70fdf10366fc97ddb9f6a69852b3478b564e6
[ "MIT" ]
1
2021-01-13T07:20:57.000Z
2021-01-13T07:20:57.000Z
Leetcode Problems/645.SetMismatch.cpp
rishusingh022/My-Journey-of-Data-Structures-and-Algorithms
28a70fdf10366fc97ddb9f6a69852b3478b564e6
[ "MIT" ]
1
2021-10-01T18:26:34.000Z
2021-10-01T18:26:34.000Z
Leetcode Problems/645.SetMismatch.cpp
rishusingh022/My-Journey-of-Data-Structures-and-Algorithms
28a70fdf10366fc97ddb9f6a69852b3478b564e6
[ "MIT" ]
7
2021-10-01T16:07:29.000Z
2021-10-04T13:23:48.000Z
class Solution { public: vector<int> findErrorNums(vector<int>& nums) { vector<bool>seen(nums.size() + 1); int twice; for (auto& val : nums) { if (seen[val]) twice = val; else seen[val] = true; } for (int i = 1; i < seen.size(); ++i) { if (!seen[i]) { return vector<int>{twice, i}; } } return vector<int>(); } };
22.571429
50
0.405063
[ "vector" ]
e291b14ca95fb6a88378ddb0ca6ad9286d43b026
10,744
hpp
C++
inc/tinyLMP.hpp
TankleL/tinyLMP
d6f2a28509480531a4d7b205f369a10af678d13d
[ "MIT" ]
null
null
null
inc/tinyLMP.hpp
TankleL/tinyLMP
d6f2a28509480531a4d7b205f369a10af678d13d
[ "MIT" ]
null
null
null
inc/tinyLMP.hpp
TankleL/tinyLMP
d6f2a28509480531a4d7b205f369a10af678d13d
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------------- MIT License Copyright (c) 2018 廖添(Tankle L.) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------- */ #pragma once #include <vector> #include <string> #include <map> /** * Dependency: tinyfsm * link: https://github.com/digint/tinyfsm.git */ #include "tinyfsm.hpp" namespace tinylmp { /************************************************************************/ /* FORWARD-DECLARATION */ /************************************************************************/ class Parser; /************************************************************************/ /* NODE */ /************************************************************************/ struct Node { void reset() { m_attr.clear(); m_name.clear(); m_text.clear(); } std::map<std::string, std::string> m_attr; std::string m_name; std::string m_text; }; /************************************************************************/ /* DOCUMENT */ /************************************************************************/ class Document { public: void push_back( const Node& node) { m_nodes.push_back(node); } const Node& node_at( size_t index) const { return m_nodes.at(index); } size_t node_count() const { return m_nodes.size(); } protected: std::vector<Node> m_nodes; }; namespace _internal_ns { inline bool is_ascii(char ch) { return ((unsigned char)ch) <= 0x7f; } static bool is_legal_nd_name_ch(char ch, bool first_ch) { if (!is_ascii(ch) || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '-' || ch == '_' || (!first_ch && (ch >= '0' && ch <= '9'))) { return true; } return false; } /************************************************************************/ /* PARSE-EVENT */ /************************************************************************/ struct PrsEvent : tinyfsm::Event { PrsEvent(char in_ch) : ch(in_ch) {} char ch; }; /************************************************************************/ /* PARSE-STATE */ /************************************************************************/ class ParseState : public tinyfsm::MooreMachine<ParseState> { public: ParseState() {} virtual ~ParseState() {} public: virtual void react(PrsEvent const &) = 0; protected: #define _DECL_PS_STATIC_MEMBER(_type, _name) _type& _name() _DECL_PS_STATIC_MEMBER(std::string, gtext); _DECL_PS_STATIC_MEMBER(std::string, gndattname); _DECL_PS_STATIC_MEMBER(Document, gdoc); _DECL_PS_STATIC_MEMBER(Node, gndbody); #undef _DECL_PS_STATIC_MEMBER }; /************************************************************************/ /* FORWARD-DECLARATION */ /************************************************************************/ class PS_Text; class PS_NDBody; /************************************************************************/ /* PS-TEXT */ /************************************************************************/ class PS_Text : public ParseState { public: void react(PrsEvent const &ev) override { switch (ev.ch) { case '<': if (gtext().length() > 0) { // convert cached text into a text node. Node nd; nd.m_text = gtext(); gdoc().push_back(nd); } gtext().clear(); gtext().push_back(ev.ch); transit<PS_NDBody>(); break; default: gtext().push_back(ev.ch); } } }; /************************************************************************/ /* PS-NDBODY */ /************************************************************************/ class PS_NDBodyText; class PS_NDBodyWaitClose; class PS_NDAttrName; class PS_NDBodyName : public ParseState { public: void entry() override { gndbody().reset(); } void react(PrsEvent const &ev) override { gtext().push_back(ev.ch); if(is_legal_nd_name_ch(ev.ch, gndbody().m_name.empty())) { gndbody().m_name.push_back(ev.ch); } else if (ev.ch == ' ') { transit<PS_NDAttrName>(); } else if(ev.ch == '/') { transit<PS_NDBodyWaitClose>(); } else if (ev.ch == '>') { transit<PS_NDBodyText>(); } else { // bad syntax gndbody().reset(); transit<PS_Text>(); } } }; class PS_NDAttrValue : public ParseState { public: void entry() override { reset(); } void react(PrsEvent const &ev) override { gtext().push_back(ev.ch); if (!m_value.empty() && m_started && ev.ch != '\"') { m_value.push_back(ev.ch); } else if (!m_started && ev.ch == '\"') { m_started = true; } else if (m_started && ev.ch == '\"') { } } protected: void reset() { m_started = false; m_value.clear(); } std::string m_value; bool m_started; }; class PS_NDAttrName : public ParseState { public: void react(PrsEvent const &ev) override { } }; /************************************************************************/ /* PS-NDBODYWAITCLOSE */ /************************************************************************/ class PS_NDBodyWaitClose : public ParseState { public: void react(PrsEvent const &ev) override { if (ev.ch == '>') { gdoc().push_back(gndbody()); gtext().clear(); transit<PS_Text>(); } else { // bad syntax gtext().push_back(ev.ch); transit<PS_Text>(); } } }; /************************************************************************/ /* PS-NDBODYREMOTECLOSE */ /************************************************************************/ class PS_NDBodyRemoteClose : public ParseState { public: void entry() override { m_name_chk.clear(); } void react(PrsEvent const &ev) override { if(is_legal_nd_name_ch(ev.ch, m_name_chk.empty())) { m_name_chk.push_back(ev.ch); } if (ev.ch == '>') { if (m_name_chk == gndbody().m_name) { gdoc().push_back(gndbody()); gtext().clear(); transit<PS_Text>(); } else { // bad syntax gtext().push_back(ev.ch); transit<PS_Text>(); } } } protected: std::string m_name_chk; }; /************************************************************************/ /* PS-NDBODYREMOTEWAITCLOSE */ /************************************************************************/ class PS_NDBodyRemoteWaitClose : public ParseState { public: void react(PrsEvent const &ev) override { if (ev.ch == '/') { transit<PS_NDBodyRemoteClose>(); } else { // bad syntax gtext().push_back(ev.ch); transit<PS_Text>(); } } }; /************************************************************************/ /* PS-NDBODYTEXT */ /************************************************************************/ class PS_NDBodyText : public ParseState { public: void react(PrsEvent const &ev) override { if (ev.ch == '<') { gtext().push_back(ev.ch); transit<PS_NDBodyRemoteWaitClose>(); } else { gndbody().m_text.push_back(ev.ch); gtext().push_back(ev.ch); } } }; } /************************************************************************/ /* PARSER */ /************************************************************************/ class Parser { friend class _internal_ns::ParseState; public: static bool parse(Document& out, const std::string& content) { using namespace _internal_ns; bool retval = true; _reset_state(); ParseState::start(); for (const auto& ch : content) { ParseState::dispatch(PrsEvent(ch)); } if (ParseState::is_in_state<_internal_ns::PS_Text>() && gtext().length() > 0) { Node nd; nd.m_text = gtext(); gdoc().push_back(nd); } out = gdoc(); return retval; } protected: #define _STATIC_MEMBER(_type, _name) static _type& _name(){static _type _inst_; return _inst_;} _STATIC_MEMBER(std::string, gtext); _STATIC_MEMBER(std::string, gndattname); _STATIC_MEMBER(Document, gdoc); _STATIC_MEMBER(Node, gndbody); #undef _STATIC_MEMBER protected: static void _reset_state() { gtext().clear(); gndbody().reset(); } }; /************************************************************************/ /* PARSER-STATE IMPLEMENTATION */ /************************************************************************/ #define _IMPL_PS_STATIC_MEMBER(_type, _name) inline _type& _internal_ns::ParseState::_name() {return Parser::_name();} _IMPL_PS_STATIC_MEMBER(std::string, gtext); _IMPL_PS_STATIC_MEMBER(std::string, gndattname); _IMPL_PS_STATIC_MEMBER(Document, gdoc); _IMPL_PS_STATIC_MEMBER(Node, gndbody); #undef _IMPL_PS_STATIC_MEMBER }
24.87037
118
0.441176
[ "vector" ]
e29f17c2622b002b4bd46e55a0d12b769341d16d
1,827
hpp
C++
include/codegen/include/System/Runtime/Serialization/Formatters/Binary/BinaryCrossAppDomainAssembly.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Runtime/Serialization/Formatters/Binary/BinaryCrossAppDomainAssembly.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Runtime/Serialization/Formatters/Binary/BinaryCrossAppDomainAssembly.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Runtime::Serialization::Formatters::Binary namespace System::Runtime::Serialization::Formatters::Binary { // Forward declaring type: __BinaryParser class __BinaryParser; } // Completed forward declares // Type namespace: System.Runtime.Serialization.Formatters.Binary namespace System::Runtime::Serialization::Formatters::Binary { // Autogenerated type: System.Runtime.Serialization.Formatters.Binary.BinaryCrossAppDomainAssembly class BinaryCrossAppDomainAssembly : public ::Il2CppObject { public: // System.Int32 assemId // Offset: 0x10 int assemId; // System.Int32 assemblyIndex // Offset: 0x14 int assemblyIndex; // public System.Void Read(System.Runtime.Serialization.Formatters.Binary.__BinaryParser input) // Offset: 0xE26EC8 void Read(System::Runtime::Serialization::Formatters::Binary::__BinaryParser* input); // public System.Void Dump() // Offset: 0xE26F10 void Dump(); // System.Void .ctor() // Offset: 0xE26EC0 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static BinaryCrossAppDomainAssembly* New_ctor(); }; // System.Runtime.Serialization.Formatters.Binary.BinaryCrossAppDomainAssembly } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::Runtime::Serialization::Formatters::Binary::BinaryCrossAppDomainAssembly*, "System.Runtime.Serialization.Formatters.Binary", "BinaryCrossAppDomainAssembly"); #pragma pack(pop)
42.488372
188
0.730159
[ "object" ]
e2a877b3d4ee2b3ea03b7cf3d81a3cc908f6769d
8,724
cpp
C++
src/ScrollButtons.cpp
Futuremappermydud/Menu-Utils
ccc5ee6bafd155bda7c6e32774c39a7663034e73
[ "MIT" ]
null
null
null
src/ScrollButtons.cpp
Futuremappermydud/Menu-Utils
ccc5ee6bafd155bda7c6e32774c39a7663034e73
[ "MIT" ]
null
null
null
src/ScrollButtons.cpp
Futuremappermydud/Menu-Utils
ccc5ee6bafd155bda7c6e32774c39a7663034e73
[ "MIT" ]
null
null
null
#include "ScrollButtons.hpp" #include "BeatSaberUI.hpp" Button* _pageUpFastButton; Button* _pageDownFastButton; Button* _scrollBottomButton; Button* _scrollTopButton; Button* originalUp; Button* originalDown; TableView* tableview; LevelCollectionTableView* CollectionTableView; const float SEGMENT_PERCENT = 0.1f; const int LIST_ITEMS_VISIBLE_AT_ONCE = 6; Array<IPreviewBeatmapLevel*>* beatmaps; void RefreshQuickScroll() { _pageUpFastButton->set_interactable(originalUp->get_interactable()); _pageDownFastButton->set_interactable(originalDown->get_interactable()); _scrollBottomButton->set_interactable(originalDown->get_interactable()); _scrollTopButton->set_interactable(originalUp->get_interactable()); } //Stolen from System.Math int Sign(int value) { if (value < 0) { return -1; } if (value > 0) { return 1; } return 0; } //Hardcoded bad but whatever //System.Array.FindIndex int FindIndex(Array<IPreviewBeatmapLevel*>* array, int startIndex, int count, std::string TargetID) { int num = startIndex + count; for (int i = startIndex; i < num; i++) { if (to_utf8(csstrtostr(array->values[i]->get_levelID())) == TargetID) { return i; } } return -1; } void ScrollToLevelByRow(int selectedIndex) { int selectedRow = CollectionTableView->selectedRow; if (selectedRow != selectedIndex && CollectionTableView->get_isActiveAndEnabled()) { CollectionTableView->HandleDidSelectRowEvent(tableview, selectedIndex); } tableview->ScrollToCellWithIdx(selectedIndex, TableViewScroller::ScrollPositionType::Beginning, true); //tableview->SelectCellWithIdx(selectedIndex, true); RefreshQuickScroll(); } void JumpSongList(int numJumps, float segmentPercent) { int totalSize = beatmaps->Length(); int segmentSize = (int)(totalSize * segmentPercent); if (segmentSize < LIST_ITEMS_VISIBLE_AT_ONCE) { segmentSize = LIST_ITEMS_VISIBLE_AT_ONCE; } int currentRow = CollectionTableView->selectedRow; int jumpDirection = Sign(numJumps); int newRow = currentRow + (jumpDirection * segmentSize); if (newRow <= 0) { newRow = 0; } else if (newRow >= totalSize) { newRow = totalSize - 1; } int selectedIndex = 0; if (totalSize <= 0) { return; } int selectedRow = FindIndex(beatmaps, 0, totalSize, to_utf8(csstrtostr(beatmaps->values[newRow]->get_levelID()))); if (selectedIndex < 0) { int selectedRow = CollectionTableView->selectedRow; selectedIndex = System::Math::Min(totalSize, selectedRow); } else { // the header counts as an index, so if the index came from the level array we have to add 1. selectedIndex += 1; } CollectionTableView->SelectLevel(beatmaps->values[newRow]); RefreshQuickScroll(); } void QuickScrollUp() { beatmaps = CollectionTableView->previewBeatmapLevels; JumpSongList(-1, SEGMENT_PERCENT); } void QuickScrollDown() { beatmaps = CollectionTableView->previewBeatmapLevels; JumpSongList(1, SEGMENT_PERCENT); } void ScrollToBottom() { beatmaps = CollectionTableView->previewBeatmapLevels; ScrollToLevelByRow(beatmaps->Length()); CollectionTableView->SelectLevel(beatmaps->values[beatmaps->Length()]); } void ScrollToTop() { beatmaps = CollectionTableView->previewBeatmapLevels; ScrollToLevelByRow(0); CollectionTableView->SelectLevel(beatmaps->values[0]); } void ToggleQuickScrollButtons(bool val) { _pageDownFastButton->get_gameObject()->get_gameObject()->SetActive(val); _pageUpFastButton->get_gameObject()->get_gameObject()->SetActive(val); _scrollBottomButton->get_gameObject()->get_gameObject()->SetActive(val); _scrollTopButton->get_gameObject()->get_gameObject()->SetActive(val); } void CreateQuickScrollButtons(LevelCollectionTableView* self) { CollectionTableView = self; beatmaps = self->previewBeatmapLevels; if(!FirstTime) { tableview = self->tableView; originalDown = tableview->pageDownButton; originalUp = tableview->pageUpButton; RefreshQuickScroll(); } if(!FirstTime) return; FirstTime = false; tableview = self->tableView; originalUp = tableview->pageUpButton; _pageUpFastButton = Object::Instantiate(originalUp, self->get_transform(), false); RectTransform* FastUpRectTransform = (RectTransform*)_pageUpFastButton->get_transform(); FastUpRectTransform->set_anchorMin(UnityEngine::Vector2(0.5f, 1.0f)); FastUpRectTransform->set_anchorMax(UnityEngine::Vector2(0.5f, 1.0f)); FastUpRectTransform->set_anchoredPosition(UnityEngine::Vector2(-26.0f, 1.0f)); FastUpRectTransform->set_sizeDelta(UnityEngine::Vector2(8.0f, 6.0f)); DoubleArrowSprite = BeatSaberUI::Base64ToSprite(DoubleArrow, 56, 36); BeatSaberUI::GetRectByName(_pageUpFastButton, "BG")->set_sizeDelta(UnityEngine::Vector2(8.0f, 6.0f)); BeatSaberUI::GetImageByName(_pageUpFastButton, "Arrow")->set_sprite(DoubleArrowSprite); _scrollTopButton = Object::Instantiate(originalUp, self->get_transform(), false); RectTransform* FastTopRectTransform = (RectTransform*)_scrollTopButton->get_transform(); FastTopRectTransform->set_anchorMin(UnityEngine::Vector2(0.5f, 1.0f)); FastTopRectTransform->set_anchorMax(UnityEngine::Vector2(0.5f, 1.0f)); FastTopRectTransform->set_anchoredPosition(UnityEngine::Vector2(-35.5f, 1.0f)); FastTopRectTransform->set_sizeDelta(UnityEngine::Vector2(8.0f, 6.0f)); TripleArrowSprite = BeatSaberUI::Base64ToSprite(TripleArrow, 56, 50); BeatSaberUI::GetRectByName(_scrollTopButton, "BG")->set_sizeDelta(UnityEngine::Vector2(8.0f, 6.0f)); BeatSaberUI::GetImageByName(_scrollTopButton, "Arrow")->set_sprite(TripleArrowSprite); originalDown = tableview->pageDownButton; _pageDownFastButton = Object::Instantiate(originalDown, self->get_transform(), false); RectTransform* FastDownRectTransform = (RectTransform*)_pageDownFastButton->get_transform(); FastDownRectTransform->set_anchorMin(UnityEngine::Vector2(0.5f, 0.0f)); FastDownRectTransform->set_anchorMax(UnityEngine::Vector2(0.5f, 0.0f)); FastDownRectTransform->set_anchoredPosition(UnityEngine::Vector2(-26.0f, -1.0f)); FastDownRectTransform->set_sizeDelta(UnityEngine::Vector2(8.0f, 6.0f)); BeatSaberUI::GetRectByName(_pageDownFastButton, "BG")->set_sizeDelta(UnityEngine::Vector2(8.0f, 6.0f)); BeatSaberUI::GetImageByName(_pageDownFastButton, "Arrow")->set_sprite(DoubleArrowSprite); auto action = MakeAction<UnityEngine::Events::UnityAction>(il2cpp_functions::class_get_type(il2cpp_utils::GetClassFromName("UnityEngine.Events", "UnityAction")), (Il2CppObject*)nullptr, RefreshQuickScroll); originalUp->get_onClick()->AddListener(action); originalDown->get_onClick()->AddListener(action); auto actionUp = MakeAction<UnityEngine::Events::UnityAction>(il2cpp_functions::class_get_type(il2cpp_utils::GetClassFromName("UnityEngine.Events", "UnityAction")), (Il2CppObject*)nullptr, QuickScrollUp); auto actionDown = MakeAction<UnityEngine::Events::UnityAction>(il2cpp_functions::class_get_type(il2cpp_utils::GetClassFromName("UnityEngine.Events", "UnityAction")), (Il2CppObject*)nullptr, QuickScrollDown); _pageUpFastButton->get_onClick()->AddListener(actionUp); _pageDownFastButton->get_onClick()->AddListener(actionDown); _scrollBottomButton = Object::Instantiate(originalDown, self->get_transform(), false); RectTransform* FastBottomRectTransform = (RectTransform*)_scrollBottomButton->get_transform(); FastBottomRectTransform->set_anchorMin(UnityEngine::Vector2(0.5f, 0.0f)); FastBottomRectTransform->set_anchorMax(UnityEngine::Vector2(0.5f, 0.0f)); FastBottomRectTransform->set_anchoredPosition(UnityEngine::Vector2(-35.5f, -1.0f)); FastBottomRectTransform->set_sizeDelta(UnityEngine::Vector2(8.0f, 6.0f)); BeatSaberUI::GetRectByName(_scrollBottomButton, "BG")->set_sizeDelta(UnityEngine::Vector2(8.0f, 6.5f)); BeatSaberUI::GetImageByName(_scrollBottomButton, "Arrow")->set_sprite(TripleArrowSprite); auto actionBottom = MakeAction<UnityEngine::Events::UnityAction>(il2cpp_functions::class_get_type(il2cpp_utils::GetClassFromName("UnityEngine.Events", "UnityAction")), (Il2CppObject*)nullptr, ScrollToBottom); _scrollBottomButton->get_onClick()->AddListener(actionBottom); auto actionTop = MakeAction<UnityEngine::Events::UnityAction>(il2cpp_functions::class_get_type(il2cpp_utils::GetClassFromName("UnityEngine.Events", "UnityAction")), (Il2CppObject*)nullptr, ScrollToTop); _scrollTopButton->get_onClick()->AddListener(actionTop); }
39.121076
212
0.742779
[ "object" ]
e2ac26a7318842d84a56231865790f46edd14df6
7,945
cpp
C++
EtherlinkerExampleProject/Plugins/Etherlinker/Source/Etherlinker/Private/EtherlinkerRemoteWalletManager.cpp
DeVerse-World/integration-server
b0a5d3db8a801727d972c294b8660346d3fc4753
[ "MIT" ]
null
null
null
EtherlinkerExampleProject/Plugins/Etherlinker/Source/Etherlinker/Private/EtherlinkerRemoteWalletManager.cpp
DeVerse-World/integration-server
b0a5d3db8a801727d972c294b8660346d3fc4753
[ "MIT" ]
null
null
null
EtherlinkerExampleProject/Plugins/Etherlinker/Source/Etherlinker/Private/EtherlinkerRemoteWalletManager.cpp
DeVerse-World/integration-server
b0a5d3db8a801727d972c294b8660346d3fc4753
[ "MIT" ]
null
null
null
// Copyright 2019 Ruslan Nazirov. All Rights Reserved. #include "EtherlinkerRemoteWalletManager.h" #include "EtherlinkerSettings.h" UEtherlinkerRemoteWalletManager::UEtherlinkerRemoteWalletManager() { PrimaryComponentTick.bCanEverTick = false; } void UEtherlinkerRemoteWalletManager::GetWalletData(FWalletAuthenticationRequest walletAuthenticationRequest) { if (GetOwner()->GetLocalRole() < ROLE_Authority) { ServerGetWalletData(walletAuthenticationRequest); return; } MakeRequest(walletAuthenticationRequest, "/getWalletData"); #if !UE_BUILD_SHIPPING UE_LOG(LogTemp, Warning, TEXT("GetWalletData executed")); #endif } void UEtherlinkerRemoteWalletManager::ServerGetWalletData_Implementation(FWalletAuthenticationRequest walletAuthenticationRequest) { GetWalletData(walletAuthenticationRequest); } bool UEtherlinkerRemoteWalletManager::ServerGetWalletData_Validate(FWalletAuthenticationRequest walletAuthenticationRequest) { return true; } void UEtherlinkerRemoteWalletManager::CreateUserAccount(FWalletAuthenticationRequest walletAuthenticationRequest) { if (GetOwner()->GetLocalRole() < ROLE_Authority) { ServerCreateUserAccount(walletAuthenticationRequest); return; } if (walletAuthenticationRequest.walletPath.IsEmpty()) { UEtherlinkerSettings* EtherlinkerSettings = GetMutableDefault<UEtherlinkerSettings>(); check(EtherlinkerSettings); if (!EtherlinkerSettings->DefaultWalletPath.IsEmpty()) { walletAuthenticationRequest.walletPath = EtherlinkerSettings->DefaultWalletPath; } else { walletAuthenticationRequest.walletPath = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir()).Append("EtherlinkerKeys/"); } } MakeRequest(walletAuthenticationRequest, "/createUserAccount"); #if !UE_BUILD_SHIPPING UE_LOG(LogTemp, Warning, TEXT("CreateUserAccount executed")); #endif } void UEtherlinkerRemoteWalletManager::ServerCreateUserAccount_Implementation(FWalletAuthenticationRequest walletAuthenticationRequest) { CreateUserAccount(walletAuthenticationRequest); } bool UEtherlinkerRemoteWalletManager::ServerCreateUserAccount_Validate(FWalletAuthenticationRequest walletAuthenticationRequest) { return true; } bool UEtherlinkerRemoteWalletManager::MakeRequest(FWalletAuthenticationRequest WalletAuthenticationRequest, const FString& URL) { // Get actual server address from settings UEtherlinkerSettings* EtherlinkerSettings = GetMutableDefault<UEtherlinkerSettings>(); check(EtherlinkerSettings); FString serverAddress; if (WalletAuthenticationRequest.serverAddress.IsEmpty()) { serverAddress = EtherlinkerSettings->IntegrationServerURL; } else { serverAddress = WalletAuthenticationRequest.serverAddress; } TSharedPtr<FJsonObject> JsontRequestObject = FJsonObjectConverter::UStructToJsonObject(WalletAuthenticationRequest); FString OutputString; TSharedRef<TJsonWriter<>> JsonWriter = TJsonWriterFactory<>::Create(&OutputString); FJsonSerializer::Serialize(JsontRequestObject.ToSharedRef(), JsonWriter); #if !UE_BUILD_SHIPPING UE_LOG(LogTemp, Warning, TEXT("%s"), *OutputString); #endif TSharedRef<IHttpRequest, ESPMode::ThreadSafe> HttpRequest = FHttpModule::Get().CreateRequest(); HttpRequest->SetVerb("POST"); HttpRequest->SetHeader(TEXT("User-Agent"), "X-UnrealEngine-Agent"); HttpRequest->SetHeader("Content-Type", "application/json"); HttpRequest->SetHeader("SenderId", WalletAuthenticationRequest.senderId); HttpRequest->SetHeader("UserIndex", WalletAuthenticationRequest.userIndex); HttpRequest->SetURL(serverAddress + URL); HttpRequest->SetContentAsString(OutputString); HttpRequest->OnProcessRequestComplete().BindUObject(this, &UEtherlinkerRemoteWalletManager::OnResponseReceived); HttpRequest->ProcessRequest(); return true; } void UEtherlinkerRemoteWalletManager::OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful) { if (!bWasSuccessful || !Response.IsValid()) { // If we can't connect to the server or in case of any other error FWalletAuthenticationResponse walletAuthenticationResponse; walletAuthenticationResponse.data = "Unknown network error in processing HTTP response."; if (!Request->GetHeader("UserIndex").IsEmpty()) { walletAuthenticationResponse.userIndex = Request->GetHeader("UserIndex"); UE_LOG(LogTemp, Error, TEXT("User Index: %s"), *Request->GetHeader("UserIndex")); } if (!Request->GetHeader("SenderId").IsEmpty()) { walletAuthenticationResponse.senderId = Request->GetHeader("SenderId"); UE_LOG(LogTemp, Error, TEXT("Sender Id: %s"), *Request->GetHeader("SenderId")); } else { walletAuthenticationResponse.senderId = "DefaultErrorProcessor"; UE_LOG(LogTemp, Error, TEXT("Sender Id: DefaultErrorProcessor")); } OnResponseReceivedEvent.Broadcast("error", walletAuthenticationResponse); UE_LOG(LogTemp, Error, TEXT("Unknown network error in processing HTTP response.")); } else { //Create a pointer to hold the json serialized data TSharedPtr<FJsonObject> JsonObject; //Create a reader pointer to read the json data TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString()); //Deserialize the json data given Reader and the actual object to deserialize if (FJsonSerializer::Deserialize(Reader, JsonObject)) { FString result = JsonObject->GetStringField("result"); #if !UE_BUILD_SHIPPING UE_LOG(LogTemp, Warning, TEXT("%s"), *result); #endif // Process error response if (result.Equals("error")) { FString errorText = JsonObject->GetStringField("data"); FWalletAuthenticationResponse walletAuthenticationResponse; walletAuthenticationResponse.data = errorText; if (!Request->GetHeader("UserIndex").IsEmpty()) { walletAuthenticationResponse.userIndex = Request->GetHeader("UserIndex"); UE_LOG(LogTemp, Error, TEXT("User Index: %s"), *Request->GetHeader("UserIndex")); } if (!Request->GetHeader("SenderId").IsEmpty()) { walletAuthenticationResponse.senderId = Request->GetHeader("SenderId"); UE_LOG(LogTemp, Error, TEXT("Sender Id: %s"), *Request->GetHeader("SenderId")); } else { walletAuthenticationResponse.senderId = "DefaultErrorProcessor"; UE_LOG(LogTemp, Error, TEXT("Sender Id: DefaultErrorProcessor")); } UE_LOG(LogTemp, Error, TEXT("%s"), *walletAuthenticationResponse.data); OnResponseReceivedEvent.Broadcast(result, walletAuthenticationResponse); } else { // Process normal response TSharedPtr<FJsonObject> JsonResponseObject = JsonObject->GetObjectField("data"); FWalletAuthenticationResponse walletAuthenticationResponse; FJsonObjectConverter::JsonAttributesToUStruct(JsonResponseObject->Values, FWalletAuthenticationResponse::StaticStruct(), &walletAuthenticationResponse, 0, 0); #if !UE_BUILD_SHIPPING UE_LOG(LogTemp, Warning, TEXT("%s"), *walletAuthenticationResponse.data); #endif OnResponseReceivedEvent.Broadcast(result, walletAuthenticationResponse); } } else { // If we can't deserialize JSON response FWalletAuthenticationResponse walletAuthenticationResponse; walletAuthenticationResponse.data = "Can't deserialize JSON response."; if (!Request->GetHeader("UserIndex").IsEmpty()) { walletAuthenticationResponse.userIndex = Request->GetHeader("UserIndex"); UE_LOG(LogTemp, Error, TEXT("User Index: %s"), *Request->GetHeader("UserIndex")); } if (!Request->GetHeader("SenderId").IsEmpty()) { walletAuthenticationResponse.senderId = Request->GetHeader("SenderId"); UE_LOG(LogTemp, Error, TEXT("Sender Id: %s"), *Request->GetHeader("SenderId")); } else { walletAuthenticationResponse.senderId = "DefaultErrorProcessor"; UE_LOG(LogTemp, Error, TEXT("Sender Id: DefaultErrorProcessor")); } OnResponseReceivedEvent.Broadcast("error", walletAuthenticationResponse); UE_LOG(LogTemp, Error, TEXT("Can't deserialize JSON response.")); } } }
34.543478
162
0.778351
[ "object" ]
e2b2c490aa8e205ffb3b1bfd242c8cbfcb9ee767
1,141
cpp
C++
leetcode/115. distinct-subsequences.cpp
cycheng/coding-for-fun
3596ee6e029a9c16bc56d2cadfbe914ce0a03102
[ "MIT" ]
null
null
null
leetcode/115. distinct-subsequences.cpp
cycheng/coding-for-fun
3596ee6e029a9c16bc56d2cadfbe914ce0a03102
[ "MIT" ]
null
null
null
leetcode/115. distinct-subsequences.cpp
cycheng/coding-for-fun
3596ee6e029a9c16bc56d2cadfbe914ce0a03102
[ "MIT" ]
null
null
null
// [1] https://leetcode.com/problems/distinct-subsequences/ // [2] https://ithelp.ithome.com.tw/articles/10218596 // #dp, #string #include "std.h" // r a b b b i t // 1 1 1 1 1 1 1 1 // r 0 1 1 1 1 1 1 1 // a 0 0 1 1 1 1 1 1 // b 0 0 0 1 2 3 3 3 // b 0 0 0 0 1 3 3 3 // i 0 0 0 0 0 0 3 3 // t 0 0 0 0 0 0 0 3 // b a b g b a g // 1 1 1 1 1 1 1 1 // b 0 1 1 2 2 3 3 3 // a 0 0 1 1 1 1 4 4 // g 0 0 0 0 1 1 1 5 int numDistinct_8ms(string s, string t) { const int m = t.length() + 1, n = s.length() + 1; vector<vector<int64_t>> dp(m, vector<int64_t>(n)); for (int i = 0; i < n; ++i) dp[0][i] = 1; for (int i = 1; i < m; ++i) for (int j = 1; j < n; ++j) { if (t[i - 1] == s[j - 1]) dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1]; else dp[i][j] = dp[i][j - 1]; } #ifdef DUMP cout << " "; for (int i = 1; i < n; ++i) cout << s[i - 1] << " "; cout << endl; for (int i = 0; i < m; ++i) { if (i) cout << t[i - 1]; else cout << " "; for (int j = 0; j < n; ++j) cout << " " << dp[i][j]; cout << endl; } #endif return dp[m - 1][n - 1]; }
21.12963
59
0.432954
[ "vector" ]
e2b47c375dc89eb01b023c28b7c1566d99da3c87
2,568
cpp
C++
src/ias/technology/factory/value_type_database_factory.cpp
JoeriHermans/Intelligent-Automation-System
b09c9f2b0c018ac5d12ab01d25297a0a92724e4c
[ "Apache-2.0" ]
1
2021-08-12T10:07:27.000Z
2021-08-12T10:07:27.000Z
src/ias/technology/factory/value_type_database_factory.cpp
JoeriHermans/Intelligent-Automation-System
b09c9f2b0c018ac5d12ab01d25297a0a92724e4c
[ "Apache-2.0" ]
null
null
null
src/ias/technology/factory/value_type_database_factory.cpp
JoeriHermans/Intelligent-Automation-System
b09c9f2b0c018ac5d12ab01d25297a0a92724e4c
[ "Apache-2.0" ]
2
2016-12-06T23:16:18.000Z
2016-12-07T07:26:56.000Z
/** * A value type factory which fetches value type instances from * a database. * * @date Jul 4, 2014 * @author Joeri HERMANS * @version 0.1 * * Copyright 2013 Joeri HERMANS * * 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. */ // BEGIN Includes. /////////////////////////////////////////////////// // System dependencies. #include <cassert> // Application dependencies. #include <ias/technology/factory/value_type_database_factory.h> // END Includes. ///////////////////////////////////////////////////// ValueTypeDatabaseFactory::ValueTypeDatabaseFactory( DatabaseConnection * c ) : DatabaseFactory<ValueType *>(c) { // Nothing to do here. } ValueTypeDatabaseFactory::~ValueTypeDatabaseFactory( void ) { // Nothing to do here. } std::vector<ValueType *> ValueTypeDatabaseFactory::fetchAll( void ) { DatabaseStatement * statement; DatabaseResult * result; DatabaseResultRow * row; std::vector<ValueType *> types; std::string strId; long bufferId; std::size_t id; std::string identifier; std::string name; std::string description; std::string regex; statement = getDbConnection()->createStatement( "SELECT *" "FROM value_types" ); if( statement != nullptr ) { result = statement->execute(); if( result != nullptr ) { while( result->hasNext() ) { row = result->next(); strId = row->getColumn(0); identifier = row->getColumn(1); regex = row->getColumn(2); name = row->getColumn(3); description = row->getColumn(4); bufferId = atol(strId.c_str()); id = static_cast<std::size_t>(bufferId); types.push_back( new ValueType(id,identifier,name,description,regex) ); delete row; } delete result; } delete statement; } return ( types ); }
30.571429
78
0.582944
[ "vector" ]
e2c0ee0ee0ac1bed0129fad3a49668006b1fd35d
4,838
cc
C++
A/6/PerfectHashing.cc
Menci/DataStructureAndAlgorithms
e5d773bd927e83f72dc0c1579e48469200f31620
[ "Unlicense" ]
null
null
null
A/6/PerfectHashing.cc
Menci/DataStructureAndAlgorithms
e5d773bd927e83f72dc0c1579e48469200f31620
[ "Unlicense" ]
null
null
null
A/6/PerfectHashing.cc
Menci/DataStructureAndAlgorithms
e5d773bd927e83f72dc0c1579e48469200f31620
[ "Unlicense" ]
1
2019-11-29T03:59:46.000Z
2019-11-29T03:59:46.000Z
#include <iostream> #include <random> #include <algorithm> #include <tuple> #include <vector> #include <cassert> #include <optional> #include <memory> #include <chrono> template <typename T> class PerfectHashing { std::vector<std::tuple<size_t, size_t, std::vector<std::optional<T>>>> data; size_t n, m, p, a, b; // Get random prime number in [min, max] static size_t getPrime(size_t min, size_t max) { std::vector<bool> isNotPrime(max + 1); std::vector<size_t> primes; // Euler sieve isNotPrime[0] = isNotPrime[1] = true; for (size_t i = 2; i <= max; i++) { if (!isNotPrime[i]) primes.push_back(i); for (size_t p : primes) { size_t x = i * p; if (x > max) break; isNotPrime[x] = true; if (i % p == 0) break; } } // Get the random range std::vector<size_t>::const_iterator l = std::lower_bound(primes.begin(), primes.end(), min), r = std::upper_bound(primes.begin(), primes.end(), max); std::random_device rng; std::uniform_int_distribution<> dis(0, r - l); return *(dis(rng) + l); } size_t hashFunction(const T &x, std::optional<size_t> i = std::nullopt) const { if (i) { auto &[a, b, v] = data[*i]; return ((a * x) % p + b) % p % v.size(); } else { return ((a * x) % p + b) % p % m; } } void initUniversalHashing(size_t &a, size_t &b) { std::random_device rng; do a = rng() % p; while (a == 0); b = rng() % p; } template <typename RAIter> bool build(RAIter begin, RAIter end) { m = n = std::distance(begin, end); p = getPrime(m, 2 * m - 1); data.clear(); data.resize(m); initUniversalHashing(a, b); std::vector<std::vector<T>> buckets(m); for (RAIter it = begin; it != end; it++) { size_t i = hashFunction(*it); buckets[i].push_back(*it); } size_t sumSize = 0; for (size_t i = 0; i < m; i++) { size_t size = buckets[i].size() * buckets[i].size(); if (size < buckets[i].size()) { std::cerr << "rebuild since inner size overflow" << std::endl; return false; } sumSize += size; } constexpr size_t MAX_SPACE_TIMES = 4; if (sumSize > MAX_SPACE_TIMES * n) { std::cerr << "rebuild since space > 4n" << std::endl; return false; } for (size_t i = 0; i < m; ) { auto &[a, b, v] = data[i]; initUniversalHashing(a, b); v.clear(); v.resize(buckets[i].size() * buckets[i].size()); bool rebuild = false; for (auto &x : buckets[i]) { size_t j = hashFunction(x, i); if (v[j]) { rebuild = true; continue; } v[j] = x; } if (rebuild) continue; i++; } return true; } public: template <typename RAIter> PerfectHashing(RAIter begin, RAIter end) { while (!build(begin, end)); } template <typename Container> PerfectHashing(Container c) : PerfectHashing(std::begin(c), std::end(c)) {} bool operator[](const T &x) const { size_t i = hashFunction(x); auto &[a, b, v] = data[i]; if (a == 0) return false; size_t j = hashFunction(x, i); if (v[j]) return *v[j] == x; return false; } }; std::vector<uint64_t> generateRandomData(size_t n) { static std::mt19937_64 rng((std::random_device()())); std::vector<uint64_t> v; for (size_t i = 0; i < n; i++) v.push_back(rng()); return v; } void measureTime(std::string actionName, std::function<void ()> function) { auto startTime = std::chrono::high_resolution_clock::now(); function(); auto endTime = std::chrono::high_resolution_clock::now(); double timeElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count(); std::cerr << actionName << " costs " << timeElapsed / 1000 << "s" << std::endl; } int main() { const size_t DATA_SIZE = 5000000; std::vector<uint64_t> data = generateRandomData(DATA_SIZE); std::cout << "Random data generated" << std::endl; std::shared_ptr<PerfectHashing<uint64_t>> h; measureTime("Create hash table", [&]() { h = std::make_shared<PerfectHashing<uint64_t>>(data); }); measureTime("Check hash table", [&]() { for (size_t i = 0; i < DATA_SIZE; i++) { assert((*h)[data[i]]); } }); }
27.645714
108
0.509921
[ "vector" ]
e2c10b1b78268e52bec414ec26bd5ab28e73e1d9
937
cpp
C++
Dataset/Leetcode/train/56/246.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/56/246.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/56/246.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: bool static cmp(vector<int>&a,vector<int>&b){//排序方式,第一个元素越小排越前面,第二个元素越大排越前面 if(a[0]!=b[0]) return a[0]<b[0]; else return a[1]>b[1]; } vector<vector<int>> XXX(vector<vector<int>>& intervals) { sort(intervals.begin(),intervals.end(),cmp); vector<vector<int>> ans; vector<int> t; t.push_back(intervals[0][0]); t.push_back(intervals[0][1]); for(int i=1;i<intervals.size();i++){ if(t[1]<intervals[i][0])//前一个区间右边界小于当前区间的左边界,说明无交集,可以把之前区间结果存下 { ans.push_back(t); t[0]=intervals[i][0]; t[1]=intervals[i][1]; }else if(t[1]<intervals[i][1]){//前一个区间右边界大于等于当前区间左边界并且小于当前区间右边界,则更新右边界 t[1]=intervals[i][1]; //其余情况,不改变边界 } } ans.push_back(t);//将最后生成的区间存储 return ans; } };
30.225806
82
0.504803
[ "vector" ]
e2ceb997c464e8d0986e98d9329c15baa204f515
6,659
cpp
C++
src/plugins/visualisenormals/visualisenormals.cpp
circlingthesun/cloudclean
4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5
[ "MIT" ]
2
2018-10-18T16:10:21.000Z
2020-05-28T01:52:24.000Z
src/plugins/visualisenormals/visualisenormals.cpp
circlingthesun/cloudclean
4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5
[ "MIT" ]
null
null
null
src/plugins/visualisenormals/visualisenormals.cpp
circlingthesun/cloudclean
4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5
[ "MIT" ]
4
2017-12-13T07:39:18.000Z
2021-05-29T13:13:48.000Z
#include "plugins/visualisenormals/visualisenormals.h" #include <QDebug> #include <QAction> #include <QMessageBox> #include <QGLShaderProgram> #include <QGLBuffer> #include <QApplication> #include <QResource> #include "model/cloudlist.h" #include "gui/glwidget.h" #include "gui/flatview.h" #include "gui/mainwindow.h" #include "utilities/pointpicker.h" #include "commands/select.h" #include "plugins/normalestimation/normalestimation.h" #include "pluginsystem/pluginmanager.h" #include "pluginsystem/core.h" QString VisualiseNormals::getName(){ return "Normal visualisation"; } void VisualiseNormals::initialize(Core *core){ core_= core; cl_ = core_->cl_; glwidget_ = core_->mw_->glwidget_; mw_ = core_->mw_; initialized_gl = false; } void VisualiseNormals::initialize2(PluginManager * pm) { ne_ = pm->findPlugin<NormalEstimator>(); if (ne_ == nullptr) { qDebug() << "Normal estimator plugin needed for normal viz"; return; } enable_ = new QAction("Visualise Normals", 0); enable_->setCheckable(true); enable_->setChecked(false); is_enabled_ = false; connect(enable_, SIGNAL(triggered()), this, SLOT(enable())); connect(this, SIGNAL(enabling()), core_, SIGNAL(endEdit())); mw_->addMenu(enable_, "View"); } void VisualiseNormals::cleanup(){ disconnect(this, SIGNAL(enabling()), core_, SIGNAL(endEdit())); disconnect(enable_, SIGNAL(triggered()), this, SLOT(enable())); unloadGLBuffers(); delete program_; } void VisualiseNormals::loadGLBuffers() { normal_buffers_.resize(cl_->clouds_.size(), nullptr); buffers_loaded_.resize(cl_->clouds_.size(), false); size_t point_size = 3*sizeof(float); for(uint i = 0; i < cl_->clouds_.size(); i++) { if(buffers_loaded_[i]) continue; QGLBuffer * buff = new QGLBuffer(); normal_buffers_[i] = buff; buff->create(); CE(); buff->bind(); CE(); buff->allocate(point_size*cl_->clouds_[i]->points.size()); CE(); float * gbuff = static_cast<float *>(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); CE(); pcl::PointCloud<pcl::Normal>::Ptr normals = ne_->getNormals(cl_->clouds_[i]); for(uint j = 0; j < cl_->clouds_[i]->points.size(); j++){ gbuff[3*j] = normals->at(j).data_n[0]; gbuff[3*j+1] = normals->at(j).data_n[1]; gbuff[3*j+2] = normals->at(j).data_n[2]; } glUnmapBuffer(GL_ARRAY_BUFFER); CE(); buff->release(); CE(); buffers_loaded_[i] = true; } } void VisualiseNormals::unloadGLBuffers() { for(uint i = 0; i < normal_buffers_.size(); i++) { if(!buffers_loaded_[i]) continue; delete normal_buffers_[i]; normal_buffers_[i] = nullptr; buffers_loaded_[i] = false; } } void VisualiseNormals::initializeGL() { if(initialized_gl) return; program_ = new QGLShaderProgram(); bool succ = program_->addShaderFromSourceFile( QGLShader::Vertex, ":/normals.vs.glsl"); CE(); qWarning() << program_->log(); if (!succ) qWarning() << "Shader compile log:" << program_->log(); succ = program_->addShaderFromSourceFile( QGLShader::Fragment, ":/normals.fs.glsl"); CE(); if (!succ) qWarning() << "Shader compile log:" << program_->log(); succ = program_->addShaderFromSourceFile( QGLShader::Geometry, ":/normals.gs.glsl"); CE(); if (!succ) qWarning() << "Shader compile log:" << program_->log(); succ = program_->link(); CE(); if (!succ) { qWarning() << "Could not link shader program_:" << program_->log(); qWarning() << "Exiting..."; abort(); } glGenVertexArrays(1, &vao_); initialized_gl = true; } void VisualiseNormals::paint(const Eigen::Affine3f& proj, const Eigen::Affine3f& mv){ initializeGL(); loadGLBuffers(); program_->bind(); glUniformMatrix4fv(program_->uniformLocation("proj"), 1, GL_FALSE, glwidget_->camera_.projectionMatrix().data()); CE(); float col[3] = {0, 1, 0}; glUniform3fv(program_->uniformLocation("line_colour"), 1, col); CE(); glBindVertexArray(vao_); for(uint i = 0; i < cl_->clouds_.size(); i++){ boost::shared_ptr<PointCloud> pc = cl_->clouds_[i]; std::unique_ptr<QGLBuffer> & pb = glwidget_->gld()->cloudgldata_[pc]->point_buffer_; pb->bind(); glEnableVertexAttribArray(0); CE(); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float)*4, 0); CE(); pb->release(); normal_buffers_[i]->bind(); glEnableVertexAttribArray(1); CE(); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, 0); CE(); normal_buffers_[i]->release(); glUniformMatrix4fv(program_->uniformLocation("mv"), 1, GL_FALSE, (glwidget_->camera_.modelviewMatrix() * pc->modelview()).data());CE(); glDrawArrays(GL_POINTS, 0, cl_->clouds_[i]->size()); CE(); } glBindVertexArray(0); program_->release(); } void VisualiseNormals::enable() { if(is_enabled_){ disable(); return; } bool ready = true; for(uint i = 0; i < cl_->clouds_.size(); i++) { if(!ne_->normalsAvailible(cl_->clouds_[i])) ready = false; } if(!ready) { int ret = QMessageBox::warning(nullptr, tr("Normals"), tr("Normals are not ready. Would you like to wait"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if(ret == QMessageBox::No){ enable_->setChecked(false); return; } } QTabWidget * tabs = qobject_cast<QTabWidget *>(glwidget_->parent()->parent()); tabs->setCurrentWidget(glwidget_); enable_->setChecked(true); emit enabling(); connect(glwidget_, SIGNAL(pluginPaint(Eigen::Affine3f, Eigen::Affine3f)), this, SLOT(paint(Eigen::Affine3f, Eigen::Affine3f)), Qt::DirectConnection); connect(core_, SIGNAL(endEdit()), this, SLOT(disable())); is_enabled_ = true; } void VisualiseNormals::disable() { unloadGLBuffers(); // TODO: Does this work? Might need to set context enable_->setChecked(false); disconnect(core_, SIGNAL(endEdit()), this, SLOT(disable())); disconnect(glwidget_, SIGNAL(pluginPaint(Eigen::Affine3f, Eigen::Affine3f)), this, SLOT(paint(Eigen::Affine3f, Eigen::Affine3f))); is_enabled_ = false; } Q_PLUGIN_METADATA(IID "za.co.circlingthesun.cloudclean.iplugin")
31.116822
97
0.612554
[ "geometry", "model" ]
e2e07d680cde190d5cca96c4c65d37f77cf57a1e
5,031
cpp
C++
kratos/mpi/utilities/data_communicator_factory.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
kratos/mpi/utilities/data_communicator_factory.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
kratos/mpi/utilities/data_communicator_factory.cpp
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main author: Jordi Cotela // #include "data_communicator_factory.h" #include "mpi.h" #include "includes/parallel_environment.h" #include "mpi/includes/mpi_data_communicator.h" namespace Kratos { namespace DataCommunicatorFactory { const DataCommunicator& DuplicateAndRegister( const DataCommunicator& rOriginalCommunicator, const std::string& rNewCommunicatorName) { MPI_Comm origin_mpi_comm = MPIDataCommunicator::GetMPICommunicator(rOriginalCommunicator); MPI_Comm duplicate_comm; MPI_Comm_dup(origin_mpi_comm, &duplicate_comm); ParallelEnvironment::RegisterDataCommunicator( rNewCommunicatorName, MPIDataCommunicator::Create(duplicate_comm), ParallelEnvironment::DoNotMakeDefault); return ParallelEnvironment::GetDataCommunicator(rNewCommunicatorName); } const DataCommunicator& SplitAndRegister( const DataCommunicator& rOriginalCommunicator, int Color, int Key, const std::string& rNewCommunicatorName) { MPI_Comm origin_mpi_comm = MPIDataCommunicator::GetMPICommunicator(rOriginalCommunicator); MPI_Comm split_mpi_comm; MPI_Comm_split(origin_mpi_comm, Color, Key, &split_mpi_comm); ParallelEnvironment::RegisterDataCommunicator( rNewCommunicatorName, MPIDataCommunicator::Create(split_mpi_comm), ParallelEnvironment::DoNotMakeDefault); return ParallelEnvironment::GetDataCommunicator(rNewCommunicatorName); } const DataCommunicator& CreateFromRanksAndRegister( const DataCommunicator& rOriginalCommunicator, const std::vector<int>& rRanks, const std::string& rNewCommunicatorName) { MPI_Comm origin_mpi_comm = MPIDataCommunicator::GetMPICommunicator(rOriginalCommunicator); MPI_Group all_ranks, selected_ranks; MPI_Comm_group(origin_mpi_comm, &all_ranks); MPI_Group_incl(all_ranks, rRanks.size(), rRanks.data(), &selected_ranks); MPI_Comm comm_from_ranks; int tag = 0; MPI_Comm_create_group(origin_mpi_comm, selected_ranks, tag, &comm_from_ranks); MPI_Group_free(&all_ranks); MPI_Group_free(&selected_ranks); ParallelEnvironment::RegisterDataCommunicator( rNewCommunicatorName, MPIDataCommunicator::Create(comm_from_ranks), ParallelEnvironment::DoNotMakeDefault); return ParallelEnvironment::GetDataCommunicator(rNewCommunicatorName); } const DataCommunicator& CreateUnionAndRegister( const DataCommunicator& rFirstDataCommunicator, const DataCommunicator& rSecondDataCommunicator, const DataCommunicator& rParentDataCommunicator, const std::string& rNewCommunicatorName) { MPI_Comm parent_comm = MPIDataCommunicator::GetMPICommunicator(rParentDataCommunicator); MPI_Comm first_mpi_comm = MPIDataCommunicator::GetMPICommunicator(rFirstDataCommunicator); MPI_Comm second_mpi_comm = MPIDataCommunicator::GetMPICommunicator(rSecondDataCommunicator); MPI_Comm combined_mpi_comm; constexpr int key = 0; // With key = 0 we are preserving the rank ordering on the new communicator if ( (first_mpi_comm != MPI_COMM_NULL) || (second_mpi_comm != MPI_COMM_NULL) ) { constexpr int color = 0; MPI_Comm_split(parent_comm, color, key, &combined_mpi_comm); } else { MPI_Comm_split(parent_comm, MPI_UNDEFINED, key, &combined_mpi_comm); } ParallelEnvironment::RegisterDataCommunicator( rNewCommunicatorName, MPIDataCommunicator::Create(combined_mpi_comm), ParallelEnvironment::DoNotMakeDefault); return ParallelEnvironment::GetDataCommunicator(rNewCommunicatorName); } const DataCommunicator& CreateIntersectionAndRegister( const DataCommunicator& rFirstDataCommunicator, const DataCommunicator& rSecondDataCommunicator, const DataCommunicator& rParentDataCommunicator, const std::string& rNewCommunicatorName) { MPI_Comm parent_comm = MPIDataCommunicator::GetMPICommunicator(rParentDataCommunicator); MPI_Comm first_mpi_comm = MPIDataCommunicator::GetMPICommunicator(rFirstDataCommunicator); MPI_Comm second_mpi_comm = MPIDataCommunicator::GetMPICommunicator(rSecondDataCommunicator); MPI_Comm combined_mpi_comm; constexpr int key = 0; // With key = 0 we are preserving the rank ordering on the new communicator if ( (first_mpi_comm != MPI_COMM_NULL) && (second_mpi_comm != MPI_COMM_NULL) ) { constexpr int color = 0; MPI_Comm_split(parent_comm, color, key, &combined_mpi_comm); } else { MPI_Comm_split(parent_comm, MPI_UNDEFINED, key, &combined_mpi_comm); } ParallelEnvironment::RegisterDataCommunicator( rNewCommunicatorName, MPIDataCommunicator::Create(combined_mpi_comm), ParallelEnvironment::DoNotMakeDefault); return ParallelEnvironment::GetDataCommunicator(rNewCommunicatorName); } } }
38.40458
117
0.758497
[ "vector" ]
e2e339d1ec223accfed14e1592cfed5d5d347773
5,478
cpp
C++
TAO/tests/Bug_3276_Regression/Manager.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tests/Bug_3276_Regression/Manager.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tests/Bug_3276_Regression/Manager.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
//$Id: Manager.cpp 91825 2010-09-17 09:10:22Z johnnyw $ #include "ace/SString.h" #include "Manager.h" #include "test_i.h" #include "ace/Get_Opt.h" #include "ace/OS_NS_stdio.h" const ACE_TCHAR *control_ior = 0; const ACE_TCHAR *proxy_ior = 0; int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("c:p:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'c': control_ior = get_opts.opt_arg (); break; case 'p': proxy_ior = get_opts.opt_arg (); break; } // Indicates successful parsing of the command line return 0; } int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { try { Manager manager; // Initilaize the ORB, POA etc. manager.init (argc, argv); if (parse_args (argc, argv) == -1) return -1; manager.activate_servant (); CORBA::ORB_var orb = manager.orb (); CORBA::Object_var server_ref = manager.server (); CORBA::String_var ior = orb->object_to_string (server_ref.in ()); FILE *output_file = 0; if (proxy_ior != 0) { ACE_DEBUG ((LM_DEBUG, "Writing the servant locator object ref out to file %s\n", proxy_ior)); output_file = ACE_OS::fopen (proxy_ior, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", proxy_ior), 1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); } // this is only to shutdown the manager afterwards Simple_Server_i server_impl (orb.in ()); Simple_Server_var server = server_impl._this (); ior = orb->object_to_string (server.in ()); ACE_DEBUG ((LM_DEBUG, "Activated as <%C>\n", ior.in ())); // If the proxy_ior exists, output the ior to it if (control_ior != 0) { ACE_DEBUG ((LM_DEBUG, "Writing the root poa servant server IOR out to file %s\n", control_ior)); output_file = ACE_OS::fopen (control_ior, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", control_ior), 1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); } manager.run (); } catch (const CORBA::Exception & ex) { ex._tao_print_exception ("Exception caught in manager:"); return -1; } return 0; } Manager::Manager (void) : orb_ (0), new_poa_var_ (0) { //no-op } Manager::~Manager (void) { this->orb_->destroy (); } CORBA::ORB_ptr Manager::orb (void) { return CORBA::ORB::_duplicate (this->orb_.in ()); } CORBA::Object_ptr Manager::server (void) { return CORBA::Object::_duplicate (this->server_.in ()); } int Manager::init (int argc, ACE_TCHAR *argv[]) { this->orb_ = CORBA::ORB_init (argc, argv); // Obtain the RootPOA. CORBA::Object_var obj_var = this->orb_->resolve_initial_references ("RootPOA"); // Get the POA_var object from Object_var. PortableServer::POA_var root_poa_var = PortableServer::POA::_narrow (obj_var.in ()); // Get the POAManager of the RootPOA. PortableServer::POAManager_var poa_manager_var = root_poa_var->the_POAManager (); poa_manager_var->activate (); // Policies for the childPOA to be created. CORBA::PolicyList policies (4); policies.length (4); // The next two policies are common to both // Id Assignment Policy policies[0] = root_poa_var->create_id_assignment_policy (PortableServer::USER_ID); // Lifespan policy policies[1] = root_poa_var->create_lifespan_policy (PortableServer::PERSISTENT); // Tell the POA to use a servant manager policies[2] = root_poa_var->create_request_processing_policy (PortableServer::USE_SERVANT_MANAGER); // Servant Retention Policy -> Use a locator policies[3] = root_poa_var->create_servant_retention_policy (PortableServer::NON_RETAIN); ACE_CString name = "newPOA"; this->new_poa_var_ = root_poa_var->create_POA (name.c_str (), poa_manager_var.in (), policies); // Creation of childPOAs is over. Destroy the Policy objects. for (CORBA::ULong i = 0; i < policies.length (); ++i) { CORBA::Policy_ptr policy = policies[i]; policy->destroy (); } return 0; } int Manager::activate_servant () { Servant_Locator *tmp = 0; ACE_NEW_THROW_EX (tmp, Servant_Locator, CORBA::NO_MEMORY ()); this->servant_locator_ = tmp; // Set ServantLocator object as the servant Manager of // secondPOA. this->new_poa_var_->set_servant_manager (this->servant_locator_.in ()); // Try to create a reference with user created ID in new_poa // which uses ServantLocator. PortableServer::ObjectId_var oid_var = PortableServer::string_to_ObjectId ("Simple_Server"); this->server_ = new_poa_var_->create_reference_with_id (oid_var.in (), "IDL:Simple_Server:1.0"); return 0; } int Manager::run () { this->orb_->run (); return 0; }
24.346667
89
0.592369
[ "object" ]
e2e51ad22a5293b4f2d6a63d13e8f8709ee94655
40,066
cc
C++
simlib/src/calendar.cc
MichalCab/IMS
d45dd8e7c0f794b4ee7f2ce1ccbc45edeaaa106e
[ "MIT" ]
null
null
null
simlib/src/calendar.cc
MichalCab/IMS
d45dd8e7c0f794b4ee7f2ce1ccbc45edeaaa106e
[ "MIT" ]
null
null
null
simlib/src/calendar.cc
MichalCab/IMS
d45dd8e7c0f794b4ee7f2ce1ccbc45edeaaa106e
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// //! \file calendar.cc Calendar queue implementation // // Copyright (c) 1991-2008 Petr Peringer // // This library is licensed under GNU Library GPL. See the file COPYING. // // implementation of class CalendarList // <br> interface is static - using global functions in SQS namespace // // <br> uses double-linked list and dynamic calendar queue [brown1988] // //TODO: reference-counting entities //////////////////////////////////////////////////////////////////////////// // interface // #include "simlib.h" #include "internal.h" #include <cmath> #include <cstring> //#define MEASURE // comment this to switch off #ifdef MEASURE // this is for measuring performance of operations only namespace { #include "rdtsc.h" // RDTSC instruction on i586+ static unsigned long long T_MEASURE; inline void START_T() { T_MEASURE = rdtsc(); } inline double STOP_T() { T_MEASURE = rdtsc() - T_MEASURE; // here can be unit conversion code // iuse CPU clocks for now return (double)T_MEASURE; } enum { OP_RESIZE=1, OP_ESTIMATE=2, OP_SWITCH2CQ=4, OP_SWITCH2LIST=8, }; int OP_MEASURE = 0; } // local namespace #endif //////////////////////////////////////////////////////////////////////////// // implementation // namespace simlib3 { SIMLIB_IMPLEMENTATION; /// common interface for all calendar (PES) implementations class Calendar { // abstract base class public: bool Empty() const { return _size == 0; } unsigned Size() const { return _size; } /// enqueue virtual void ScheduleAt(Entity *e, double t) = 0; /// dequeue first virtual Entity * GetFirst() = 0; /// dequeue virtual Entity * Get(Entity *e) = 0; /// remove all scheduled entities virtual void clear(bool destroy_entities=false) = 0; #ifndef NDEBUG /// for debugging only virtual void debug_print() = 0; // print the calendar contents #endif /// time of activation of first item double MinTime() const { return mintime; } protected: /// set cache for faster access void SetMinTime(double t) { mintime=t; } /////////////////////////////////////////////////////////////////////////// // data protected: unsigned _size; //!< number of scheduled items private: double mintime; //!< activation time of first event /////////////////////////////////////////////////////////////////////////// // singleton: public: static Calendar * instance(); //!< create/get single instance (singleton) protected: Calendar(): _size(0), mintime(SIMLIB_MAXTIME) {} virtual ~Calendar() {} //!< clear is called in derived class dtr static void delete_instance(); //!< destroy single instance private: static Calendar * _instance; //!< pointer to single instance /////////////////////////////////////////////////////////////////////////// friend void SetCalendar(const char *name); // uses _instance }; ///////////////////////////////////////////////////////////////////////////// /// calendar item - PRIVATE for any implementation /// <br> we use double-linked circular list struct EventNoticeLinkBase { // base class with list pointers only // used as list head in CalendarList and as part of list items EventNoticeLinkBase * pred; //!< previous object in list EventNoticeLinkBase * succ; //!< next object in list EventNoticeLinkBase() : pred(this), succ(this) {} /// remove from calendar list void remove() { pred->succ = succ; succ->pred = pred; pred = succ = this; // NOT linked } /// insert at position p void insert(EventNoticeLinkBase * p) { // todo: move this test (it is not needed always) if(pred != this) remove(); // is in calendar, remove first // --- insert before item s succ = p; pred = p->pred; pred->succ = this; p->pred = this; } }; /// activation record struct EventNotice : public EventNoticeLinkBase { /// which entity is scheduled Entity * entity; /// activation time of entity double time; /// priority at the time of scheduling Entity::Priority_t priority; EventNotice(Entity *p, double t) : //inherited: pred(this), succ(this), // == NOT linked entity(p), // which entity time(t), // activation time priority(p->Priority) // current scheduling priority { create_reverse_link(); } /// create link from entity to activation record void create_reverse_link() { entity->_evn = this; // reverse link to this activation record } /// delete link from entity to activation record void delete_reverse_link() { entity->_evn = 0; // unlink reverse link } ~EventNotice() { if(pred != this) { remove(); // remove from calendar delete_reverse_link(); } } /// set new values to existing (unlinked) record void Set(Entity *e, double t) { pred=succ=this; entity = e; // which entity time = t; // activation time priority = e->Priority; // current scheduling priority create_reverse_link(); } static EventNotice *Create(Entity *p, double t); static void Destroy(EventNotice *en); private: EventNotice(const EventNotice&); // disable EventNotice &operator=(const EventNotice&); }; // TODO: update interface to be compatible with std:: allocators /// allocate activation records fast // TODO: use std::list class EventNoticeAllocator { static const unsigned MAXSIZELIMIT = 1000000; EventNoticeLinkBase *l; // single-linked list of freed items unsigned freed; public: EventNoticeAllocator(): l(0), freed(0) {} ~EventNoticeAllocator() { clear(); // delete freelist } /// free EventNotice, add to freelist for future allocation void free(EventNotice *en) { if(en->pred!=en) { // if scheduled en->remove(); // unlink from calendar list en->delete_reverse_link(); } if(freed>MAXSIZELIMIT) // limit the size of freelist delete en; else { // add to freelist en->succ=l; l=en; freed++; } } /// EventNotice allocation or reuse from freelist EventNotice *alloc(Entity *p, double t) { if(l==0) return new EventNotice(p, t); else { // get from freelist freed--; EventNotice *ptr = static_cast<EventNotice *>(l); l = l->succ; ptr->Set(p,t); return ptr; } } /// clear: delete all free-list items void clear() { while(l!=0) { EventNotice *p = static_cast<EventNotice*>(l); l=l->succ; delete p; } } } allocator; // global allocator TODO: improve -> singleton //////////////////////////////////////////////////////////////////////////// /// class CalendarListImplementation --- sorted list // +-----------------------------------------------------+ // | +---+ +---+ +---+ | // +-->| |<-- ............ -->| |<---->| |<--+ // +--+---+---------------------+ +---+ +---+ // | CalendarListImplementation | |EvN| |EvN| // +----------------------------+ +---+ +---+ // double-linked circular list (should be faster than std::list) // items sorted by: 1) time // 2) priority // 3) FIFO // // no checking // class CalendarListImplementation { EventNoticeLinkBase l; //!< head of circular list public: class iterator { //!< bidirectional iterator EventNoticeLinkBase *p; public: iterator(EventNoticeLinkBase *pos) : p(pos) {} // prefix version only iterator &operator++() { p = p->succ; return *this; } iterator &operator--() { p = p->pred; return *this; } // implicit operator= and copy constructor are OK EventNotice * operator*() { // access to activation record return static_cast<EventNotice *>(p); } bool operator != (iterator q) { return p!=q.p; } bool operator == (iterator q) { return p==q.p; } }; // iterator iterator begin() { return l.succ; } iterator end() { return &l; } bool empty() { return begin() == end(); } /////////////////////////////////////////////////////////// double first_time() { return (*begin())->time; } EventNotice *first() { return *begin(); } private: /// search --- linear search for insert position iterator search(EventNotice *en) { if(empty()) return end(); double t = en->time; iterator evn = --end(); // search from back while(evn!=end() && (*evn)->time > t) { // search time --evn; } Entity::Priority_t prio = en->priority; while(evn!=end() && (*evn)->time==t && // equal time... (*evn)->priority < prio) { // ...search priority --evn; } ++evn; return evn; // return insert position or end() } public: /// enqueue operation void insert(Entity *e, double t) { EventNotice *evn = EventNotice::Create(e,t); iterator pos = search(evn); evn->insert(*pos); // insert before pos } /// special dequeue operation for rescheduling Entity *remove(Entity *e) { EventNotice::Destroy(e->GetEventNotice()); // disconnect, remove item return e; } /// dequeue operation Entity *remove_first() { Entity *e = first()->entity; EventNotice::Destroy(first()); // disconnect, remove item return e; } CalendarListImplementation() { } /// remove all items /// @param destroy deallocates entities if true void clear(bool destroy) { while (!empty()) { Entity *e = remove_first(); if (destroy && e->isAllocated()) delete e; // delete entity } } ~ CalendarListImplementation() { clear(true); allocator.clear(); // clear freelist } #ifndef NDEBUG /// print of calendar contents - FOR DEBUGGING ONLY void debug_print(); #endif /// fast special operations for list swap (Dangerous!): EventNotice *extract_first() { EventNotice *en = first(); en->remove(); // disconnect only, no other changes return en; } /// fast special enqueue operation void insert_extracted(EventNotice *evn) { iterator pos = search(evn); evn->insert(*pos); // insert before pos } }; //////////////////////////////////////////////////////////////////////////// /// class CalendarList --- list implementation of calendar // class CalendarList : public Calendar { CalendarListImplementation l; public: /// enqueue virtual void ScheduleAt(Entity *p, double t); /// dequeue virtual Entity *Get(Entity *p); // remove process p from calendar /// dequeue first entity virtual Entity *GetFirst(); /// remove all virtual void clear(bool destroy=false); // remove/destroy all items /// create calendar instance // TODO: we need this only if calendar use is allowed before Init() static CalendarList * create() { // create instance Dprintf(("CalendarList::create()")); CalendarList *l = new CalendarList; SIMLIB_atexit(delete_instance); // last SIMLIB module cleanup calls it //else SIMLIB_error(DuplicateCalendar); return l; } virtual const char* Name() { return "CalendarList"; } private: CalendarList() { Dprintf(("CalendarList::CalendarList()")); SetMinTime( SIMLIB_MAXTIME ); // empty } ~CalendarList() { Dprintf(("CalendarList::~CalendarList()")); clear(true); } public: #ifndef NDEBUG virtual void debug_print(); // print of calendar contents - FOR DEBUGGING ONLY #endif }; //////////////////////////////////////////////////////////////////////////// // CalendarList implementation // //////////////////////////////////////////////////////////////////////////// /// creates new EventNotice, inline EventNotice *EventNotice::Create(Entity *e, double t) { register EventNotice *evn = e->GetEventNotice(); if(evn) { // Entity is scheduled already --- REUSE EventNotice evn->remove(); // remove from calendar list, should stay connected evn->time = t; // change activation time evn->priority = e->Priority; // use current scheduling priority // Dprintf(("EventNotice::Create(entity=%p, time=%g, [priority=%d]): %p [RECYCLED]", // evn->entity, evn->time, evn->priority, this)); } else { evn = allocator.alloc(e,t); // Dprintf(("EventNotice::Create(entity=%p, time=%g, [priority=%d]): %p [NEW]", // evn->entity, evn->time, evn->priority, this)); } return evn; } //////////////////////////////////////////////////////////////////////////// /// delete EventNotice, if inserted in calendar remove it first // inline void EventNotice::Destroy(EventNotice *en) { allocator.free(en); // disconnect, remove item } //////////////////////////////////////////////////////////////////////////// /// schedule entity e at time t void CalendarList::ScheduleAt(Entity *e, double t) { // Dprintf(("CalendarList::ScheduleAt(%s,%g)", e->Name(), t)); if(t<Time) SIMLIB_error(SchedulingBeforeTime); l.insert(e,t); ++_size; // update mintime: if(t < MinTime()) SetMinTime(l.first_time()); } //////////////////////////////////////////////////////////////////////////// /// delete first entity Entity *CalendarList::GetFirst() { // Dprintf(("CalendarList::GetFirst(): size=%u", Size())); if(Empty()) SIMLIB_error(EmptyCalendar); Entity *e = l.remove_first(); --_size; if(Empty()) SetMinTime(SIMLIB_MAXTIME); else SetMinTime(l.first_time()); return e; } //////////////////////////////////////////////////////////////////////////// /// remove entity e from calendar Entity * CalendarList::Get(Entity * e) { // Dprintf(("CalendarList::Get(e=%s): size=%u",e->Name(), Size())); if(Empty()) SIMLIB_error(EmptyCalendar); // internal --> TODO:remove if(e->Idle()) SIMLIB_error(EntityIsNotScheduled); l.remove(e); --_size; if(Empty()) SetMinTime(SIMLIB_MAXTIME); else SetMinTime(l.first_time()); return e; } //////////////////////////////////////////////////////////////////////////// /// remove all event notices, and optionally destroy them // //TODO analyze possible problems // void CalendarList::clear(bool destroy) { Dprintf(("CalendarList::clear(%s)", destroy?"true":"false")); l.clear(destroy); _size = 0; SetMinTime(SIMLIB_MAXTIME); } ///////////////////////////////////////////////////////////////////////////// // CalendarQueue tunable parameters: // when to switch from list to calendar queue const unsigned LIST_MAX = 512; // TODO:tune parameter: 64-1024 const unsigned MINBUCKETS = LIST_MAX>4?LIST_MAX:4; // should be power of 2 and >=4 const unsigned LIST_MIN = LIST_MAX/2; // TODO:tune parameter // average bucket list length const double COEF_PAR = 1.5; // TODO:tune parameter: cca 1.5 // bucket width = MUL_PAR * average delta t const double MUL_PAR = 1.0; // TODO:tune parameter: 1.0--5.0 //////////////////////////////////////////////////////////////////////////// /// CQ implementation of calendar class CalendarQueue : public Calendar { typedef CalendarListImplementation BucketList; BucketList *buckets; // bucket array BucketList list; // list for small number of items unsigned nbuckets; // current number of buckets unsigned hi_bucket_mark; // high bucket threshold for resize unsigned low_bucket_mark; // low bucket threshold for resize unsigned nextbucket; // next bucket to check for first item unsigned numop; // number of operations performed from last tuning double bucket_width; // parameter: width of each bucket double buckettop; // top time of current bucket double last_dequeue_time; // for deleta computation double sumdelta; // sum for bucket_width estimation unsigned ndelta; // count private: bool list_impl() { return buckets==NULL; } /// Convert time to bucket number inline int time2bucket (double t) { return static_cast<int>(fmod(t/bucket_width, static_cast<double>(nbuckets))); } /// Compute bucket top limit // the *1.5 is good for bucket number >= 3 // XXXX++++++--XXXX X = time can be in bucket 1 // 1111222233331111 inline double time2bucket_top(double t) { return t + 1.5*bucket_width; } double estimate_bucket_width(); void switchtocq(); void switchtolist(); public: /// enqueue virtual void ScheduleAt(Entity *p, double t); /// dequeue virtual Entity *Get(Entity *p); // remove process p from calendar /// dequeue first virtual Entity *GetFirst(); /// remove all virtual void clear(bool destroy=false); // remove/destroy all items /// create calendar instance // TODO: we need this only if calendar use is allowed before Init() static CalendarQueue * create() { // create instance Dprintf(("CalendarQueue::create()")); CalendarQueue *l = new CalendarQueue; SIMLIB_atexit(delete_instance); // last SIMLIB module cleanup calls it //TODO:SIMLIB_error(DuplicateCalendar); return l; } virtual const char* Name() { return "CalendarQueue"; } private: CalendarQueue(); ~CalendarQueue(); void Resize(int grow=0); // grow/shrink operation void SearchMinTime(double starttime); // search for new minimum public: #ifndef NDEBUG virtual void debug_print(); // print of calendar contents - FOR DEBUGGING ONLY void visualize(const char *msg); #endif }; // CalendarQueue // TODO: tune this parameter #define MAX_OP (Size()/2) ///////////////////////////////////////////////////////////////////////////// /// Initialize calendar queue CalendarQueue::CalendarQueue(): buckets(0), // ptr to bucketarray nbuckets(0), // number of buckets hi_bucket_mark(0), // high bucket threshold low_bucket_mark(0), // low bucket threshold nextbucket(0), // next bucket to check numop(0), // number of operations from last tuning bucket_width(0.0), // width of each bucket buckettop(0.0), // high time limit of current bucket last_dequeue_time(-1.0), sumdelta(0.0), ndelta(0) // statistics { Dprintf(("CalendarQueue::CalendarQueue()")); SetMinTime( SIMLIB_MAXTIME ); // empty // init: Allocate initial buckets // Resize(); } /// schedule void CalendarQueue::ScheduleAt(Entity *e, double t) { Dprintf(("CalendarQueue::ScheduleAt(%s,%g)", e->Name(), t)); if(t<Time) SIMLIB_error(SchedulingBeforeTime); // if overgrown if(_size>LIST_MAX && list_impl()) switchtocq(); if(list_impl()) { // insert at right position list.insert(e,t); } else { // if too many items, resize bucket array if(_size + 1 > hi_bucket_mark) Resize(+1); if(++numop > MAX_OP) // tune each MAX_OP edit operations Resize(); // select bucket BucketList &bp = buckets[time2bucket(t)]; // insert at right position bp.insert(e,t); } ++_size; // update mintime if (MinTime() > t) { SetMinTime(t); } } //////////////////////////////////////////////////////////////////////////// /// dequeue Entity * CalendarQueue::GetFirst() { // Dprintf(("CalendarQueue::GetFirst()")); if(Empty()) SIMLIB_error(EmptyCalendar); if(_size<LIST_MIN && !list_impl()) switchtolist(); if(list_impl()) { Entity * e = list.remove_first(); // update size --_size; if(Empty()) SetMinTime(SIMLIB_MAXTIME); else SetMinTime(list.first_time()); return e; } // else // get statistics for tuning double min_time = MinTime(); if(last_dequeue_time >= 0.0) { double diff = min_time - last_dequeue_time; if(diff>0.0) { sumdelta += diff; ndelta++; } } last_dequeue_time=min_time; // select bucket nextbucket = time2bucket(min_time); // TODO: optimization BucketList & bp = buckets[nextbucket]; // get first item Entity * e = bp.remove_first(); // update size --_size; if (_size < low_bucket_mark) Resize(-1); if(++numop > MAX_OP) Resize(); // update mintime SearchMinTime(MinTime()); return e; } //////////////////////////////////////////////////////////////////////////// /// remove entity e from calendar /// <br>called only if rescheduling Entity * CalendarQueue::Get(Entity * e) { // Dprintf(("CalendarQueue::Get(e=%s)",e->Name())); if(Empty()) SIMLIB_error(EmptyCalendar); // internal use only --> TODO:remove if(e->Idle ()) SIMLIB_error(EntityIsNotScheduled); if(_size<LIST_MIN && !list_impl()) switchtolist(); if(list_impl()) { list.remove(e); // update size --_size; // update mintime if(Empty()) SetMinTime(SIMLIB_MAXTIME); else SetMinTime(list.first_time()); return e; } // else // TODO: Get statistics! double t = e->ActivationTime(); unsigned b = time2bucket(t); BucketList & bp = buckets[b]; bp.remove(e); // update size --_size; if (_size < low_bucket_mark) // should be resized Resize(-1); if(++numop > MAX_OP) Resize(); // update mintime if(t==MinTime()) // maybe first item removed - update mintime SearchMinTime(t); return e; } ///////////////////////////////////////////////////////////////////////////// /// compute new mintime // TODO: compute dequeue price here // void CalendarQueue::SearchMinTime (double starttime) { if(Empty()) { SetMinTime(SIMLIB_MAXTIME); return; } // search for minimum from starttime double tmpmin=SIMLIB_MAXTIME; // unsigned tmpnextbucket = 0; nextbucket = time2bucket(starttime); buckettop = time2bucket_top(starttime); // search buckets for (int n__ = nbuckets; n__ > 0; --n__) { // n__ is not used BucketList & bp = buckets[nextbucket]; if (!bp.empty()) { // check first item in bucket double t = bp.first_time(); if (t < buckettop) { // time is in this "year" // debug only -- TODO: leave out after tests if (t < starttime) SIMLIB_error("CalendarQueue implementation error in SearchMinTime"); // first item is OK SetMinTime(t); return; } // search minimum time of all buckets for fallback if (t < tmpmin) { tmpmin = t; // tmpnextbucket = nextbucket; } } // go to next bucket (modulo nbuckets) // TODO: can be optimized if nbuckets is power of 2 ++nextbucket; if (nextbucket == nbuckets) nextbucket = 0; buckettop += bucket_width; } // all buckets checked and none record found in current "year" // we use tmpmin // (happens when the queued times are sparse) SetMinTime(tmpmin); // nextbucket = tmpnextbucket; // buckettop = time2bucket_top (mintime); } ///////////////////////////////////////////////////////////////////////////// /// compute new bucket width --- EXPERIMENTAL // double CalendarQueue::estimate_bucket_width() { Dprintf(("Calendar bucket width estimation:")); #ifdef MEASURE OP_MEASURE |= OP_ESTIMATE; #endif if(ndelta>10 && sumdelta>0) { // do not use bad statistics double bu_width = MUL_PAR * sumdelta/ndelta; Dprintf((" estm1: %g", bu_width)); if(bu_width < 1e-12*MinTime()) SIMLIB_error("CalendarQueue:e1 bucketwidth < 1e-12*Time -- total loss of precision"); return bu_width; } // =========================== EXPERIMENTAL CODE ======================== // no past statistics - use future events const unsigned LIMIT = nbuckets>1000?1000:nbuckets; // limit # of intervals skipped (cca 1 "year") double last_time = MinTime(); unsigned count=0; // number of non-zero intervals for(int a__ = 0; a__<2; ++a__) { double tmpmin = SIMLIB_MAXTIME; unsigned next_bucket = time2bucket(last_time); double bucket_top = time2bucket_top(last_time); // search all buckets for (int n__ = nbuckets; n__ > 0; --n__) { // n__ is not used BucketList & bp = buckets[next_bucket]; // check items in bucket for(BucketList::iterator i=bp.begin(); i != bp.end(); ++i) { double t=(*i)->time; if (t > bucket_top||t < last_time) { // time is NOT in this "year" // search minimum time of next years if (t < tmpmin) tmpmin = t; break; } double diff = t - last_time; if(diff>0.0) { ++count; } last_time=t; if(count>LIMIT) break; } if(count>LIMIT) break; // go to next bucket (modulo nbuckets) // TODO: can be optimized if nbuckets is power of 2 ++next_bucket; if (next_bucket == nbuckets) next_bucket = 0; bucket_top += bucket_width; } if(count>10) { double avg = (last_time-MinTime())/count; Dprintf((" estm2: avg=%g", avg)); double bu_width = MUL_PAR * avg; if(bu_width < 1e-12*MinTime()) SIMLIB_error("CalendarQueue:e2 bucketwidth < 1e-12*Time -- total loss of precision"); return bu_width; } if(tmpmin < SIMLIB_MAXTIME) { Dprintf((" estm3: next tmpmin=%g", tmpmin)); last_time = tmpmin; continue; // scan next year } else break; } // for ================================================== // should (almost) never be reached // we have problem - bad calendar structure // TODO return 1.0; } ///////////////////////////////////////////////////////////////////////////// /// Resize bucket array // - parameter: // grow > 0 grow // grow == 0 update bucket_width, init // grow < 0 shrink // - does not change mintime ! // // PROBLEM: TODO: too high-cost for 512-256-128 resize down ! void CalendarQueue::Resize(int grow) // TODO: is it better to use target size? { // visualize("before Resize"); #ifdef MEASURE OP_MEASURE |= OP_RESIZE; #endif // first tune bucket_width bool bucket_width_changed = false; numop=0; // number of operations from last tuning/checking // test/change bucket_width double new_bucket_width = estimate_bucket_width(); // TODO: 1.3/0.7 -- this needs improvement if(new_bucket_width>1.3*bucket_width || new_bucket_width<0.7*bucket_width) { bucket_width = new_bucket_width; bucket_width_changed = true; } // save old contents unsigned oldnbuckets = nbuckets; BucketList *oldbuckets = buckets; // change nbuckets if (grow>0) nbuckets = oldnbuckets * 2; if (grow<0) nbuckets = oldnbuckets / 2; // check low limit if(nbuckets < MINBUCKETS) nbuckets = MINBUCKETS; // minimal number of buckets is 4 // TODO: switch to list if <LOWLIMIT // switch to calqueue if >HIGHLIMIT Dprintf(("Calendar resize: nbuckets=%d->%d", oldnbuckets, nbuckets)); // nbuckets is a power of 2 if(oldnbuckets == nbuckets && !bucket_width_changed) // no change return; // allocate new bucket array buckets = new BucketList[nbuckets]; // initialized by default constructors // TODO: search optimal PARAMETERS hi_bucket_mark = static_cast<unsigned>(nbuckets * COEF_PAR); // cca 1.5 TODO: benchmarking low_bucket_mark = (nbuckets / 2) - 2; // if initialization only, we can stop here if (oldbuckets == NULL) return; // move old contents into new bucket array _size = 0; for (unsigned n = 0; n < oldnbuckets; ++n) { BucketList &oldbp = oldbuckets[n]; while(!oldbp.empty()) { // extract EventNotice from old bucket EventNotice * en = oldbp.extract_first(); // no change of e,t,p // select new bucket BucketList &bp = buckets[time2bucket(en->time)]; // insert EventNotice at right position bp.insert_extracted(en); ++_size; } } delete [] oldbuckets; // all are empty } // Resize /// switch to list implementation void CalendarQueue::switchtolist() { // _size, _mintime does not change // assert (buckets != NULL); // assert list.empty() #ifdef MEASURE OP_MEASURE |= OP_SWITCH2LIST; #endif // fill list from CQ for (unsigned n = 0; n < nbuckets; ++n) { BucketList &oldbp = buckets[n]; while(!oldbp.empty()) { // extract EventNotice from old bucket EventNotice * en = oldbp.extract_first(); // no change of e,t,p // insert EventNotice at right position list.insert_extracted(en); // list is short } } delete [] buckets; // all are empty buckets = NULL; nbuckets = 0; // visualize("after switchtolist"); } // switch2list /// switch to calendar queue implementation void CalendarQueue::switchtocq() { // first some initialization: #ifdef MEASURE OP_MEASURE |= OP_SWITCH2CQ; #endif // _size does not change // MinTime unchanged // assert (buckets == NULL); // nit CQ statistics: last_dequeue_time = -1.0; sumdelta = 0.0; ndelta = 0; numop=0; // number of operations from last tuning/checking // compute bucket_width CalendarListImplementation::iterator i=list.begin(); double t0=(*i)->time; // mintime unsigned count = 0; for(unsigned n=0; i!=list.end() && n<100; ++i, ++n) { double t1=(*i)->time; if(t1==t0) continue; t0 = t1; ++count; } if(count > 5) { double avg = (t0-MinTime())/count; bucket_width = MUL_PAR * avg; } else bucket_width = 1.0; // TODO: ? // assert if(bucket_width < 1e-12*MinTime()) SIMLIB_warning("CalendarQueue:switchtocq bucketwidth<1e-12*Time = loss of precision"); // search for first power of 2 greater than size for(nbuckets=4; nbuckets<_size; nbuckets<<=1) { /*empty*/ } // assert: nbuckets is power of 2 // allocate new bucket array buckets = new BucketList[nbuckets]; // initialized by default constructors // TODO: search optimal PARAMETERS hi_bucket_mark = static_cast<unsigned>(nbuckets * COEF_PAR); // cca 1.5 TODO: benchmarking low_bucket_mark = (nbuckets / 2) - 2; // move list contents into new bucket array while(!list.empty()) { // extract EventNotice from list EventNotice * en = list.extract_first(); // no change of e,t,p // select new bucket BucketList &bp = buckets[time2bucket(en->time)]; // insert EventNotice at right position bp.insert_extracted(en); } // visualize("after switchtocq"); } // switch2cq ///////////////////////////////////////////////////////////////////////////// /// clear calendar queue // // DIFFERENCE from simple list implementation: // - order of entity destruction is different // void CalendarQueue::clear(bool destroy) { Dprintf(("CalendarQueue::clear(%s)",destroy?"true":"false")); // clear non-empty calendar if(!Empty()) { if(list_impl()) list.clear(destroy); else // empty all buckets for(unsigned i=0; i<nbuckets; i++) buckets[i].clear(destroy); _size = 0; } // delete bucketarray delete [] buckets; buckets = NULL; nbuckets = 0; // // re-initialize // statistics: last_dequeue_time = -1.0; sumdelta = 0.0; ndelta = 0; numop = 0; // for tuning // list implementation is active now. SetMinTime(SIMLIB_MAXTIME); } ///////////////////////////////////////////////////////////////////////////// /// Destroy calendar queue CalendarQueue::~CalendarQueue() { Dprintf(("CalendarQueue::~CalendarQueue()")); clear(true); allocator.clear(); // clear freelist } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// #ifndef NDEBUG //////////////////////////////////////////////////////////////////////////// void CalendarListImplementation::debug_print() // print of list contents { int n=0; for(iterator i = begin(); i!=end(); ++i) { Print(" [%03u]:", ++n ); // order Print("\t %s", (*i)->entity->Name() ); // print entity ID Print("\t at=%g", (*i)->time ); // schedule time Print("\n"); } if(n==0) Print(" <empty>\n"); } //////////////////////////////////////////////////////////////////////////// void CalendarList::debug_print() // print of calendar contents { Print("CalendarList:\n"); if(CalendarList::instance()==0) return; l.debug_print(); Print("\n"); } //////////////////////////////////////////////////////////////////////////// void CalendarQueue::debug_print() // print of calendar queue contents { Print("CalendarQueue:\n"); if(CalendarQueue::instance()==0) return; for(unsigned i=0; i<nbuckets; i++) { Print(" bucket#%03u:\n", i); buckets[i].debug_print(); Print("\n"); } Print("\n"); } //////////////////////////////////////////////////////////////////////////// /// CalendarQueue::visualize -- output suitable for Gnuplot void CalendarQueue::visualize(const char *msg) { Print("# CalendarQueue::visualize %s\n",msg); if(list_impl()) Print("# size=%u, mintime=%g (list)\n", Size(), MinTime()); else Print("# size=%u, nbuckets=%d, mintime=%g, operations=%u, bucket_width=%g\n", Size(), nbuckets, MinTime(), numop, bucket_width); if(Empty()) return; for(unsigned b=0; b<nbuckets; b++) { BucketList &bl = buckets[b]; unsigned cnt=0; Print("%d:", b ); for(BucketList::iterator i = bl.begin(); i!=bl.end(); ++i) { //Print("%g %d\n", (*i)->time, b ); // schedule time Print(" %g", (*i)->time ); // schedule time cnt++; } Print("\n"); //if(cnt>0) Print("#[%u].len = %u\n", b, cnt ); } Print("\n"); } //////////////////////////////////////////////////////////////////////////// #endif //////////////////////////////////////////////////////////////////////////// /// static pointer to singleton instance Calendar * Calendar::_instance = 0; /// interface to singleton instance inline Calendar * Calendar::instance() { if(_instance==0) { #if 1 // choose default _instance = CalendarList::create(); // create default calendar #else _instance = CalendarQueue::create(); // create default calendar #endif } return _instance; } /// destroy single instance void Calendar::delete_instance() { Dprintf(("Calendar::delete_instance()")); if(_instance) { delete _instance; // remove all, free _instance = 0; } } #if 0 class Calendars { typedef Calendar * (*create_fun_ptr_t)(); std::map<string, create_fun_ptr_t> record; Calendars() {} Register(create_fun_ptr_t f, const char *name) { string n(name); for(string::iterator i=n.begin(); i!=n.end(); ++i) *i = std::tolower(*i); record[n] = f; } Calendar *create(const char *name) { string n(name); for(string::iterator i=n.begin(); i!=n.end(); ++i) *i = std::tolower(*i); if(record.count(n)==0) // not present SIMLIB_error("Bad calendar type name"); create_fun_ptr_t f = record[n]; return f(); } }; #endif /// choose calendar implementation /// default is list void SetCalendar(const char *name) { if( SIMLIB_Phase == INITIALIZATION || SIMLIB_Phase == SIMULATION ) SIMLIB_error("SetCalendar() can't be used after Init()"); if(Calendar::_instance) // already initialized Calendar::delete_instance(); if(name==0 || std::strcmp(name,"")==0 || std::strcmp(name,"default")==0) Calendar::_instance = CalendarList::create(); else if(std::strcmp(name,"list")==0) Calendar::_instance = CalendarList::create(); else if(std::strcmp(name,"cq")==0) Calendar::_instance = CalendarQueue::create(); else SIMLIB_error("SetCalendar: bad argument"); } //////////////////////////////////////////////////////////////////////////// // public INTERFACE = exported functions... // #ifdef MEASURE // global measurement results (in simlib3 namespace) unsigned cal_cost_size; double cal_cost_time; int cal_cost_flag; const char * cal_cost_op; #endif /// empty calendar predicate bool SQS::Empty() { // used by Run() only return Calendar::instance()->Empty(); } /// schedule entity e at given time t using scheduling priority from e /// @param e entity /// @param t time of activation void SQS::ScheduleAt(Entity *e, double t) { // used by scheduling operations if(!e->Idle()) SIMLIB_error("ScheduleAt call if already scheduled"); #ifdef MEASURE START_T(); #endif Calendar::instance()->ScheduleAt(e,t); #ifdef MEASURE double ttt=STOP_T(); // Print("enqueue %d %g %d\n", Calendar::instance()->size(), ttt, OP_MEASURE); cal_cost_size = Calendar::instance()->Size(); cal_cost_time = ttt; cal_cost_flag = OP_MEASURE; cal_cost_op = "enqueue"; OP_MEASURE=0; // if(Calendar::instance()->size() < 300) Calendar::instance()->visualize(""); #endif _SetTime(NextTime, Calendar::instance()->MinTime()); } /// remove selected entity activation record from calendar void SQS::Get(Entity *e) { // used by Run() only #ifdef MEASURE START_T(); #endif Calendar::instance()->Get(e); #ifdef MEASURE double ttt=STOP_T(); // Print("dequeue2 %d %g %d\n", Calendar::instance()->size(), ttt, OP_MEASURE); cal_cost_size = Calendar::instance()->Size(); cal_cost_time = ttt; cal_cost_flag = OP_MEASURE; cal_cost_op = "delete"; OP_MEASURE=0; #endif _SetTime(NextTime, Calendar::instance()->MinTime()); } /// remove entity with minimum activation time /// @returns pointer to entity Entity *SQS::GetFirst() { // used by Run() #ifdef MEASURE START_T(); #endif Entity * ret = Calendar::instance()->GetFirst(); #ifdef MEASURE double ttt=STOP_T(); // Print("dequeue %d %g %d\n", Calendar::instance()->size(), ttt, OP_MEASURE); cal_cost_size = Calendar::instance()->Size(); cal_cost_time = ttt; cal_cost_flag = OP_MEASURE; cal_cost_op = "dequeue"; OP_MEASURE=0; #endif _SetTime(NextTime, Calendar::instance()->MinTime()); return ret; } /// remove all scheduled entities void SQS::Clear() { // remove all Calendar::instance()->clear(true); _SetTime(NextTime, Calendar::instance()->MinTime()); } int SQS::debug_print() { // for debugging only Calendar::instance()->debug_print(); return Calendar::instance()->Size(); } /// get activation time of entity - iff scheduled <br> /// it is here, because Entity has no knowledge of calendar activation record structure double Entity::ActivationTime() { // activation time //if(Idle()) SIMLIB_internal_error(); // passive entity if(Idle()) return SIMLIB_MAXTIME; // passive entity return GetEventNotice()->time; } } // end of namespace
29.460294
101
0.562122
[ "object" ]
e2e6b34c2c11a75f99871a31821820875f9927d3
8,640
cpp
C++
SharedCode/scenes/SplayFingers2Scene.cpp
jing-interactive/digital_art_2014
736ce10ea3fa92b415c57fa5a1a41a64e6d98622
[ "MIT" ]
1
2019-10-10T12:23:21.000Z
2019-10-10T12:23:21.000Z
SharedCode/scenes/SplayFingers2Scene.cpp
jing-interactive/digital_art_2014
736ce10ea3fa92b415c57fa5a1a41a64e6d98622
[ "MIT" ]
null
null
null
SharedCode/scenes/SplayFingers2Scene.cpp
jing-interactive/digital_art_2014
736ce10ea3fa92b415c57fa5a1a41a64e6d98622
[ "MIT" ]
3
2019-05-02T11:20:41.000Z
2021-07-26T16:38:38.000Z
#pragma once #include "SplayFingers2Scene.h" SplayFingers2Scene::SplayFingers2Scene(ofxPuppet* puppet, HandWithFingertipsSkeleton* handWithFingertipsSkeleton, HandWithFingertipsSkeleton* immutableHandWithFingertipsSkeleton) { Scene::Scene(); Scene::setup("Splay Fingers 2", "Splay Fingers 2 (Hand With Fingertips)", puppet, (Skeleton*)handWithFingertipsSkeleton, (Skeleton*)immutableHandWithFingertipsSkeleton); this->maxPalmAngleLeft = 60; this->maxPalmAngleRight = -60; this->maxBaseAngleLeft = 20; this->maxBaseAngleRight = -20; this->splayAxis = 192; this->maxAngle = 50; this->averageAngleOffset = 0; } //================================================================= void SplayFingers2Scene::setupGui() { SplayFingers2Scene::initializeGui(); this->gui->addSlider("Max Angle", 0, 90, &maxAngle); this->gui->addSpacer(); this->gui->autoSizeToFitWidgets(); } //================================================================= void SplayFingers2Scene::setupMouseGui() { SplayFingers2Scene::initializeMouseGui(); vector<string> mouseOptions; mouseOptions.push_back("Palm Position"); mouseOptions.push_back("Palm Rotation"); mouseOptions.push_back("Finger Base Rotation"); this->mouseRadio = this->mouseGui->addRadio("Mouse Control Options", mouseOptions); this->mouseRadio->getToggles()[0]->setValue(true); this->mouseGui->addSpacer(); this->mouseGui->autoSizeToFitWidgets(); } //================================================================= void SplayFingers2Scene::update() { HandWithFingertipsSkeleton* handWithFingertipsSkeleton = (HandWithFingertipsSkeleton*)this->skeleton; int palm = HandWithFingertipsSkeleton::PALM; ofVec2f palmPos = handWithFingertipsSkeleton->getPositionAbsolute(palm); int tip[] = {HandWithFingertipsSkeleton::PINKY_TIP, HandWithFingertipsSkeleton::RING_TIP, HandWithFingertipsSkeleton::MIDDLE_TIP, HandWithFingertipsSkeleton::INDEX_TIP, HandWithFingertipsSkeleton::THUMB_TIP}; int top[] = {HandWithFingertipsSkeleton::PINKY_TOP, HandWithFingertipsSkeleton::RING_TOP, HandWithFingertipsSkeleton::MIDDLE_TOP, HandWithFingertipsSkeleton::INDEX_TOP, HandWithFingertipsSkeleton::THUMB_TOP}; int mid[] = {HandWithFingertipsSkeleton::PINKY_MID, HandWithFingertipsSkeleton::RING_MID, HandWithFingertipsSkeleton::MIDDLE_MID, HandWithFingertipsSkeleton::INDEX_MID, HandWithFingertipsSkeleton::THUMB_MID}; int base[] = { HandWithFingertipsSkeleton::PINKY_BASE, HandWithFingertipsSkeleton::RING_BASE, HandWithFingertipsSkeleton::MIDDLE_BASE, HandWithFingertipsSkeleton::INDEX_BASE, HandWithFingertipsSkeleton::THUMB_BASE}; // have the angle offset based on a running average, for stability float angleOffset = ofMap (palmPos.x, 256,440, 1,0); angleOffset = ofClamp (angleOffset, 0,1); angleOffset = maxAngle * powf (angleOffset, 0.75); averageAngleOffset = 0.94*averageAngleOffset + 0.06* angleOffset; int fingerCount = 5; for (int i=0; i < fingerCount; i++) { int joints[] = {base[i], mid[i], top[i], tip[i]}; float angleOffsetToUse = averageAngleOffset; ofVec2f basePos = handWithFingertipsSkeleton->getPositionAbsolute(joints[0]); bool bDoThumb = (fingerCount > 4); if (bDoThumb && (i == 4)){ basePos = handWithFingertipsSkeleton->getPositionAbsolute(joints[1]); } ofVec2f positions[] = { handWithFingertipsSkeleton->getPositionAbsolute(joints[0]), handWithFingertipsSkeleton->getPositionAbsolute(joints[1]), handWithFingertipsSkeleton->getPositionAbsolute(joints[2]), handWithFingertipsSkeleton->getPositionAbsolute(joints[3])}; float lengths[] = { positions[0].distance(positions[1]), positions[1].distance(positions[2]), positions[2].distance(positions[3])}; ofVec2f dir = positions[1] - positions[0]; if (bDoThumb && (i == 4)){ dir = positions[2] - positions[1]; } dir.normalize(); // compute the angleOffsetToUse for this finger. // The angleOffsetToUse is +/- based on the distance of the finger base to the splayaxis. float absDistanceFromSplayAxis = abs(basePos.y - splayAxis); float frac = ofClamp( (absDistanceFromSplayAxis / 10.0), 0, 1); if (basePos.y >= splayAxis) { angleOffsetToUse = -abs(averageAngleOffset) * frac; } else { angleOffsetToUse = abs(averageAngleOffset) * frac; } int fingerPartCount = 3; for (int j=0; j<fingerPartCount; j++) { dir = dir.getRotated (angleOffsetToUse); dir.normalize(); dir = dir * lengths[j]; ofVec2f parent = handWithFingertipsSkeleton->getPositionAbsolute(joints[j]); handWithFingertipsSkeleton->setPosition(joints[j+1], parent, true, false); handWithFingertipsSkeleton->setPosition(joints[j+1], dir, false, false); } } } //================================================================= void SplayFingers2Scene::updateMouse(float mx, float my) { ofVec2f mouse(mx, my); HandWithFingertipsSkeleton* handWithFingertipsSkeleton = (HandWithFingertipsSkeleton*)this->skeleton; HandWithFingertipsSkeleton* immutableHandWithFingertipsSkeleton = (HandWithFingertipsSkeleton*)this->immutableSkeleton; ofVec2f xAxis(1, 0); const int fingerCount = 5; int wrist = HandWithFingertipsSkeleton::WRIST; int palm = HandWithFingertipsSkeleton::PALM; int base[] = {HandWithFingertipsSkeleton::THUMB_BASE, HandWithFingertipsSkeleton::INDEX_BASE, HandWithFingertipsSkeleton::MIDDLE_BASE, HandWithFingertipsSkeleton::RING_BASE, HandWithFingertipsSkeleton::PINKY_BASE}; int mid[] = {HandWithFingertipsSkeleton::THUMB_MID, HandWithFingertipsSkeleton::INDEX_MID, HandWithFingertipsSkeleton::MIDDLE_MID, HandWithFingertipsSkeleton::RING_MID, HandWithFingertipsSkeleton::PINKY_MID}; int top[] = {HandWithFingertipsSkeleton::THUMB_TIP, HandWithFingertipsSkeleton::INDEX_TIP, HandWithFingertipsSkeleton::MIDDLE_TIP, HandWithFingertipsSkeleton::RING_TIP, HandWithFingertipsSkeleton::PINKY_TIP}; ofVec2f origWristPos = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(wrist)); ofVec2f origPalmPos = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(palm)); ofVec2f origBasePos[fingerCount]; ofVec2f origMidPos[fingerCount]; ofVec2f origTopPos[fingerCount]; for (int i=0; i < fingerCount; i++) { origBasePos[i] = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(base[i])); origMidPos[i] = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(mid[i])); origTopPos[i] = puppet->getOriginalMesh().getVertex(handWithFingertipsSkeleton->getControlIndex(top[i])); } ofVec2f origPalmDir; ofVec2f origFingerDir; float curRot; float newRot; float correction = 0; float baseCorrection[] = {26.75, -3, 1.75, 7.75, 9.75}; float midCorrection[] = {6.75, 2, -1.5, -1.75, -3.5}; switch(getSelection(mouseRadio)) { case 0: // palm position handWithFingertipsSkeleton->setPosition(HandWithFingertipsSkeleton::PALM, mouse, true); immutableHandWithFingertipsSkeleton->setPosition(HandWithFingertipsSkeleton::PALM, mouse, true); break; case 1: // palm rotation origPalmDir = origPalmPos - origWristPos; curRot = origPalmDir.angle(xAxis); newRot; if (mx <= 384) { newRot = ofMap(mx, 0, 384, -(curRot+correction+maxPalmAngleLeft), -(curRot+correction)); } else { newRot = ofMap(mx, 384, 768, -(curRot+correction), -(curRot+correction+maxPalmAngleRight)); } handWithFingertipsSkeleton->setRotation(palm, newRot, true, false); immutableHandWithFingertipsSkeleton->setRotation(palm, newRot, true, false); break; case 2: // finger base rotation for (int i=0; i < fingerCount; i++) { origFingerDir = origBasePos[i] - origPalmPos; curRot = origFingerDir.angle(xAxis); if (mx <= 384) { newRot = ofMap(mx, 0, 384, -(curRot+baseCorrection[i]+maxBaseAngleLeft), -(curRot+baseCorrection[i])); } else { newRot = ofMap(mx, 384, 768, -(curRot+baseCorrection[i]), -(curRot+baseCorrection[i]+maxBaseAngleRight)); } handWithFingertipsSkeleton->setRotation(base[i], newRot, true, false); immutableHandWithFingertipsSkeleton->setRotation(base[i], newRot, true, false); } break; } } void SplayFingers2Scene::draw() { //ofSetColor(255); //ofLine(0, splayAxis, ofGetWidth(),splayAxis); }
42.561576
215
0.699537
[ "vector" ]
e2e6d663668bc5d03e765ae2ffb0074c99763e2f
1,590
cpp
C++
2015/NOIP&NOI/NOIP2007tigao/core.cpp
jasha64/jasha64
653881f0f79075a628f98857e77eac27aef1919d
[ "MIT" ]
null
null
null
2015/NOIP&NOI/NOIP2007tigao/core.cpp
jasha64/jasha64
653881f0f79075a628f98857e77eac27aef1919d
[ "MIT" ]
null
null
null
2015/NOIP&NOI/NOIP2007tigao/core.cpp
jasha64/jasha64
653881f0f79075a628f98857e77eac27aef1919d
[ "MIT" ]
1
2020-06-15T07:58:13.000Z
2020-06-15T07:58:13.000Z
#include <iostream> #include <algorithm> #include <vector> using namespace std; const int N = 307, INF = 300007; int f[N][N], n, d, e[N][N]; bool G[N][N], v[N]; vector<int> r; vector<vector<int> > Roadlist; bool DFS(int x) { v[x] = true; if (G[x][d]) {r.push_back(x); return true;} for (int i = 1; i <= n; i++) if (G[x][i] && !v[i] && DFS(i)) {r.push_back(x); return true;} return false; } int main() { int s, a, b, c, i; cin >> n; for (i = 1; i <= n; i++) { fill(f[i] + 1, f[i] + i, INF); fill(f[i] + i + 1, f[i] + n + 1, INF); } cin >> s; for (i = 1; i < n; i++) { cin >> a >> b >> c; f[a][b] = f[b][a] = c; G[a][b] = G[b][a] = true; } int j, k, t; for (k = 1; k <= n; k++) for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) f[i][j] = min(f[i][j], f[i][k] + f[k][j]); k = 0; for (i = 1; i <= n; i++) for (j = i + 1; j <= n; j++) if (f[i][j] < INF) k = max(k, f[i][j]); for (i = 1; i <= n; i++) for (j = i + 1; j <= n; j++) if (f[i][j] == k) { r.push_back(j); d = j; fill(v, v + N, 0); DFS(i); Roadlist.push_back(r); r.clear(); } int l, Res = INF; while (!Roadlist.empty()) { r = Roadlist.back(); Roadlist.pop_back(); t = r.size(); for (i = 0; i < t; i++) for (j = i; j < t; j++) { a = r[i]; b = r[j]; if (f[a][b] > s) break; if (!e[a][b]) { for (k = 1; k <= n; k++) { c = min(f[k][a], f[k][b]); for (l = i + 1; l <= j; l++) c = min(c, f[k][r[l]]); e[a][b] = max(e[a][b], c); } } Res = min(Res, e[a][b]); } } cout << Res << endl; return 0; }
19.875
70
0.409434
[ "vector" ]
e2e9b6d8bfc226ba505ef98f1a4d2ec38c03a34e
2,060
hpp
C++
src/NetTcpJson/Extractor.hpp
OlivierLDff/NetTcpJson
e63d126cd0149b09cdf7f1c67d44da014c71c687
[ "MIT" ]
3
2021-06-08T23:59:35.000Z
2021-12-01T09:03:45.000Z
src/NetTcpJson/Extractor.hpp
OlivierLDff/NetTcpJson
e63d126cd0149b09cdf7f1c67d44da014c71c687
[ "MIT" ]
null
null
null
src/NetTcpJson/Extractor.hpp
OlivierLDff/NetTcpJson
e63d126cd0149b09cdf7f1c67d44da014c71c687
[ "MIT" ]
null
null
null
// // MIT License // // Copyright (c) 2021 Olivier Le Doeuff // // 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 __NETTCPJSON_EXTRACTOR_HPP__ #define __NETTCPJSON_EXTRACTOR_HPP__ #include <NetTcpJson/Export.hpp> #include <string> #include <vector> namespace nettcpjson { class NETTCPJSON_API_ Extractor { public: Extractor() = default; bool extract(const std::uint8_t* buffer, const std::size_t& length); void clear(); std::vector<std::string> takeAvailableStrings(); [[nodiscard]] const std::vector<std::string>& availableStrings() const; public: [[nodiscard]] const std::vector<std::uint8_t>& lastBuffer() const { return _lastBuffer; } [[nodiscard]] std::size_t maxBufferAllowedSize() const { return _maxBufferAllowedSize; } void setMaxBufferAllowedSize(std::size_t maxBufferAllowedSize); private: std::vector<std::string> _availableStrings; std::vector<std::uint8_t> _lastBuffer; std::size_t _maxBufferAllowedSize = 65535; }; } #endif
31.212121
81
0.735922
[ "vector" ]
e2eaec55358ebab22b1df6083124ced4234f7325
3,145
cpp
C++
Game/GameObject.cpp
Floppy/alienation
d2fca9344f88f70f1547573bea2244f77bd23379
[ "BSD-3-Clause" ]
null
null
null
Game/GameObject.cpp
Floppy/alienation
d2fca9344f88f70f1547573bea2244f77bd23379
[ "BSD-3-Clause" ]
null
null
null
Game/GameObject.cpp
Floppy/alienation
d2fca9344f88f70f1547573bea2244f77bd23379
[ "BSD-3-Clause" ]
null
null
null
#include "Game/GameObject.h" int CGameObject::m_iLastID = 0; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CGameObject::CGameObject(int num, float mass) : CSimulation(num, mass), m_poTarget(NULL), m_vecForce(0.0f,0.0f,0.0f), m_vecHeading(0.0f,0.0f,1.0f), m_vecUp(0.0f,1.0f,0.0f), m_vecRight(1.0f,0.0f,0.0f), m_vecDirection(0.0f,0.0f,1.0f), m_fPitch(0.0f), m_fYaw(0.0f), m_fRoll(0.0f), m_fPitchRate(0.0f), m_fYawRate(0.0f), m_fRollRate(0.0f), m_fVel(0.0f), m_fDrag(0.025f) { //initialise data m_ppMasses[0]->m_vecVel = CVector3(0.0f, 0.0f, 0.0f); m_vecHeading = CVector3(0.0f, -2.0f, -11.0f); m_matRotation.loadIdentity(); m_iObjectID = m_iLastID++; } CGameObject::CGameObject(){} CGameObject::~CGameObject() { } //what it says on the tin void CGameObject::draw(bool bTestFrustum) { m_oModel.boundingSphere().m_vecPos = m_ppMasses[0]->m_vecPos; if (bTestFrustum && !m_oFrustum.SphereInFrustum(&m_oModel.boundingSphere())) return; glPushMatrix(); glTranslatef(m_ppMasses[0]->m_vecPos.X(), m_ppMasses[0]->m_vecPos.Y(), m_ppMasses[0]->m_vecPos.Z()); glMultMatrixf(m_matRotation.glElements()); m_oModel.render(); //draw the ship glPopMatrix(); } void CGameObject::rotate(float fDT) { float fPitch = 0.0f, fYaw = 0.0f, fRoll = 0.0f; if (m_fPitchRate) { fPitch = fDT * m_fPitchRate; //change in pitch rate over time } if (m_fYawRate) { fYaw = fDT * m_fYawRate; //change in yaw rate over time } if (m_fRollRate) { fRoll = fDT * m_fRollRate; //change in roll rate over time } CQuat quaTemp(DEG_TO_RAD(fYaw), DEG_TO_RAD(fRoll), DEG_TO_RAD(fPitch)); quaTemp *= m_quaOrientation; m_quaOrientation = quaTemp; m_matRotation = CMatrix(m_quaOrientation); rotHeading(m_matRotation); } void CGameObject::rotHeading(CMatrix mat) { m_vecHeading = mat * CVector3( 0.0f, 0.0f,-1.0f) + m_ppMasses[0]->m_vecPos; m_vecUp = mat * CVector3( 0.0f, 1.0f, 0.0f) + m_ppMasses[0]->m_vecPos; m_vecRight = mat * CVector3( 1.0f, 0.0f, 0.0f) + m_ppMasses[0]->m_vecPos; } //Applies the time based update void CGameObject::simulate(float fDT) { CVector3 vecMovement, vecDistanceMoved; CSimulation::simulate (fDT); //get the amount of movement to calculate speed vecMovement = m_ppMasses[0]->m_vecPos - m_ppMasses[0]->m_vecOldPos; //Stores the movement as its used after its unitised vecDistanceMoved = vecMovement; //Not moved? velocity = 0; if (vecMovement.length() == 0.0f) { m_fVel = 0.0f; m_vecDirection = m_vecHeading; } else { //calculate velocity, new direction of movement m_fVel = vecMovement.length() / fDT; vecMovement.normalise(); m_vecDirection = vecMovement; } //Perform rotation to ship 0 rotate (fDT); } void CGameObject::setObjectType(int iObjectType) { m_iObjectType = iObjectType; } int CGameObject::getObjectType() { return m_iObjectType; } int CGameObject::getObjectID() { return m_iObjectID; }
22.625899
87
0.647695
[ "render" ]
e2ed86c2cb5a5ab5b5c7b14bc12362458c85ffab
3,447
cpp
C++
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_Ray_Tracing/Rendering_Objects/RENDERING_UNIFORM_GRID_ACCELERATOR.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_Ray_Tracing/Rendering_Objects/RENDERING_UNIFORM_GRID_ACCELERATOR.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_Ray_Tracing/Rendering_Objects/RENDERING_UNIFORM_GRID_ACCELERATOR.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2004, Ron Fedkiw, Andrew Selle. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class RENDERING_UNIFORM_GRID_ACCELERATOR //##################################################################### #include <PhysBAM_Rendering/PhysBAM_Ray_Tracing/Rendering_Objects/RENDERING_UNIFORM_GRID_ACCELERATOR.h> using namespace PhysBAM; //##################################################################### // Class INTERSECTION_MAP_HELPER //##################################################################### template<class T> class INTERSECTION_MAP_HELPER { public: const RENDERING_UNIFORM_GRID_ACCELERATOR<T>* rendering_uniform_accelerator; int lowest_priority; const RENDERING_OBJECT<T>** intersected_object;RAY<VECTOR<T,3> > working_ray; bool Callback(RAY<VECTOR<T,3> >& ray,const ARRAY<RENDERING_OBJECT_ACCELERATION_PRIMITIVE<T>*>& primitives,const T cell_t_max) {const RENDERING_OBJECT<T>* closest_object=0; for(int primitive_id=1;primitive_id<=primitives.m;primitive_id++){ RENDERING_OBJECT_ACCELERATION_PRIMITIVE<T>& primitive=*primitives(primitive_id); if(primitive.operation==rendering_uniform_accelerator->operation){ // already have done this intersection if(primitive.hit_aggregate_id!=-1&&primitive.hit_t<=cell_t_max&&primitive.hit_t<=working_ray.t_max){ closest_object=primitive.object;working_ray.t_max=primitive.hit_t;working_ray.aggregate_id=primitive.hit_aggregate_id;}} else if(primitive.object->Intersection(working_ray,primitive.aggregate_id)){ // got intersection if(working_ray.t_max<=cell_t_max)closest_object=primitive.object; // intersection was in cell else{ // intersection was not in current cell, save for later primitive.hit_t=working_ray.t_max;primitive.hit_aggregate_id=working_ray.aggregate_id;primitive.operation=rendering_uniform_accelerator->operation;}} else{ // no intersection, save for later primitive.hit_aggregate_id=-1;primitive.operation=rendering_uniform_accelerator->operation;}} if(closest_object){*intersected_object=closest_object;ray.Restore_Intersection_Information(working_ray);return true;} else return false;} }; //##################################################################### // Function Intersection //##################################################################### template<class T> bool RENDERING_UNIFORM_GRID_ACCELERATOR<T>:: Intersection(RAY<VECTOR<T,3> >& ray,const int lowest_priority,const RENDERING_OBJECT<T>** intersected_object) const { INTERSECTION_MAP_HELPER<T> helper;helper.rendering_uniform_accelerator=this;helper.lowest_priority=lowest_priority;helper.intersected_object=intersected_object; helper.working_ray=RAY<VECTOR<T,3> >(ray); bool intersect_value=uniform_grid.template Map_Intersection<INTERSECTION_MAP_HELPER<T>*>(ray,&helper); operation++; // throw away all saved mailboxes return intersect_value; } //##################################################################### template class RENDERING_UNIFORM_GRID_ACCELERATOR<float>; #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT template class RENDERING_UNIFORM_GRID_ACCELERATOR<double>; #endif
67.588235
167
0.659124
[ "object", "vector" ]
e2faf1f015608fc96caf9e68e3543bd09e9ed8d9
2,994
cc
C++
src/stack/phy/das/DasFilter.cc
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
58
2021-04-15T09:20:26.000Z
2022-03-31T08:52:23.000Z
src/stack/phy/das/DasFilter.cc
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
34
2021-05-14T15:05:36.000Z
2022-03-31T20:51:33.000Z
src/stack/phy/das/DasFilter.cc
talal00/Simu5G
ffbdda3e4cd873b49d7022912fe25e39d1a503e8
[ "Intel" ]
30
2021-04-16T05:46:13.000Z
2022-03-28T15:26:29.000Z
// // Simu5G // // Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa) // // This file is part of a software released under the license included in file // "license.pdf". Please read LICENSE and README files before using it. // The above files and the present reference are part of the software itself, // and cannot be removed from it. // #include "stack/phy/das/DasFilter.h" using namespace omnetpp; DasFilter::DasFilter(LtePhyBase* ltePhy, Binder* binder, RemoteAntennaSet* ruSet, double rssiThreshold) { ruSet_ = ruSet; rssiThreshold_ = rssiThreshold; binder_ = binder; ltePhy_ = ltePhy; } DasFilter::~DasFilter() { ruSet_ = nullptr; } void DasFilter::setMasterRuSet(MacNodeId masterId) { cModule* module = getSimulation()->getModule(binder_->getOmnetId(masterId)); if (getNodeTypeById(masterId) == ENODEB || getNodeTypeById(masterId) == GNODEB) { das_ = check_and_cast<LtePhyEnb*>(module->getSubmodule("cellularNic")->getSubmodule("phy"))->getDasFilter(); ruSet_ = das_->getRemoteAntennaSet(); } else { ruSet_ = nullptr; } // Clear structures used with old master on handover reportingSet_.clear(); } double DasFilter::receiveBroadcast(LteAirFrame* frame, UserControlInfo* lteInfo) { EV << "DAS Filter: Received Broadcast\n"; EV << "DAS Filter: ReportingSet now contains:\n"; reportingSet_.clear(); double rssiEnb = 0; for (unsigned int i=0; i<ruSet_->getAntennaSetSize(); i++) { // equal bitrate mapping std::vector<double> rssiV; LteChannelModel* channelModel = ltePhy_->getChannelModel(); if (channelModel == NULL) throw cRuntimeError("DasFilter::receiveBroadcast - channel model is a null pointer. Abort."); else rssiV = channelModel->getSINR(frame,lteInfo); std::vector<double>::iterator it; double rssi = 0; for (it=rssiV.begin();it!=rssiV.end();++it) rssi+=*it; rssi /= rssiV.size(); //EV << "Sender Position: (" << senderPos.getX() << "," << senderPos.getY() << ")\n"; //EV << "My Position: (" << myPos.getX() << "," << myPos.getY() << ")\n"; EV << "RU" << i << " RSSI: " << rssi; if (rssi > rssiThreshold_) { EV << " is associated"; reportingSet_.insert((Remote)i); } EV << "\n"; if (i == 0) rssiEnb = rssi; } return rssiEnb; } RemoteSet DasFilter::getReportingSet() { return reportingSet_; } RemoteAntennaSet* DasFilter::getRemoteAntennaSet() const { return ruSet_; } double DasFilter::getAntennaTxPower(int i) { return ruSet_->getAntennaTxPower(i); } inet::Coord DasFilter::getAntennaCoord(int i) { return ruSet_->getAntennaCoord(i); } std::ostream &operator << (std::ostream &stream, const DasFilter* das) { stream << das->getRemoteAntennaSet() << endl; return stream; }
27.218182
116
0.627255
[ "vector", "model" ]
c3b8dd802a4cb08dfb91ec151f2618394b125d9e
710
hpp
C++
source/CGTutorial/source/CarGhost.hpp
cg-htw/proof
dcee0468356b09e94b82508ced46b59cb4abe943
[ "Apache-2.0" ]
null
null
null
source/CGTutorial/source/CarGhost.hpp
cg-htw/proof
dcee0468356b09e94b82508ced46b59cb4abe943
[ "Apache-2.0" ]
null
null
null
source/CGTutorial/source/CarGhost.hpp
cg-htw/proof
dcee0468356b09e94b82508ced46b59cb4abe943
[ "Apache-2.0" ]
null
null
null
// // GhostController.hpp // CG_Beleg // // Created by Janis on 18.06.19. // #pragma once #include <stdio.h> #include "Constants.h" #include "Car.hpp" class CarGhost { std::vector<HistoryEntry> history; Model carModel; glm::mat4 *carModelMatrix; int currentPosition; double previousTimestamp; double currentTimestamp; std::vector<float> recordTimestamps; public: CarGhost(const std::string& file, Model carModel); // evt das Model übergeben glm::mat4 getModelMatrix(); void readRecordFile(const std::string& file); void updateCarMatrixWithHistory(double time); void draw(Shader shader, double time); std::vector<float> getRecordTimestamps(); };
20.882353
81
0.695775
[ "vector", "model" ]
c3bf27e9e0e18c248e18ee1fb690eb764337baf4
3,015
cpp
C++
src/prediction.cpp
enkhtuvshinj/CarND-Path-Planning
cbe0b36669c6279e82556f53bdb9fc3df33cd96a
[ "MIT" ]
null
null
null
src/prediction.cpp
enkhtuvshinj/CarND-Path-Planning
cbe0b36669c6279e82556f53bdb9fc3df33cd96a
[ "MIT" ]
null
null
null
src/prediction.cpp
enkhtuvshinj/CarND-Path-Planning
cbe0b36669c6279e82556f53bdb9fc3df33cd96a
[ "MIT" ]
null
null
null
#include "prediction.h" vector<double> NaiveBayesClassifier(const NaiveBayesParameters_t &param, vector<double> observation) { /** * Once trained, this method is called and expected to return * a predicted behavior for the given observation. * @param observation - a 4 tuple with s, d, s_dot, d_dot. * - Example: [3.5, 0.1, 8.5, -0.2] * @output A label representing the best guess of the classifier. Can * be one of "left", "keep" or "right". * * TODO: Complete this function to return your classifier's prediction */ // Calculate product of conditional probabilities for each label. double left_p = 1.0; double keep_p = 1.0; double right_p = 1.0; // For a feature x and label C with mean mu and standard deviation sigma (computed in training), // the conditional probability can be computed using the formula Naive Bayes formula for (int i=0; i<4; ++i) { left_p *= (1.0/sqrt(2.0 * M_PI * pow(param.left_stddev[i], 2))) * exp(-0.5*pow(observation[i] - param.left_mean[i], 2)/pow(param.left_stddev[i], 2)); keep_p *= (1.0/sqrt(2.0 * M_PI * pow(param.keep_stddev[i], 2))) * exp(-0.5*pow(observation[i] - param.keep_mean[i], 2)/pow(param.keep_stddev[i], 2)); right_p *= (1.0/sqrt(2.0 * M_PI * pow(param.right_stddev[i], 2))) * exp(-0.5*pow(observation[i] - param.right_mean[i], 2)/pow(param.right_stddev[i], 2)); } // Multiply each by the prior left_p *= param.left_prior; keep_p *= param.keep_prior; right_p *= param.right_prior; vector<double> probs; probs.push_back(left_p); probs.push_back(keep_p); probs.push_back(right_p); return probs; } /* Predict future position of observed cars based on assumption of the car with constant speed */ vector<vector<double>> Predict(vector<vector<double>> observations, int prev_size) { vector<vector<double>> predictions; for(int i=0; i<observations.size(); i++) { vector<double> projected_observation; float d = observations[i][6]; double car_lane = 2; if (d<=4) { car_lane = 0; } else if (d>4 && d<=8) { car_lane = 1; } double car_id = observations[i][0]; double vx = observations[i][3]; double vy = observations[i][4]; double velocity = sqrt(vx*vx + vy*vy); // magnitude of speed double s_at_t0 = observations[i][5]; // Using size of previous points, project s values at next 3 time steps. // basically, we looking at car in future double s_at_t1 = s_at_t0 + ((double)prev_size*0.02*velocity); double s_at_t2 = s_at_t0 + 2*((double)prev_size*0.02*velocity); double s_at_t3 = s_at_t0 + 3*((double)prev_size*0.02*velocity); projected_observation.push_back(car_id); projected_observation.push_back(car_lane); projected_observation.push_back(velocity); projected_observation.push_back(s_at_t1); projected_observation.push_back(s_at_t2); projected_observation.push_back(s_at_t3); predictions.push_back(projected_observation); } return predictions; }
37.222222
157
0.678275
[ "vector" ]
c3c1b058f17eb11aa0d159fe41d01bb744a0e05b
26,113
cpp
C++
test/test.cpp
markparticle/TinyJson
4eaa9a3d7e58dcb85e35623b3b80b0a073baaddd
[ "Apache-2.0" ]
2
2020-08-04T08:23:55.000Z
2021-07-13T08:03:59.000Z
test/test.cpp
markparticle/TinyJson
4eaa9a3d7e58dcb85e35623b3b80b0a073baaddd
[ "Apache-2.0" ]
null
null
null
test/test.cpp
markparticle/TinyJson
4eaa9a3d7e58dcb85e35623b3b80b0a073baaddd
[ "Apache-2.0" ]
1
2021-10-13T02:32:39.000Z
2021-10-13T02:32:39.000Z
/* * @Author : mark * @Date : 2020-05-26 * @copyleft Apache 2.0 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../code/tinyjson.h" static int testCount = 0; static int testPass = 0; static int mainRet = 0; #define EXPECT_EQ_BASE(equality, expect, actual, format) \ do {\ testCount++;\ if(equality)\ testPass++;\ else {\ fprintf(stderr, "%s:%d: expect: " format " actual: " format "\n", __FILE__, __LINE__, expect, actual);\ mainRet = 1;\ }\ } while(0) #define EXPECT_EQ_INT(expect, actual) EXPECT_EQ_BASE((expect) == (actual), expect, actual, "%d") #define EXPECT_EQ_DOUBLE(expect, actual) EXPECT_EQ_BASE((expect) == (actual), expect, actual, "%.17f") #define EXPECT_EQ_STRING(expect, actual, aLength) \ EXPECT_EQ_BASE(sizeof(expect) - 1 == aLength && \ memcmp(expect, actual, aLength) == 0, expect, actual, "%s") #define EXPECT_TRUE(actual) EXPECT_EQ_BASE(((actual) == true), "true", "false", "%s"); #define EXPECT_FALSE(actual) EXPECT_EQ_BASE(((actual) == false), "false", "true", "%s"); #define EXPECT_EQ_SIZE_T(expect, actual) EXPECT_EQ_BASE((expect) == (actual), (size_t)expect, (size_t)actual, "%zu"); #define TEST_PARSE(expectReact, expectValType, json)\ do {\ TinyValue value;\ TinyInitValue(&value);\ EXPECT_EQ_INT(expectReact, TinyParse(&value, json));\ EXPECT_EQ_INT(expectValType, TinyGetType(&value));\ TinyFree(&value);\ } while(0) #define TEST_PARSE_ERROR(expectReact, json)\ do {\ TEST_PARSE(expectReact, TINY_NULL, json);\ } while(0) #define TEST_PARSE_NUMBER(expectReact, expectNum, json)\ do {\ TinyValue value;\ EXPECT_EQ_INT(expectReact, TinyParse(&value, json));\ EXPECT_EQ_INT(TINY_NUMBER, TinyGetType(&value));\ EXPECT_EQ_DOUBLE(expectNum, TinyGetNumber(&value));\ TinyFree(&value);\ } while(0) #define TEST_STRING(expect, json) \ do {\ TinyValue value;\ TinyInitValue(&value);\ EXPECT_EQ_INT(TINY_PARSE_OK, TinyParse(&value, json));\ EXPECT_EQ_INT(TINY_STRING, TinyGetType(&value));\ EXPECT_EQ_STRING(expect, TinyGetString(&value), TinyGetStringLength(&value));\ TinyFree(&value);\ } while(0) #define TEST_ROUNDTRIP(json) \ do {\ TinyValue value;\ size_t len;\ TinyInitValue(&value);\ EXPECT_EQ_INT(TINY_PARSE_OK, TinyParse(&value, json));\ char* json2 = TinyStringify(&value, &len);\ EXPECT_EQ_STRING(json, json2, len);\ TinyFree(&value);\ free(json2);\ } while(0) #define TEST_EQUAL(json1, json2, equality) \ do {\ TinyValue v1, v2;\ TinyInitValue(&v1);\ TinyInitValue(&v2);\ EXPECT_EQ_INT(TINY_PARSE_OK, TinyParse(&v1, json1));\ EXPECT_EQ_INT(TINY_PARSE_OK, TinyParse(&v2, json2));\ EXPECT_EQ_INT(equality, TinyIsEqual(&v1, &v2));\ TinyFree(&v1);\ TinyFree(&v2);\ } while(0) static void TestParseOk() { TEST_PARSE(TINY_PARSE_OK, TINY_NULL, "null"); TEST_PARSE(TINY_PARSE_OK, TINY_FALSE, "false"); TEST_PARSE(TINY_PARSE_OK, TINY_TRUE, "true"); TEST_PARSE(TINY_PARSE_OK, TINY_STRING, "\"helloword!\""); } static void TestParseInvalidValue() { TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "nul"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "NULL"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "?"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "+0"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "+1"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, ".123"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "1."); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "0123"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "1.1.1"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "1e1e1"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "1e1.1"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "1.1e1e2"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "INF"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "inf"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "NAN"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "nan"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "[1,]"); TEST_PARSE_ERROR(TINY_PARSE_INVALID_VALUE, "[\"a\", nul]"); } static void TestParseExceptValue() { TEST_PARSE_ERROR(TINY_PARSE_EXPECT_VALUE, ""); TEST_PARSE_ERROR(TINY_PARSE_EXPECT_VALUE, " "); } static void TestParseRootNoSingular() { TEST_PARSE_ERROR(TINY_PARSE_ROOT_NOT_SINGULAR, "null x"); TEST_PARSE_ERROR(TINY_PARSE_ROOT_NOT_SINGULAR, "0x0"); TEST_PARSE_ERROR(TINY_PARSE_ROOT_NOT_SINGULAR, "0x123"); } static void TestParseNumberToBig() { #if 1 TEST_PARSE_ERROR(TINY_PARSE_NUMBER_TOO_BIG, "1e309"); TEST_PARSE_ERROR(TINY_PARSE_NUMBER_TOO_BIG, "-1e309"); TEST_PARSE_ERROR(TINY_PARSE_NUMBER_TOO_BIG, "1e30000009"); TEST_PARSE_ERROR(TINY_PARSE_NUMBER_TOO_BIG, "-1e3000009"); #endif } static void TestParseString() { TEST_STRING("", "\"\""); TEST_STRING("Hello", "\"Hello\""); TEST_STRING("Hello\nWord", "\"Hello\\nWord\""); TEST_STRING("\" \\ / \b \f \n \r \t", "\"\\\" \\\\ \\/ \\b \\f \\n \\r \\t\""); TEST_STRING("Hello\0World", "\"Hello\\u0000World\""); TEST_STRING("\x24", "\"\\u0024\""); /* Dollar sign U+0024 */ TEST_STRING("\xC2\xA2", "\"\\u00A2\""); /* Cents sign U+00A2 */ TEST_STRING("\xE2\x82\xAC", "\"\\u20AC\""); /* Euro sign U+20AC */ #if 1 TEST_STRING("\xF0\x9D\x84\x9E", "\"\\uD834\\uDD1E\""); /* G clef sign U+1D11E */ TEST_STRING("\xF0\x9D\x84\x9E", "\"\\ud834\\udd1e\""); /* G clef sign U+1D11E */ #endif } static void TestParseNumber() { TEST_PARSE_NUMBER(TINY_PARSE_OK, 0.0, "0"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 0.0, "-0"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 0.0, "-0.0"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 1.0, "1"); TEST_PARSE_NUMBER(TINY_PARSE_OK, -1.0, "-1"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 1.5, "1.5"); TEST_PARSE_NUMBER(TINY_PARSE_OK, -1.5, "-1.5"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 3.1415926, "3.1415926"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 1E10, "1E10"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 1e10, "1e10"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 1E-10, "1E-10"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 1E+10, "1E+10"); TEST_PARSE_NUMBER(TINY_PARSE_OK, -1E-10, "-1E-10"); TEST_PARSE_NUMBER(TINY_PARSE_OK, -3.1544e-10, "-3.1544e-10"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 3.1544e-10, "3.1544e-10"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 0.0, "1e-100000"); //the smallest number > 1 TEST_PARSE_NUMBER(TINY_PARSE_OK, 1.0000000000000002, "1.0000000000000002"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 4.9406564584124654e-324, "4.9406564584124654e-324"); TEST_PARSE_NUMBER(TINY_PARSE_OK, -4.9406564584124654e-324, "-4.9406564584124654e-324"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 2.2250738585072009e-308, "2.2250738585072009e-308"); TEST_PARSE_NUMBER(TINY_PARSE_OK, -2.2250738585072009e-308, "-2.2250738585072009e-308"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 2.2250738585072014e-308, "2.2250738585072014e-308"); TEST_PARSE_NUMBER(TINY_PARSE_OK, -2.2250738585072014e-308, "-2.2250738585072014e-308"); TEST_PARSE_NUMBER(TINY_PARSE_OK, 1.7976931348623157e+308, "1.7976931348623157e+308"); TEST_PARSE_NUMBER(TINY_PARSE_OK, -1.7976931348623157e+308, "-1.7976931348623157e+308"); } static void TestParseMissingQuotationMark() { TEST_PARSE_ERROR(TINY_PARSE_MISS_QUOTATION_MARK, "\""); TEST_PARSE_ERROR(TINY_PARSE_MISS_QUOTATION_MARK, "\"abc"); } static void TestParseInvalidStringEscape() { TEST_PARSE_ERROR(TINY_PARSE_INVALID_STRING_ESCAPE, "\"\\v\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_STRING_ESCAPE, "\"\\'\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_STRING_ESCAPE, "\"\\v\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_STRING_ESCAPE, "\"\\0\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_STRING_ESCAPE, "\"\\x12\""); } static void TestParseInvalidStringChar() { TEST_PARSE_ERROR(TINY_PARSE_INVALID_STRING_CHAR, "\"\x01\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_STRING_CHAR, "\"\x1F\""); } static void TestParseInvalidUnicodeHex() { TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u0\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u01\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u012\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u/000\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\uG000\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u0/00\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u0G00\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u00/0\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u00G0\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u000/\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u000G\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u000/\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_HEX, "\"\\u 123\""); } static void TestParseInvalidUnicodeSurrodate() { TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uD800\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uDBFF\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uD800\\\\\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uD800\\uDBFF\""); TEST_PARSE_ERROR(TINY_PARSE_INVALID_UNICODE_SURROGATE, "\"\\uD800\\uE000\""); } static void TestParseArray() { TinyValue value; TinyInitValue(&value); EXPECT_EQ_INT(TINY_PARSE_OK, TinyParse(&value, "[ null, false, true, 123, \"abc\" ]")); EXPECT_EQ_INT(TINY_ARRAY, TinyGetType(&value)); EXPECT_EQ_SIZE_T(5, TinyGetArraySize(&value)); EXPECT_EQ_INT(TINY_NULL, TinyGetType(TinyGetArrayElement(&value, 0))); EXPECT_EQ_INT(TINY_FALSE, TinyGetType(TinyGetArrayElement(&value, 1))); EXPECT_EQ_INT(TINY_TRUE, TinyGetType(TinyGetArrayElement(&value, 2))); EXPECT_EQ_INT(TINY_NUMBER, TinyGetType(TinyGetArrayElement(&value, 3))); EXPECT_EQ_INT(TINY_STRING, TinyGetType(TinyGetArrayElement(&value, 4))); EXPECT_EQ_DOUBLE(123.0, TinyGetNumber(TinyGetArrayElement(&value, 3))); EXPECT_EQ_STRING("abc", TinyGetString(TinyGetArrayElement(&value, 4)), TinyGetStringLength(TinyGetArrayElement(&value, 4))); TinyFree(&value); TinyInitValue(&value); EXPECT_EQ_INT(TINY_PARSE_OK, TinyParse(&value, "[ [ ] , [ 0 ] , [ 0 , 1 ] , [ 0 , 1 , 2 ] ]")); EXPECT_EQ_INT(TINY_ARRAY, TinyGetType(&value)); EXPECT_EQ_SIZE_T(4, TinyGetArraySize(&value)); for(size_t i = 0; i < 4; i++) { TinyValue* arr = TinyGetArrayElement(&value, i); EXPECT_EQ_INT(TINY_ARRAY, TinyGetType(arr)); EXPECT_EQ_SIZE_T(i, TinyGetArraySize(arr)); for(size_t j = 0; j < i; j++) { TinyValue* e = TinyGetArrayElement(arr, j); EXPECT_EQ_INT(TINY_NUMBER, TinyGetType(e)); EXPECT_EQ_DOUBLE((double)j, TinyGetNumber(e)); } } TinyFree(&value); } static void TestParseObject() { TinyValue value; TinyInitValue(&value); EXPECT_EQ_INT(TINY_PARSE_OK, TinyParse(&value, "{ }")); EXPECT_EQ_INT(TINY_OBJECT, TinyGetType(&value)); EXPECT_EQ_SIZE_T(0, TinyGetObjectSize(&value)); TinyFree(&value); TinyInitValue(&value); EXPECT_EQ_INT(TINY_PARSE_OK, TinyParse(&value, " { " "\"n\" : null , " "\"f\" : false , " "\"t\" : true , " "\"i\" : 123 , " "\"s\" : \"abc\", " "\"a\" : [ 1, 2, 3 ]," "\"o\" : { \"1\" : 1, \"2\" : 2, \"3\" : 3 }" " } " )); EXPECT_EQ_INT(TINY_OBJECT, TinyGetType(&value)); EXPECT_EQ_SIZE_T(7, TinyGetObjectSize(&value)); EXPECT_EQ_STRING("n", TinyGetObjectKey(&value, 0), TinyGetObjectKeyLength(&value, 0)); EXPECT_EQ_INT(TINY_NULL, TinyGetType(TinyGetObjectValue(&value, 0))); EXPECT_EQ_STRING("f", TinyGetObjectKey(&value, 1), TinyGetObjectKeyLength(&value, 1)); EXPECT_EQ_INT(TINY_FALSE, TinyGetType(TinyGetObjectValue(&value, 1))); EXPECT_EQ_STRING("t", TinyGetObjectKey(&value, 2), TinyGetObjectKeyLength(&value, 2)); EXPECT_EQ_INT(TINY_TRUE, TinyGetType(TinyGetObjectValue(&value, 2))); EXPECT_EQ_STRING("i", TinyGetObjectKey(&value, 3), TinyGetObjectKeyLength(&value, 3)); EXPECT_EQ_INT(TINY_NUMBER, TinyGetType(TinyGetObjectValue(&value, 3))); EXPECT_EQ_DOUBLE(123.0, TinyGetNumber(TinyGetObjectValue(&value, 3))); EXPECT_EQ_STRING("s", TinyGetObjectKey(&value, 4), TinyGetObjectKeyLength(&value, 4)); EXPECT_EQ_INT(TINY_STRING, TinyGetType(TinyGetObjectValue(&value, 4))); EXPECT_EQ_STRING("abc", TinyGetString(TinyGetObjectValue(&value, 4)), TinyGetStringLength(TinyGetObjectValue(&value, 4))); EXPECT_EQ_STRING("a", TinyGetObjectKey(&value, 5), TinyGetObjectKeyLength(&value, 5)); EXPECT_EQ_INT(TINY_ARRAY, TinyGetType(TinyGetObjectValue(&value, 5))); EXPECT_EQ_SIZE_T(3, TinyGetArraySize(TinyGetObjectValue(&value, 5))); for (size_t i = 0; i < 3; i++) { TinyValue* e = TinyGetArrayElement(TinyGetObjectValue(&value, 5), i); EXPECT_EQ_INT(TINY_NUMBER, TinyGetType(e)); EXPECT_EQ_DOUBLE(i + 1.0, TinyGetNumber(e)); } EXPECT_EQ_STRING("o", TinyGetObjectKey(&value, 6), TinyGetObjectKeyLength(&value, 6)); { TinyValue* o = TinyGetObjectValue(&value, 6); EXPECT_EQ_INT(TINY_OBJECT, TinyGetType(o)); for (size_t i = 0; i < 3; i++) { TinyValue* ov = TinyGetObjectValue(o, i); EXPECT_TRUE(('1' + (int)i) == TinyGetObjectKey(o, i)[0]); EXPECT_EQ_SIZE_T(1, TinyGetObjectKeyLength(o, i)); EXPECT_EQ_INT(TINY_NUMBER, TinyGetType(ov)); EXPECT_EQ_DOUBLE(i + 1.0, TinyGetNumber(ov)); } } TinyFree(&value); } static void TestParseMissCommaOrSquareBracket(){ TEST_PARSE_ERROR(TINY_PARSE_MISS_COMMA_OR_SQUARE_BRACKET, "[1"); TEST_PARSE_ERROR(TINY_PARSE_MISS_COMMA_OR_SQUARE_BRACKET, "[1}"); TEST_PARSE_ERROR(TINY_PARSE_MISS_COMMA_OR_SQUARE_BRACKET, "[1, 2"); TEST_PARSE_ERROR(TINY_PARSE_MISS_COMMA_OR_SQUARE_BRACKET, "[1 2"); TEST_PARSE_ERROR(TINY_PARSE_MISS_COMMA_OR_SQUARE_BRACKET, "[[[]]"); } static void TestParseMissKey() { TEST_PARSE_ERROR(TINY_PARSE_MISS_KEY, "{:1,"); TEST_PARSE_ERROR(TINY_PARSE_MISS_KEY, "{1:1,"); TEST_PARSE_ERROR(TINY_PARSE_MISS_KEY, "{true:1,"); TEST_PARSE_ERROR(TINY_PARSE_MISS_KEY, "{false:1,"); TEST_PARSE_ERROR(TINY_PARSE_MISS_KEY, "{null:1,"); TEST_PARSE_ERROR(TINY_PARSE_MISS_KEY, "{[]:1,"); TEST_PARSE_ERROR(TINY_PARSE_MISS_KEY, "{{}:1,"); TEST_PARSE_ERROR(TINY_PARSE_MISS_KEY, "{\"a\":1,"); } static void TestParseMissColon() { TEST_PARSE_ERROR(TINY_PARSE_MISS_COLON, "{\"a\"}"); TEST_PARSE_ERROR(TINY_PARSE_MISS_COLON, "{\"a\", \"b\"}"); } static void TestParseMissCommaOrCurlyBracket() { TEST_PARSE_ERROR(TINY_PARSE_MISS_COMMA_OR_CURLY_BRACKET, "{\"a\": 1"); TEST_PARSE_ERROR(TINY_PARSE_MISS_COMMA_OR_CURLY_BRACKET, "{\"a\": 1]"); TEST_PARSE_ERROR(TINY_PARSE_MISS_COMMA_OR_CURLY_BRACKET, "{\"a\": 1 \"b\""); TEST_PARSE_ERROR(TINY_PARSE_MISS_COMMA_OR_CURLY_BRACKET, "{\"a\": {}"); } static void TestAccessBool() { TinyValue value; TinyInitValue(&value); TinySetBoolen(&value, 0); EXPECT_FALSE(TinyGetBoolean(&value)); TinySetBoolen(&value, true); EXPECT_TRUE(TinyGetBoolean(&value)); TinyFree(&value); } static void TestAccessNull() { TinyValue value; TinyInitValue(&value); TinySetString(&value, "a", 1); TinySetNull(&value); EXPECT_EQ_INT(TINY_NULL,TinyGetType(&value)); TinyFree(&value); } static void TestAccessNumber() { TinyValue value; TinyInitValue(&value); TinySetNumber(&value, 123.0); EXPECT_EQ_DOUBLE(123.0, TinyGetNumber(&value)); TinyFree(&value); } static void TestAccessString() { TinyValue value; TinyInitValue(&value); TinySetString(&value, "", 0); EXPECT_EQ_STRING("", TinyGetString(&value), TinyGetStringLength(&value)); TinySetString(&value, "Hello", 5); EXPECT_EQ_STRING("Hello", TinyGetString(&value), TinyGetStringLength(&value)); TinyFree(&value); } static void TestAccessArray() { TinyValue a, e; TinyInitValue(&a); for(size_t j = 0; j <= 5; j += 5) { TinySetArray(&a, j); EXPECT_EQ_SIZE_T(0, TinyGetArraySize(&a)); EXPECT_EQ_SIZE_T(j, TinyGetArrayCapacity(&a)); for(size_t i = 0; i < 10; i++) { TinyInitValue(&e); TinySetNumber(&e, i); TinyMove(TinyPushBackArrayElement(&a), &e); TinyFree(&e); } } EXPECT_EQ_SIZE_T(10, TinyGetArraySize(&a)); for(size_t i = 0; i < 10; i++) { EXPECT_EQ_DOUBLE((double)i, TinyGetNumber(TinyGetArrayElement(&a, i))); } TinyPopBackArrayElement(&a); EXPECT_EQ_SIZE_T(9, TinyGetArraySize(&a)); for(size_t i = 0; i < 9; i++) { EXPECT_EQ_DOUBLE((double)i, TinyGetNumber(TinyGetArrayElement(&a, i))); } TinyEraseArrayElement(&a, 4, 0); EXPECT_EQ_SIZE_T(9, TinyGetArraySize(&a)); for(size_t i = 0; i < 9; i++) { EXPECT_EQ_DOUBLE((double)i, TinyGetNumber(TinyGetArrayElement(&a, i))); } TinyEraseArrayElement(&a, 8, 1); EXPECT_EQ_SIZE_T(8, TinyGetArraySize(&a)); for(size_t i = 0; i < 8; i++) { EXPECT_EQ_DOUBLE((double)i, TinyGetNumber(TinyGetArrayElement(&a, i))); } TinyEraseArrayElement(&a, 0, 2); EXPECT_EQ_SIZE_T(6, TinyGetArraySize(&a)); for(size_t i = 0; i < 6; i++) { EXPECT_EQ_DOUBLE((double)i + 2, TinyGetNumber(TinyGetArrayElement(&a, i))); } for(size_t i = 0; i < 2; i++) { TinyInitValue(&e); TinySetNumber(&e, i); TinyMove(TinyInsertArrayElement(&a, i), &e); TinyFree(&e); } EXPECT_EQ_SIZE_T(8, TinyGetArraySize(&a)); for(size_t i = 0; i < 8; i++) { EXPECT_EQ_DOUBLE((double)i, TinyGetNumber(TinyGetArrayElement(&a, i))); } EXPECT_TRUE(TinyGetArrayCapacity(&a) > 8); TinyShrinkArray(&a); EXPECT_TRUE(TinyGetArrayCapacity(&a) == 8); EXPECT_TRUE(TinyGetArraySize(&a) == 8); for(size_t i = 0; i < 8; i++) { EXPECT_EQ_DOUBLE((double)i, TinyGetNumber(TinyGetArrayElement(&a, i))); } TinySetString(&e, "Hello", 5); TinyMove(TinyPushBackArrayElement(&a), &e); /* Test if element is freed */ size_t i = TinyGetArrayCapacity(&a); TinyClearArray(&a); EXPECT_EQ_SIZE_T(0, TinyGetArraySize(&a)); EXPECT_EQ_SIZE_T(i, TinyGetArrayCapacity(&a)); TinyShrinkArray(&a); EXPECT_EQ_SIZE_T(0, TinyGetArrayCapacity(&a)); TinyFree(&a); } static void TestAccessObject() { TinyValue o, v, *pv; size_t i, j, index; TinyInitValue(&o); for(j = 0; j <= 5; j += 5) { TinySetObject(&o, j); EXPECT_EQ_SIZE_T(0, TinyGetObjectSize(&o)); EXPECT_EQ_SIZE_T(j, TinyGetObjectCapacity(&o)); for(i = 0; i < 10; i++) { char key[] = "a"; key[0] += i; TinyInitValue(&v); TinySetNumber(&v, i); TinyMove(TinySetObjectValue(&o, key, 1), &v); //TinyFree(&v); } EXPECT_EQ_SIZE_T(10, TinyGetObjectSize(&o)); for(i = 0; i < 10; i++) { char key[] = "a"; key[0] += i; index = TinyFindObjectIndex(&o, key, 1); EXPECT_TRUE(index != TINY_KEY_NOT_EXIST); pv = TinyGetObjectValue(&o, index); EXPECT_EQ_DOUBLE((double)i, TinyGetNumber(pv)); } } index = TinyFindObjectIndex(&o, "j", 1); EXPECT_TRUE(index != TINY_KEY_NOT_EXIST); TinyRemoveObjectValue(&o, index); index = TinyFindObjectIndex(&o, "j", 1); EXPECT_TRUE(index == TINY_KEY_NOT_EXIST); EXPECT_EQ_SIZE_T(9, TinyGetObjectSize(&o)); index = TinyFindObjectIndex(&o, "a", 1); EXPECT_TRUE(index != TINY_KEY_NOT_EXIST); TinyRemoveObjectValue(&o, index); index = TinyFindObjectIndex(&o, "a", 1); EXPECT_TRUE(index == TINY_KEY_NOT_EXIST); EXPECT_EQ_SIZE_T(8, TinyGetObjectSize(&o)); EXPECT_TRUE(TinyGetObjectCapacity(&o) > 8); TinyShrinkObject(&o); EXPECT_EQ_SIZE_T(8, TinyGetObjectCapacity(&o)); EXPECT_EQ_SIZE_T(8, TinyGetObjectSize(&o)); for(i = 0; i < 8; i++) { char key[] = "a"; key[0] += i + 1; EXPECT_EQ_DOUBLE((double)i + 1, TinyGetNumber(TinyGetObjectValue(&o, TinyFindObjectIndex(&o, key, 1)))); } TinySetString(&v, "Hello", 5); TinyMove(TinySetObjectValue(&o, "World", 5), &v); //TinyFree(&v); pv = TinyFindObjectValue(&o, "World", 5); EXPECT_TRUE(pv != NULL); EXPECT_EQ_STRING("Hello", TinyGetString(pv), TinyGetStringLength(pv)); i = TinyGetObjectCapacity(&o); TinyClearObject(&o); EXPECT_EQ_SIZE_T(0, TinyGetObjectSize(&o)); EXPECT_EQ_SIZE_T(i, TinyGetObjectCapacity(&o)); TinyShrinkObject(&o); EXPECT_EQ_SIZE_T(0, TinyGetObjectCapacity(&o)); TinyFree(&o); } static void TestStringifyNumber() { TEST_ROUNDTRIP("0"); TEST_ROUNDTRIP("-0"); TEST_ROUNDTRIP("-0"); TEST_ROUNDTRIP("1"); TEST_ROUNDTRIP("-1"); TEST_ROUNDTRIP("1.5"); TEST_ROUNDTRIP("-1.5"); TEST_ROUNDTRIP("-1e+20"); TEST_ROUNDTRIP("1.234e+20"); TEST_ROUNDTRIP("1.234e-20"); TEST_ROUNDTRIP("1.0000000000000002"); /* the smallest number > 1 */ TEST_ROUNDTRIP("4.9406564584124654e-324"); /* minimum denormal */ TEST_ROUNDTRIP("-4.9406564584124654e-324"); TEST_ROUNDTRIP("2.2250738585072009e-308"); /* Max subnormal double */ TEST_ROUNDTRIP("-2.2250738585072009e-308"); TEST_ROUNDTRIP("2.2250738585072014e-308"); /* Min normal positive double */ TEST_ROUNDTRIP("-2.2250738585072014e-308"); TEST_ROUNDTRIP("1.7976931348623157e+308"); /* Max double */ TEST_ROUNDTRIP("-1.7976931348623157e+308"); } static void TestStringifyString() { TEST_ROUNDTRIP("\"\""); TEST_ROUNDTRIP("\"Hello\""); TEST_ROUNDTRIP("\"Hello\\nWorld\""); TEST_ROUNDTRIP("\"\\\" \\\\ / \\b \\f \\n \\r \\t\""); TEST_ROUNDTRIP("\"Hello\\u0000World\""); } static void TestStringifyArray() { TEST_ROUNDTRIP("[]"); TEST_ROUNDTRIP("[null,false,true,123,\"abc\",[1,2,3]]"); } static void TestStringifyObject() { TEST_ROUNDTRIP("{}"); TEST_ROUNDTRIP("{\"n\":null,\"f\":false,\"t\":true,\"i\":123,\"s\":\"abc\",\"a\":[1,2,3],\"o\":{\"1\":1,\"2\":2,\"3\":3}}"); } static void TestParse() { TestParseOk(); TestParseNumber(); TestParseString(); // error // number TestParseNumberToBig(); TestParseExceptValue(); TestParseRootNoSingular(); // string TestParseInvalidValue(); TestParseInvalidStringChar(); TestParseInvalidStringEscape(); TestParseMissingQuotationMark(); TestParseInvalidUnicodeSurrodate(); TestParseInvalidUnicodeHex(); // array TestParseArray(); TestParseMissCommaOrSquareBracket(); // object TestParseMissKey(); TestParseMissColon(); TestParseMissCommaOrCurlyBracket(); TestParseObject(); } static void TestAccess() { TestAccessString(); TestAccessNumber(); TestAccessBool(); TestAccessNull(); TestAccessArray(); TestAccessObject(); } static void TestStringify() { TEST_ROUNDTRIP("null"); TEST_ROUNDTRIP("false"); TEST_ROUNDTRIP("true"); TestStringifyNumber(); TestStringifyString(); TestStringifyArray(); TestStringifyObject(); } static void TestEqual() { TEST_EQUAL("true", "true", 1); TEST_EQUAL("true", "false", 0); TEST_EQUAL("false", "false", 1); TEST_EQUAL("null", "null", 1); TEST_EQUAL("null", "0", 0); TEST_EQUAL("123", "123", 1); TEST_EQUAL("123", "456", 0); TEST_EQUAL("\"abc\"", "\"abc\"", 1); TEST_EQUAL("\"abc\"", "\"abcd\"", 0); TEST_EQUAL("[]", "[]", 1); TEST_EQUAL("[]", "null", 0); TEST_EQUAL("[1,2,3]", "[1,2,3]", 1); TEST_EQUAL("[1,2,3]", "[1,2,3,4]", 0); TEST_EQUAL("[1, 2, true, null, \"hello\"]", "[1, 2, true, null, \"hello\"]", 1); TEST_EQUAL("[[]]", "[[]]", 1); TEST_EQUAL("{}", "{}", 1); TEST_EQUAL("{}", "null", 0); TEST_EQUAL("{}", "[]", 0); TEST_EQUAL("{\"a\":1,\"b\":2}", "{\"a\":1,\"b\":2}", 1); TEST_EQUAL("{\"a\":1,\"b\":2}", "{\"b\":2,\"a\":1}", 1); TEST_EQUAL("{\"a\":1,\"b\":2}", "{\"a\":1,\"b\":3}", 0); TEST_EQUAL("{\"a\":1,\"b\":2}", "{\"a\":1,\"b\":2,\"c\":3}", 0); TEST_EQUAL("{\"a\":{\"b\":{\"c\":{}}}}", "{\"a\":{\"b\":{\"c\":{}}}}", 1); TEST_EQUAL("{\"a\":{\"b\":{\"c\":{}}}}", "{\"a\":{\"b\":{\"c\":[]}}}", 0); } static void TestCopy() { TinyValue v1, v2; TinyInitValue(&v1); TinyParse(&v1, "{\"t\":true,\"f\":false,\"n\":null,\"d\":1.5,\"a\":[1,2,3]}"); TinyInitValue(&v2); TinyCopy(&v2, &v1); EXPECT_TRUE(TinyIsEqual(&v1, &v2)); TinyFree(&v1); TinyFree(&v2); } static void TestMove() { TinyValue v1, v2, v3; TinyInitValue(&v1); TinyInitValue(&v2); TinyInitValue(&v3); TinyParse(&v1, "{\"t\":true,\"f\":false,\"n\":null,\"d\":1.5,\"a\":[1,2,3]}"); TinyCopy(&v2, &v1); TinyMove(&v3, &v2); EXPECT_EQ_INT(TINY_NULL, TinyGetType(&v2)); EXPECT_TRUE(TinyIsEqual(&v3, &v1)); TinyFree(&v1); TinyFree(&v2); TinyFree(&v3); } static void TestSwap() { TinyValue v1, v2; TinyInitValue(&v1); TinyInitValue(&v2); TinySetString(&v1, "Hello", 5); TinySetString(&v2, "world!", 6); TinySwap(&v2, &v1); EXPECT_EQ_STRING("world!", TinyGetString(&v1), TinyGetStringLength(&v1)); EXPECT_EQ_STRING("Hello", TinyGetString(&v2), TinyGetStringLength(&v2)); TinyFree(&v1); TinyFree(&v2); } int main() { TestParse(); TestAccess(); TestStringify(); TestEqual(); TestCopy(); TestMove(); TestSwap(); printf("%d/%d (%3.2f%%) passed!\n", testPass, testCount, 100.0 * testPass / testCount); return mainRet; }
37.304286
128
0.647034
[ "object" ]
c3c3c95ca9272843aae7c7f63eca1f286971df0c
16,097
hpp
C++
include/ilasynth/horn.hpp
Bo-Yuan-Huang/ItSy
aade7a0456461fcd160cd6a90bbca646c0d7990d
[ "MIT" ]
1
2018-12-08T07:32:38.000Z
2018-12-08T07:32:38.000Z
include/ilasynth/horn.hpp
PrincetonUniversity/ILA-Synthesis-Python
084564f5a8fbe9ae4c7e3d3c4995bf85885972f0
[ "MIT" ]
5
2018-12-07T15:59:41.000Z
2019-01-18T06:11:12.000Z
include/ilasynth/horn.hpp
PrincetonUniversity/ILA-Synthesis-Python
084564f5a8fbe9ae4c7e3d3c4995bf85885972f0
[ "MIT" ]
1
2019-05-15T14:56:43.000Z
2019-05-15T14:56:43.000Z
#ifndef __HORN_HPP_DEFINED__ #define __HORN_HPP_DEFINED__ #include <map> #include <set> #include <string> #include <ilasynth/ast.hpp> #include <ilasynth/type.hpp> namespace ilasynth { // ---------------------------------------------------------------------- // class HornVar; class HornLiteral; class HornClause; class HornDB; class HornTranslator; typedef HornVar* hvptr_t; typedef HornLiteral* hlptr_t; typedef HornClause* hcptr_t; // ---------------------------------------------------------------------- // class HornVar { private: // var id. unsigned _id; // var name. std::string _name; // var type. std::string _type; // constraint for var. std::set<std::string> _exec; // set of input (dependent) vars. std::map<std::string, hvptr_t> _ins; // set of output vars. std::set<hvptr_t> _outs; // var is const. bool _const; // var level. int _lvl; // non-deterministic value. std::string _nd; public: // ctor. HornVar(const unsigned& id); // dtor. virtual ~HornVar(); // ------------------------------------------------------------------ // // get var id. const unsigned& getId() const; // get var name. const std::string& getName() const; // get var type. const std::string& getType() const; // get var execution constraints. const std::set<std::string>& getExec() const; // get var predicate. std::string getPred() const; // get var relation. std::string getRel() const; // check if is constant. bool isConst() const; // ------------------------------------------------------------------ // // set var name. void setName(std::string s); // set var type. void setType(std::string s); // set constraints for var execution. void setExec(std::string s); // erase execution. void eraseExec(); // add dependent input var. void addInVar(hvptr_t v); // add output var. void addOutVar(hvptr_t v); // merge dependent input vars. void mergeInVars(hvptr_t v); // merge output vars. void mergeOutVars(hvptr_t v); // set to be constant. void setConst(); // get var level. const int& getLevel() const; // set var level. void setLevel(const int& lvl); // get the number of input vars. size_t getInNum() const; // get the number of output vars. size_t getOutNum() const; // get the input var set. const std::map<std::string, hvptr_t>& getInSet() const; // get the output var set. const std::set<hvptr_t>& getOutSet() const; // get the first output var. hvptr_t getOutVar() const; // ------------------------------------------------------------------ // // set non-deterministic value. void setNd(const std::string& nd); // get non-deterministic value. const std::string& getNd() const; // check if is nd. bool isNd() const; }; // ---------------------------------------------------------------------- // class HornLiteral { private: // var of the literal. hvptr_t _var; // sign of the literal. bool _sign; // the literal is a relation, else, a constraint. bool _rel; public: // ctor. HornLiteral(hvptr_t v, bool r = false, bool s = true); // dotr. virtual ~HornLiteral(); // ------------------------------------------------------------------ // // get the predicate, with sign considered. std::string getPred() const; // get the set of execution, with sign considered. std::set<std::string> getExec() const; // get the var. hvptr_t getVar() const; // get the sign. bool getSign() const; // check if it is a predicate. bool isRel() const; }; // ---------------------------------------------------------------------- // class HornClause { private: // horn clause body. std::set<hlptr_t> _body; // horn clause head. hlptr_t _head; public: // ctor. HornClause(); // dtor. virtual ~HornClause(); // ------------------------------------------------------------------ // // add one literal to the body. void addBody(hlptr_t l); // set the literal to the head. void setHead(hlptr_t l); // ------------------------------------------------------------------ // // output the clause to stream. void print(std::ostream& out); }; // ---------------------------------------------------------------------- // class HornRewriter { private: // translator HornTranslator* _tr; // predicate hvptr_t _pred; // var mapping from predicate input var to state. std::map<hvptr_t, std::string> _mapIS; // var mapping from predicate output var to state. std::map<hvptr_t, std::string> _mapOS; // var mapping from state to input. std::map<std::string, hvptr_t> _mapSI; // var mapping from state to output. std::map<std::string, hvptr_t> _mapSO; public: // ctor. HornRewriter(HornTranslator* tr, hvptr_t p); // dtor. virtual ~HornRewriter(); // configure predicate output arguments to state. Set up _mapVS. void configOutput(const std::string& state, hvptr_t arg); // configure predicate input argument as the original predicate. void configInput(); // update rewrite mapping for states. void update(const std::string& state, hvptr_t inArg, hvptr_t outArg); // rewrite predicate with specified rules. std::string rewrite(char inType, int inSuff, char outType, int outSuff); // add the rule of rewriting to the clause. void addRewriteRule(hcptr_t C, char aType, int aSuff, char bType, int bSuff); // get rewrited horn var. hvptr_t getRewriteVar(char inTy, int inSu, char outTy, int outSu); }; // ---------------------------------------------------------------------- // class HornDB { private: // set of variables. std::map<std::string, hvptr_t> _vars; // set of relations (predicates). std::set<hvptr_t> _rels; // set of horn clauses. std::set<hcptr_t> _clauses; // set of horn clauses for instruction wrapping. std::set<hcptr_t> _wrapClauses; public: // ctor. HornDB(); // dtor. virtual ~HornDB(); // ------------------------------------------------------------------ // // add one variable to the set. void addVar(hvptr_t v); // denote a rel to the set. void addRel(hvptr_t v); // add a clause to the set. void addClause(hcptr_t c); // add a clause to the instruction wrapping set. void addWrapClause(hcptr_t c); // remove a var from the set. void removeVar(const std::string& n); // remove a rel from the set. void removeRel(hvptr_t v); // ------------------------------------------------------------------ // // output whole to stream. void print(std::ostream& out); private: // output var declaration to stream. void declareVar(std::ostream& out); // output rel declaration to stream. void declareRel(std::ostream& out); // output clauses to stream. void declareClause(std::ostream& out); // output wrap clauses to stream. void declareWrapClause(std::ostream& out); // collector for duplicated ast nodes. std::set<hvptr_t> _dupls; }; // ---------------------------------------------------------------------- // class HornTranslator { private: // name for the translator. (prefix for variables) std::string _name; // pointer to the abstraction. Abstraction* _abs; // horn clause data base. HornDB* _db; // translate ITE as new clause or a node. bool _iteAsNode; // translate bitvectors as Int. bool _bvAsInt; // max bitvector length. int _bvMaxSize; public: // ctor; HornTranslator(Abstraction* abs, const std::string& name); // dtor. virtual ~HornTranslator(); // ------------------------------------------------------------------ // // convert whole abs to horn clauses and output to file. void hornifyAll(const std::string& fileName); // convert one ast node to horn clauses. hvptr_t hornifyNode(NodeRef* node, const std::string& ruleName); // convert abstraction to horn clauses. (Interleave/Blocking) void generateMapping(const std::string& type); // export horn clause to file. void exportHorn(const std::string& fileName); // set _iteAsNode. void setIteAsNode(bool iteAsNode); // set _bvAsInt. void setBvAsInt(bool bvAsInt); // ------------------------------------------------------------------ // // create an instruction with name i, and decode d. void addInstr(const std::string& i, NodeRef* d); // add next state function n for state s to (child-)instruction i. void addNext(const std::string& i, const std::string& s, NodeRef* n); // create a child-instruction with name c, and decode d to instr i. void addChildInstr(const std::string& c, const std::string& i, NodeRef* d); // ------------------------------------------------------------------ // // Traverse and generate horn clauses in depth-first order. void depthFirstTraverse(nptr_t n); // This will be used by depthFirstVisit. void operator()(nptr_t n); private: // var id count. unsigned _varCnt; // mapping from node to var (for internal var with ast node) std::map<nptr_t, hvptr_t> _nVarMap; // mapping from string to var (for top level var without ast node) std::map<std::string, hvptr_t> _sVarMap; // current working clause. hcptr_t _curHc; // structure for an instruction. struct Instr_t { std::string _name; hvptr_t _decodeFunc; std::map<std::string, hvptr_t> _nxtFuncs; std::set<std::string> _childInstrs; }; // sets of states. std::set<std::string> _states; // sets of instructions. std::map<std::string, struct Instr_t*> _instrs; // sets of child-instructions. std::map<std::string, struct Instr_t*> _childs; // ------------------------------------------------------------------ // // get horn var for the node; create if not exist. hvptr_t getVar(nptr_t n); // get horn var for the name; create if not exist. hvptr_t getVar(const std::string& s); // create a clause with the specified head. hcptr_t addClause(hvptr_t v = NULL); // initialize horn var from a node; Ex. _name, _exec, _outs. void initVar(hvptr_t v, nptr_t n); // initialize horn var from a node (model bitvector as BitVec). void initVarBv(hvptr_t v, nptr_t n); // initialize horn var from a node (model bitvector as Int). void initVarInt(hvptr_t v, nptr_t n); // initialize horn var from a name; _name. void initVar(hvptr_t v, const std::string& s); // get equal node. hvptr_t getEqVar(hvptr_t a, hvptr_t b); // get condition node. hvptr_t getConVar(hvptr_t c); // ------------------------------------------------------------------ // // eval if node n is an ITE node. bool isITE(nptr_t n) const; // ------------------------------------------------------------------ // // init horn var context: _name, _type, _exec, _ins, and _outs. // init horn var for BoolOp. void initBoolOp(const BoolOp* n, hvptr_t v); // init horn var for BoolVar. void initBoolVar(const BoolVar* n, hvptr_t v); // init horn var for BoolConst. void initBoolConst(const BoolConst* n, hvptr_t v); // init horn var for BitvectorOp. void initBvOp(const BitvectorOp* n, hvptr_t v); // init horn var for BitvectorVar. void initBvVar(const BitvectorVar* n, hvptr_t v); // init horn var for BitvectorConst. void initBvConst(const BitvectorConst* n, hvptr_t v); // init horn var for MemOp. void initMemOp(const MemOp* n, hvptr_t v); // init horn var for MemVar. void initMemVar(const MemVar* n, hvptr_t v); // init horn var for MemConst. void initMemConst(const MemConst* n, hvptr_t v); // init horn var for FuncVar. void initFuncVar(const FuncVar* n, hvptr_t v); // ------------------------------------------------------------------ // // if _bvAsNode is true: model bitvector as Int. // init horn var context: _name, _type, _exec, _ins, and _outs. // init horn var for BoolOp if bv as Int. void initBoolOpInt(const BoolOp* n, hvptr_t v); // init horn var for BoolVar if bv as Int. void initBoolVarInt(const BoolVar* n, hvptr_t v); // init horn var for BoolConst if bv as Int. void initBoolConstInt(const BoolConst* n, hvptr_t v); // init horn var for BitvectorOp if bv as Int. void initBvOpInt(const BitvectorOp* n, hvptr_t v); // init horn var for BitvectorVar if bv as Int. void initBvVarInt(const BitvectorVar* n, hvptr_t v); // init horn var for BitvectorConst if bv as Int. void initBvConstInt(const BitvectorConst* n, hvptr_t v); // init horn var for MemOp if bv as Int. void initMemOpInt(const MemOp* n, hvptr_t v); // init horn var for MemVar if bv as Int. void initMemVarInt(const MemVar* n, hvptr_t v); // init horn var for MemConst if bv as Int. void initMemConstInt(const MemConst* n, hvptr_t v); // init horn var for FuncVar if bv as Int. void initFuncVarInt(const FuncVar* n, hvptr_t v); // ------------------------------------------------------------------ // // add constraints or relations to working horn clause. // add BoolOp to horn clause. void addBoolOp(const BoolOp* n, hvptr_t v); // add BoolVar to horn clause. void addBoolVar(const BoolVar* n, hvptr_t v); // add BoolConst to horn clause. void addBoolConst(const BoolConst* n, hvptr_t v); // add BitvectorOp to horn clause. void addBvOp(const BitvectorOp* n, hvptr_t v); // add BitvectorVar to horn clause. void addBvVar(const BitvectorVar* n, hvptr_t v); // add BitvectorConst to horn clause. void addBvConst(const BitvectorConst* n, hvptr_t v); // add MemOp to horn clause. void addMemOp(const MemOp* n, hvptr_t v); // add MemVar to horn clause. void addMemVar(const MemVar* n, hvptr_t v); // add MemConst to horn clause. void addMemConst(const MemConst* n, hvptr_t v); // add FuncVar to horn clause. void addFuncVar(const FuncVar* n, hvptr_t v); // ------------------------------------------------------------------ // // generate BvOpReadMemBlock execution - little endian std::string genReadMemBlkExecLit(const std::string& mem, const std::string& addr, int addrWidth, int idx) const; // generate BvOpReadMemBlock execution - big endian std::string genReadMemBlkExecBig(const std::string& mem, const std::string& addr, int addrWidth, int idx, int num) const; // generate MemOpStoreMemBlock execution - little endian std::string genStoreMemBlkExecLit(const std::string& mem, const std::string& addr, const std::string& data, int chunkSize, int chunkNum, int addrWidth, int idx) const; // generate MemOpStoreMemBlock execution - big endian std::string genStoreMemBlkExecBig(const std::string& mem, const std::string& addr, const std::string& data, int chunkSize, int chunkNum, int addrWidth, int idx) const; // convert value to smt2.0 bitvector format. ex. #b0000 std::string bvToString(mp_int_t val, int width) const; // convert value to smt2.0 bitvector format. ex. #b0000 std::string bvToString(int val, int width) const; // generate rules for MemConst. void genMemConstRules(const MemConst* n, hvptr_t v); public: // ------------------------------------------------------------------ // // create name with suffix index: name_idx std::string addSuffix(const std::string& name, const int& idx) const; // duplicate variable with suffix index hvptr_t copyVar(hvptr_t v, const int& idx); private: // ------------------------------------------------------------------ // // check if the length exceed maximum bitvector width. bool isLongBv(const int& w) const; // ------------------------------------------------------------------ // // generate mappings for interleave modeling. void generateInterleaveMapping(); // generate mappings for blocking modeling. void generateBlockingMapping(); // generate loop predicate. HornRewriter* generateLoopPredicate(); // generate mappings for interleave modeling for all instructions. void allInterleaveMapping(); }; } // namespace ilasynth #endif /* __HORN_HPP_DEFINED__ */
34.248936
80
0.596633
[ "model" ]
c3d489974062f576b069c4257fb1aa118ef5bf0e
3,397
cpp
C++
src/core/CL/CLTracePoint.cpp
Ehsan-aghapour/AI-Sheduling-Reprodution
657dfa7c875445ab275c8a4418bbf29ed4d94891
[ "MIT" ]
1
2021-08-24T15:44:31.000Z
2021-08-24T15:44:31.000Z
src/core/CL/CLTracePoint.cpp
Ehsan-aghapour/AI-Sheduling-Reprodution
657dfa7c875445ab275c8a4418bbf29ed4d94891
[ "MIT" ]
1
2021-08-31T14:38:07.000Z
2022-02-16T16:34:13.000Z
src/core/CL/CLTracePoint.cpp
Ehsan-aghapour/AI-Sheduling-Reprodution
657dfa7c875445ab275c8a4418bbf29ed4d94891
[ "MIT" ]
1
2021-03-28T07:09:48.000Z
2021-03-28T07:09:48.000Z
/* * Copyright (c) 2020-2021 Arm Limited. * * SPDX-License-Identifier: MIT * * 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 "arm_compute/core/TracePoint.h" #include "arm_compute/core/CL/CLTypes.h" #include "arm_compute/core/CL/ICLArray.h" #include "arm_compute/core/CL/ICLDistribution1D.h" #include "arm_compute/core/CL/ICLHOG.h" #include "arm_compute/core/CL/ICLLut.h" #include "arm_compute/core/CL/ICLMultiHOG.h" #include "arm_compute/core/CL/ICLMultiImage.h" #include "arm_compute/core/CL/ICLTensor.h" #include "utils/TypePrinter.h" #include <vector> namespace arm_compute { std::string to_string(const ICLTensor &arg) { std::stringstream str; str << "TensorInfo(" << *arg.info() << ")"; return str.str(); } template <> TracePoint::Args &&operator<<(TracePoint::Args &&tp, const ICLTensor *arg) { tp.args.push_back("ICLTensor(" + to_string_if_not_null(arg) + ")"); return std::move(tp); } ARM_COMPUTE_TRACE_TO_STRING(std::vector<ICLTensor *>) ARM_COMPUTE_TRACE_TO_STRING(ICLMultiImage) ARM_COMPUTE_TRACE_TO_STRING(ICLDetectionWindowArray) ARM_COMPUTE_TRACE_TO_STRING(ICLKeyPointArray) ARM_COMPUTE_TRACE_TO_STRING(ICLLKInternalKeypointArray) ARM_COMPUTE_TRACE_TO_STRING(ICLCoefficientTableArray) ARM_COMPUTE_TRACE_TO_STRING(ICLCoordinates2DArray) ARM_COMPUTE_TRACE_TO_STRING(ICLOldValArray) ARM_COMPUTE_TRACE_TO_STRING(cl::Buffer) ARM_COMPUTE_TRACE_TO_STRING(ICLDistribution1D) ARM_COMPUTE_TRACE_TO_STRING(ICLMultiHOG) ARM_COMPUTE_TRACE_TO_STRING(ICLHOG) ARM_COMPUTE_TRACE_TO_STRING(ICLLut) ARM_COMPUTE_TRACE_TO_STRING(ICLSize2DArray) ARM_COMPUTE_TRACE_TO_STRING(std::vector<const ICLTensor *>) ARM_COMPUTE_CONST_PTR_CLASS(std::vector<ICLTensor *>) ARM_COMPUTE_CONST_PTR_CLASS(ICLMultiImage) ARM_COMPUTE_CONST_PTR_CLASS(ICLDetectionWindowArray) ARM_COMPUTE_CONST_PTR_CLASS(ICLKeyPointArray) ARM_COMPUTE_CONST_PTR_CLASS(ICLLKInternalKeypointArray) ARM_COMPUTE_CONST_PTR_CLASS(ICLCoefficientTableArray) ARM_COMPUTE_CONST_PTR_CLASS(ICLCoordinates2DArray) ARM_COMPUTE_CONST_PTR_CLASS(ICLOldValArray) ARM_COMPUTE_CONST_PTR_CLASS(cl::Buffer) ARM_COMPUTE_CONST_PTR_CLASS(ICLDistribution1D) ARM_COMPUTE_CONST_PTR_CLASS(ICLMultiHOG) ARM_COMPUTE_CONST_PTR_CLASS(ICLHOG) ARM_COMPUTE_CONST_PTR_CLASS(ICLLut) ARM_COMPUTE_CONST_PTR_CLASS(ICLSize2DArray) ARM_COMPUTE_CONST_PTR_CLASS(std::vector<const ICLTensor *>) } // namespace arm_compute
39.5
81
0.814248
[ "vector" ]
c3d8d278b420ad75f241c21c929f60b50508cedc
802
cpp
C++
GCJ/kickstart/2017/round-B/A/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
2
2018-11-08T05:57:22.000Z
2018-11-08T05:57:27.000Z
GCJ/kickstart/2017/round-B/A/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
GCJ/kickstart/2017/round-B/A/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { freopen("test.in", "r", stdin); freopen("test.out", "w", stdout); int T; cin >> T; for(int test = 1; test <= T; test++) { int n; cin >> n; vector < int > aa(n); for(int i = 0; i < n; i++) cin >> aa[i]; sort(aa.begin(), aa.end()); long long mod = 1e9 + 7; long long ans = 0; vector < long long > bp(n + 1); bp[0] = 1; for(int i = 1; i <= n; i++) bp[i] = (bp[i - 1] * 2) % mod; for(int i = 0; i < n; i++) { ans = (ans + (aa[i] * bp[i]) % mod) % mod; ans = (ans - (aa[i] * bp[n - 1 - i]) % mod + mod) % mod; } cout << "Case #" << test << ": " << ans << endl; } return 0; }
22.914286
68
0.386534
[ "vector" ]
c3d9a68f02b5ea0344f1f42e019afb6659e4b98a
39,628
cpp
C++
src/MayaBridge/DeviceGrabber/NuiMayaDeviceGrabber.cpp
hustztz/NatureUserInterfaceStudio
3cdac6b6ee850c5c8470fa5f1554c7447be0d8af
[ "MIT" ]
3
2016-07-14T13:04:35.000Z
2017-04-01T09:58:27.000Z
src/MayaBridge/DeviceGrabber/NuiMayaDeviceGrabber.cpp
hustztz/NatureUserInterfaceStudio
3cdac6b6ee850c5c8470fa5f1554c7447be0d8af
[ "MIT" ]
null
null
null
src/MayaBridge/DeviceGrabber/NuiMayaDeviceGrabber.cpp
hustztz/NatureUserInterfaceStudio
3cdac6b6ee850c5c8470fa5f1554c7447be0d8af
[ "MIT" ]
1
2021-11-21T15:33:35.000Z
2021-11-21T15:33:35.000Z
#include "../api_macros.h" #include "NuiMayaDeviceGrabber.h" #include "NuiMayaPreviewerRenderOverride.h" #include "Frame/Buffer/NuiFrameCache.h" #include "Frame/Buffer/NuiFrameBuffer.h" #include "DeviceManager/NuiRGBDDeviceController.h" #include "SLAM/Backend/NuiSLAMController.h" #include "../SkeletonDriver/NuiMayaSkeletonData.h" #include "../SkeletonDriver/NuiMayaGestureData.h" #include "../SkeletonDriver/NuiMayaFacialModelData.h" #include "../SkeletonDriver/NuiMayaImageData.h" #include "../PointCloudShape/NuiMayaMappableData.h" #include "Shape/NuiMeshShape.h" #include "Frame/NuiFrameUtilities.h" #include <maya/MTime.h> #include <maya/MGlobal.h> #include <maya/MPlug.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnEnumAttribute.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnUnitAttribute.h> #include <maya/MFnPluginData.h> #include <maya/MFnMesh.h> #include <maya/MFnMeshData.h> #include <maya/MFloatPointArray.h> #include <maya/MFloatArray.h> #include <maya/MDistance.h> static std::string sTestDataFolder = getenv("NUI_TESTDATA") ? getenv("NUI_TESTDATA") : "G:\\tmp\\"; MTypeId NuiMayaDeviceGrabber::id( 0x80089 ); // Attributes // MObject NuiMayaDeviceGrabber::aTime; MObject NuiMayaDeviceGrabber::aDeviceOn; MObject NuiMayaDeviceGrabber::aDeviceMode; MObject NuiMayaDeviceGrabber::aUseCache; MObject NuiMayaDeviceGrabber::aNearMode; MObject NuiMayaDeviceGrabber::aElevationAngle; MObject NuiMayaDeviceGrabber::aPreviewerOn; MObject NuiMayaDeviceGrabber::aKinFuOn; MObject NuiMayaDeviceGrabber::aVolumeVoxelSize; MObject NuiMayaDeviceGrabber::aShowMesh; MObject NuiMayaDeviceGrabber::aShowInvalid; MObject NuiMayaDeviceGrabber::aShowOnlyBody; MObject NuiMayaDeviceGrabber::aMinDepth; MObject NuiMayaDeviceGrabber::aMaxDepth; MObject NuiMayaDeviceGrabber::aOutputMappable; MObject NuiMayaDeviceGrabber::aOutputMesh; MObject NuiMayaDeviceGrabber::aOutputSkeleton; MObject NuiMayaDeviceGrabber::aOutputGesture; MObject NuiMayaDeviceGrabber::aOutputFacialModel; MObject NuiMayaDeviceGrabber::aFaceRotateX; MObject NuiMayaDeviceGrabber::aFaceRotateY; MObject NuiMayaDeviceGrabber::aFaceRotateZ; MObject NuiMayaDeviceGrabber::aFaceRotate; MObject NuiMayaDeviceGrabber::aCameraRotateX; MObject NuiMayaDeviceGrabber::aCameraRotateY; MObject NuiMayaDeviceGrabber::aCameraRotateZ; MObject NuiMayaDeviceGrabber::aCameraRotate; MObject NuiMayaDeviceGrabber::aCameraTranslateX; MObject NuiMayaDeviceGrabber::aCameraTranslateY; MObject NuiMayaDeviceGrabber::aCameraTranslateZ; MObject NuiMayaDeviceGrabber::aCameraTranslate; NuiMayaDeviceGrabber::NuiMayaDeviceGrabber() : m_pDevice(NULL) , m_pCache(NULL) , m_pSLAM(NULL) { } NuiMayaDeviceGrabber::~NuiMayaDeviceGrabber() { if(m_pDevice) m_pDevice->stopDevice(); SafeDelete(m_pDevice); SafeDelete(m_pSLAM); if(m_pCache) m_pCache->clear(); SafeDelete(m_pCache); removeCallbacks(); } void NuiMayaDeviceGrabber::attrChangedCB(MNodeMessage::AttributeMessage msg, MPlug & plug, MPlug & otherPlug, void* clientData) { NuiMayaDeviceGrabber *wrapper = static_cast<NuiMayaDeviceGrabber *>(clientData); if(!wrapper) return; MStatus stat; MObject attr = plug.attribute(&stat); MFnAttribute fnAttr(attr); if (fnAttr.name() == "deviceOn" || fnAttr.name() == "deviceMode" ) { wrapper->updateDevice(); } else if (fnAttr.name() == "nearMode") { wrapper->updateNearMode(); } else if (fnAttr.name() == "elevationAngle") { wrapper->updateaElevationAngle(); } else if (fnAttr.name() == "previewerOn") { wrapper->updatePreviewer(); } else if (fnAttr.name() == "fusionOn") { wrapper->updateKinfu(); } } void NuiMayaDeviceGrabber::addCallbacks() { MStatus status; MObject node = thisMObject(); fCallbackIds.append( MNodeMessage::addAttributeChangedCallback(node, attrChangedCB, (void*)this) ); } void NuiMayaDeviceGrabber::removeCallbacks() { MMessage::removeCallbacks(fCallbackIds); } void NuiMayaDeviceGrabber::postConstructor() { // Avoid node to be auto deleted when all connection breaks setExistWithoutInConnections(true); setExistWithoutOutConnections(true); addCallbacks(); SafeDelete(m_pCache); m_pCache = new NuiFrameBuffer(); SafeDelete(m_pDevice); m_pDevice = new NuiRGBDDeviceController(); } void* NuiMayaDeviceGrabber::creator() // // Description: // this method exists to give Maya a way to create new objects // of this type. // // Return Value: // a new object of this type // { return new NuiMayaDeviceGrabber(); } MStatus NuiMayaDeviceGrabber::initialize() // // Description: // This method is called to create and initialize all of the attributes // and attribute dependencies for this node type. This is only called // once when the node type is registered with Maya. // // Return Values: // MS::kSuccess // MS::kFailure // { // This sample creates a single input float attribute and a single // output float attribute. // MFnNumericAttribute nAttr; MFnTypedAttribute typedAttr; MFnUnitAttribute unitAttr; MFnEnumAttribute enumAttr; MStatus stat; aTime = unitAttr.create( "time", "tm", MFnUnitAttribute::kTime, 0.0, &stat ); stat = addAttribute( aTime ); if (!stat) { stat.perror("addAttribute time"); return stat;} aUseCache = nAttr.create( "useCache", "uc", MFnNumericData::kBoolean, false ); // Attribute will be written to files when this type of node is stored nAttr.setStorable(true); // Attribute is keyable and will show up in the channel box stat = addAttribute( aUseCache ); if (!stat) { stat.perror("addAttribute"); return stat;} aDeviceOn = nAttr.create( "deviceOn", "do", MFnNumericData::kBoolean, false ); // Attribute will be written to files when this type of node is stored nAttr.setStorable(true); // Attribute is keyable and will show up in the channel box stat = addAttribute( aDeviceOn ); if (!stat) { stat.perror("addAttribute"); return stat;} aDeviceMode = enumAttr.create( "deviceMode", "dm", NuiRGBDDeviceController::EDeviceMode_VertexColorCamera, &stat ); if (!stat) { stat.perror("create DeviceMode attribute"); return stat;} stat = enumAttr.addField( "Depth,Color", NuiRGBDDeviceController::EDeviceMode_DepthColor ); if (!stat) { stat.perror("add enum type DepthColor"); return stat;} stat = enumAttr.addField( "Depth,Color,Player", NuiRGBDDeviceController::EDeviceMode_VertexColorCamera ); if (!stat) { stat.perror("add enum type DepthColorPlayer"); return stat;} stat = enumAttr.addField( "Depth,Color,Skeleton", NuiRGBDDeviceController::EDeviceMode_VertexColorSkeleton ); if (!stat) { stat.perror("add enum type DepthColorSkeleton"); return stat;} stat = enumAttr.addField( "Depth,Color,Skeleton,Face", NuiRGBDDeviceController::EDeviceMode_VertexColorSkeletonFace ); if (!stat) { stat.perror("add enum type DepthColorSkeletonFace"); return stat;} stat = enumAttr.addField( "Depth,Color,Skeleton,Gesture", NuiRGBDDeviceController::EDeviceMode_VertexColorSkeletonGesture ); if (!stat) { stat.perror("add enum type DepthColorSkeletonGesture"); return stat;} stat = enumAttr.addField( "Color", NuiRGBDDeviceController::EDeviceMode_Color ); if (!stat) { stat.perror("add enum type Color"); return stat;} stat = enumAttr.addField( "Depth", NuiRGBDDeviceController::EDeviceMode_Vertex ); if (!stat) { stat.perror("add enum type Depth"); return stat;} stat = enumAttr.addField( "Skeleton", NuiRGBDDeviceController::EDeviceMode_Skeleton ); if (!stat) { stat.perror("add enum type Skeleton"); return stat;} stat = enumAttr.addField( "Fusion", NuiRGBDDeviceController::EDeviceMode_Fusion ); if (!stat) { stat.perror("add enum type fusion"); return stat;} CHECK_MSTATUS( enumAttr.setHidden( false ) ); CHECK_MSTATUS( enumAttr.setKeyable( false ) ); stat = addAttribute( aDeviceMode ); if (!stat) { stat.perror("addAttribute"); return stat;} aNearMode = nAttr.create( "nearMode", "ne", MFnNumericData::kBoolean, false ); // Attribute will be written to files when this type of node is stored nAttr.setStorable(true); // Attribute is keyable and will show up in the channel box stat = addAttribute( aNearMode ); if (!stat) { stat.perror("addAttribute"); return stat;} aElevationAngle = nAttr.create( "elevationAngle", "ea", MFnNumericData::kInt, 0 ); // Attribute will be written to files when this type of node is stored nAttr.setStorable(true); nAttr.setKeyable(true); nAttr.setMin(-27); nAttr.setMax(27); // Attribute is keyable and will show up in the channel box stat = addAttribute( aElevationAngle ); if (!stat) { stat.perror("addAttribute"); return stat;} aPreviewerOn = nAttr.create( "previewerOn", "po", MFnNumericData::kBoolean, false ); // Attribute will be written to files when this type of node is stored nAttr.setStorable(true); // Attribute is keyable and will show up in the channel box stat = addAttribute( aPreviewerOn ); if (!stat) { stat.perror("addAttribute"); return stat;} aKinFuOn = nAttr.create( "fusionOn", "fo", MFnNumericData::kBoolean, false ); // Attribute will be written to files when this type of node is stored nAttr.setStorable(true); // Attribute is keyable and will show up in the channel box stat = addAttribute( aKinFuOn ); if (!stat) { stat.perror("addAttribute"); return stat;} aVolumeVoxelSize = nAttr.create( "volumeVoxelSize", "vvs", MFnNumericData::kFloat, 0.01f ); // Attribute will be written to files when this type of node is stored nAttr.setStorable(true); nAttr.setKeyable(true); nAttr.setMin(0.005f); nAttr.setMax(0.02f); // Attribute is keyable and will show up in the channel box stat = addAttribute( aVolumeVoxelSize ); if (!stat) { stat.perror("addAttribute"); return stat;} aShowInvalid = nAttr.create("showInvalid", "siv", MFnNumericData::kBoolean, false, &stat); MCHECKERROR( stat, "create showInvalid attribute" ) nAttr.setKeyable(true); ADD_ATTRIBUTE( aShowInvalid ); aShowOnlyBody = nAttr.create("showOnlyBody", "sc", MFnNumericData::kBoolean, false, &stat); MCHECKERROR( stat, "create showOnlyBody attribute" ) nAttr.setKeyable(true); ADD_ATTRIBUTE( aShowOnlyBody ); aShowMesh = nAttr.create("showMesh", "sm", MFnNumericData::kBoolean, false, &stat); MCHECKERROR( stat, "create showMesh attribute" ) nAttr.setKeyable(true); ADD_ATTRIBUTE( aShowMesh ); aMinDepth = nAttr.create( "nearPlane", "np", MFnNumericData::kShort, 400 ); // Attribute will be written to files when this type of node is stored nAttr.setStorable(true); nAttr.setKeyable(true); nAttr.setMin(400); nAttr.setMax(4500); // Attribute is keyable and will show up in the channel box stat = addAttribute( aMinDepth ); if (!stat) { stat.perror("addAttribute"); return stat;} aMaxDepth = nAttr.create( "farPlane", "fp", MFnNumericData::kShort, 4200 ); // Attribute will be written to files when this type of node is stored nAttr.setStorable(true); nAttr.setKeyable(true); nAttr.setMin(400); nAttr.setMax(4500); // Attribute is keyable and will show up in the channel box stat = addAttribute( aMaxDepth ); if (!stat) { stat.perror("addAttribute"); return stat;} // ----------------------- OUTPUTS ------------------------- aOutputMappable = typedAttr.create( "outputPointCloud", "opc", NuiMayaMappableData::id, MObject::kNullObj, &stat ); if (!stat) { stat.perror("create outputPointCloud attribute"); return stat;} typedAttr.setWritable( false ); typedAttr.setStorable(false); stat = addAttribute( aOutputMappable ); if (!stat) { stat.perror("addAttribute"); return stat;} aOutputSkeleton = typedAttr.create( "outputSkeleton", "osk", NuiMayaSkeletonData::id, MObject::kNullObj, &stat ); if (!stat) { stat.perror("create outputSkeleton attribute"); return stat;} typedAttr.setWritable( false ); typedAttr.setStorable(false); stat = addAttribute( aOutputSkeleton ); if (!stat) { stat.perror("addAttribute"); return stat;} aOutputMesh = typedAttr.create( "outputMesh", "om", MFnData::kMesh, MObject::kNullObj, &stat ); MCHECKERROR( stat, "create outputSurface attribute" ) typedAttr.setWritable( false ); ADD_ATTRIBUTE( aOutputMesh ); aOutputGesture = typedAttr.create( "outputGesture", "ogs", NuiMayaGestureData::id, MObject::kNullObj, &stat ); if (!stat) { stat.perror("create outputGesture attribute"); return stat;} typedAttr.setWritable( false ); typedAttr.setStorable(false); stat = addAttribute( aOutputGesture ); if (!stat) { stat.perror("addAttribute"); return stat;} aOutputFacialModel = typedAttr.create( "outputFacialModel", "ofm", NuiMayaFacialModelData::id, MObject::kNullObj, &stat ); if (!stat) { stat.perror("create outputFacialModel attribute"); return stat;} typedAttr.setWritable( false ); stat = addAttribute( aOutputFacialModel ); if (!stat) { stat.perror("addAttribute"); return stat;} aFaceRotateX = nAttr.create( "faceRotateX", "frX", MFnNumericData::kDouble, 0.0, &stat ); if (!stat) { stat.perror("create face rotateX attribute"); return stat;} nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); aFaceRotateY = nAttr.create( "faceRotateY", "frY", MFnNumericData::kDouble, 0.0, &stat ); if (!stat) { stat.perror("create face rotateY attribute"); return stat;} nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); aFaceRotateZ = nAttr.create( "faceRotateZ", "frZ", MFnNumericData::kDouble, 0.0, &stat ); if (!stat) { stat.perror("create rotateZ attribute"); return stat;} nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); aFaceRotate = nAttr.create( "faceRotate", "fr", aFaceRotateX, aFaceRotateY, aFaceRotateZ, &stat ); if (!stat) { stat.perror("create face rotate attribute"); return stat;} nAttr.setDefault(0.0f, 0.0f, 0.0f); nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); stat = addAttribute( aFaceRotate ); if (!stat) { stat.perror("addAttribute"); return stat;} aCameraRotateX = nAttr.create( "cameraRotateX", "crX", MFnNumericData::kDouble, 0.0, &stat ); if (!stat) { stat.perror("create cameraRotateX attribute"); return stat;} nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); aCameraRotateY = nAttr.create( "cameraRotateY", "crY", MFnNumericData::kDouble, 0.0, &stat ); if (!stat) { stat.perror("create rotateY attribute"); return stat;} nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); aCameraRotateZ = nAttr.create( "cameraRotateZ", "crZ", MFnNumericData::kDouble, 0.0, &stat ); if (!stat) { stat.perror("create rotateZ attribute"); return stat;} nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); aCameraRotate = nAttr.create( "cameraRotate", "cr", aCameraRotateX, aCameraRotateY, aCameraRotateZ, &stat ); if (!stat) { stat.perror("create cameraRotate attribute"); return stat;} nAttr.setDefault(0.0f, 0.0f, 0.0f); nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); stat = addAttribute( aCameraRotate ); if (!stat) { stat.perror("addAttribute"); return stat;} aCameraTranslateX = nAttr.create( "cameraTranslateX", "ctX", MFnNumericData::kDouble, 0.0, &stat ); if (!stat) { stat.perror("create cameraTranslateX attribute"); return stat;} nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); aCameraTranslateY = nAttr.create( "cameraTranslateY", "ctY", MFnNumericData::kDouble, 0.0, &stat ); if (!stat) { stat.perror("create cameraTranslateY attribute"); return stat;} nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); aCameraTranslateZ = nAttr.create( "cameraTranslateZ", "ctZ", MFnNumericData::kDouble, 0.0, &stat ); if (!stat) { stat.perror("create cameraTranslateZ attribute"); return stat;} nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); aCameraTranslate = nAttr.create( "cameraTranslate", "ct", aCameraTranslateX, aCameraTranslateY, aCameraTranslateZ, &stat ); if (!stat) { stat.perror("create cameraTranslate attribute"); return stat;} nAttr.setDefault(0.0f, 0.0f, 0.0f); nAttr.setReadable( true ); nAttr.setWritable( false ); nAttr.setStorable(true); stat = addAttribute( aCameraTranslate ); if (!stat) { stat.perror("addAttribute"); return stat;} // Set up a dependency between the input and the output. This will cause // the output to be marked dirty when the input changes. The output will // then be recomputed the next time the value of the output is requested. // stat = attributeAffects( aTime, aOutputMappable ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aOutputSkeleton ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aOutputFacialModel ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aFaceRotateX ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aFaceRotateY ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aFaceRotateZ ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aFaceRotate ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aCameraRotateX ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aCameraRotateY ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aCameraRotateZ ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aCameraRotate ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aCameraTranslateX ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aCameraTranslateY ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aCameraTranslateZ ); if (!stat) { stat.perror("attributeAffects"); return stat;} stat = attributeAffects( aTime, aCameraTranslate ); if (!stat) { stat.perror("attributeAffects"); return stat;} return MS::kSuccess; } /* override */ MStatus NuiMayaDeviceGrabber::connectionMade( const MPlug& plug, const MPlug& otherPlug, bool asSrc ) // // Description // // Whenever a connection is made to this node, this method // will get called. // { /*if ( plug == aOutputPointCloud ) { m_cacheFlags |= NuiDeviceBufferImpl::ECache_CLData; } else if ( plug == aOutputSkeleton ) { m_cacheFlags |= NuiDeviceBufferImpl::ECache_Skeleton; } else if ( plug == aOutputGesture ) { m_cacheFlags |= NuiDeviceBufferImpl::ECache_Gesture; } else if ( plug == aOutputFacialModel ) { m_cacheFlags |= NuiDeviceBufferImpl::ECache_Face; } if(m_pCache) m_pCache->SetFlags(m_cacheFlags);*/ return MPxNode::connectionMade( plug, otherPlug, asSrc ); } /* override */ MStatus NuiMayaDeviceGrabber::connectionBroken( const MPlug& plug, const MPlug& otherPlug, bool asSrc ) // // Description // // Whenever a connection to this node is broken, this method // will get called. // { bool bHasConnected = plug.isConnected(); /*if(!bHasConnected) { if ( plug == aOutputPointCloud ) { m_cacheFlags = ~(~m_cacheFlags | NuiDeviceBufferImpl::ECache_CLData); } else if ( plug == aOutputSkeleton ) { m_cacheFlags = ~(~m_cacheFlags | NuiDeviceBufferImpl::ECache_Skeleton); } else if ( plug == aOutputGesture ) { m_cacheFlags = ~(~m_cacheFlags | NuiDeviceBufferImpl::ECache_Gesture); } else if ( plug == aOutputFacialModel ) { m_cacheFlags = ~(~m_cacheFlags | NuiDeviceBufferImpl::ECache_Face); } if(m_pCache) m_pCache->SetFlags(m_cacheFlags); }*/ // When aOutputPointCloud connection lost, we should unlock any graphic/compute shared memory if (plug == aOutputMappable) { std::shared_ptr<NuiCLMappableData> clData = NuiMayaMappableData::findData(thisMObject(), aOutputMappable); if (clData) { clData->relaxToCPU(); } } return MPxNode::connectionBroken( plug, otherPlug, asSrc ); } MStatus NuiMayaDeviceGrabber::compute( const MPlug& plug, MDataBlock& datablock ) // // Description: // This method computes the value of the given output plug based // on the values of the input attributes. // // Arguments: // plug - the plug to compute // data - object that provides access to the attributes for this node // { assert(m_pCache); if(!m_pCache) return MS::kFailure; MStatus returnStatus; /* Get time */ MDataHandle timeData = datablock.inputValue( aTime, &returnStatus ); MCHECKERROR(returnStatus, "Error getting time data handle\n") MTime time = timeData.asTime(); //!< 30 frames per second int frame = (int)time.as( MTime::kNTSCFrame ) - 1;//Noted: The first frame in MAYA is 1; if(m_pDevice) { std::shared_ptr<NuiCompositeFrame> pFrame = m_pDevice->popFrame(); if(pFrame) { pFrame->m_depthFrame.SetMinDepth(getShortValue(aMinDepth)); pFrame->m_depthFrame.SetMaxDepth(getShortValue(aMaxDepth)); if(m_pSLAM /*&& m_pSLAM->m_tracker.isThreadOn()*/) { std::shared_ptr<NuiVisualFrame> pVisualFrame = std::make_shared<NuiVisualFrame>(); pVisualFrame->acquireFromCompositeFrame(pFrame.get()); m_pSLAM->m_tracker.pushbackFrame(pVisualFrame); pVisualFrame.reset(); } m_pCache->pushbackFrame(pFrame); pFrame.reset(); } } std::shared_ptr<NuiCompositeFrame> pCurrentFrame = m_pCache->getLatestFrame(); if ( plug == aOutputMappable ) { std::shared_ptr<NuiCLMappableData> clData(nullptr); MDataHandle outHandle = datablock.outputValue( aOutputMappable ); NuiMayaMappableData* clmData = static_cast<NuiMayaMappableData*>(outHandle.asPluginData()); if(!clmData) { // Create some user defined geometry data and access the // geometry so we can set it // MFnPluginData fnDataCreator; MTypeId tmpid( NuiMayaMappableData::id ); fnDataCreator.create( tmpid, &returnStatus ); MCHECKERROR( returnStatus, "compute : error creating mappableData") clmData = (NuiMayaMappableData*)fnDataCreator.data( &returnStatus ); MCHECKERROR( returnStatus, "compute : error gettin at proxy mappableData object") clData = std::shared_ptr<NuiCLMappableData>(new NuiCLMappableData()); clmData->setData(clData); returnStatus = outHandle.set( clmData ); MCHECKERROR( returnStatus, "compute : error gettin at proxy mappableData object") } else { clData = clmData->data(); } int indexFlags = getBooleanValue(aShowMesh) ? (NuiCLMappableData::E_MappableData_Triangle | NuiCLMappableData::E_MappableData_Wireframe) : NuiCLMappableData::E_MappableData_Point; bool bReceived = (m_pSLAM /*&& m_pSLAM->m_tracker.isThreadOn()*/) ? m_pSLAM->evaluateCLData(clData.get(), getBooleanValue(aShowMesh) ? NuiSLAMEngine::NuiSLAMController::eDraw_RealtimeMesh : NuiSLAMEngine::NuiSLAMController::eDraw_PointCloud) : NuiFrameUtilities::FrameToMappableData(pCurrentFrame.get(), clData.get(), indexFlags, getBooleanValue(aShowOnlyBody), 0.2f); datablock.setClean( plug ); } else if ( plug == aOutputMesh ) { NuiMeshShape mesh; bool bReceived = (m_pSLAM /*&& m_pSLAM->m_tracker.isThreadOn()*/) ? m_pSLAM->getMesh(&mesh) : NuiFrameUtilities::FrameToMesh(pCurrentFrame.get(), &mesh, getBooleanValue(aShowOnlyBody), 0.2f); // Create some mesh data and access the // geometry so we can set it // MFnMeshData dataCreator; MObject newOutputData = dataCreator.create(&returnStatus); MCHECKERROR(returnStatus, "ERROR creating outputData"); // If there is an input mesh then copy it's values // and construct some apiMeshGeom for it. // returnStatus = bReceived ? computeOutputMesh( &mesh, datablock, newOutputData) : MS::kFailure; if(returnStatus != MS::kSuccess) { createEmptyMesh( newOutputData ); } // Assign the new data to the outputSurface handle // MDataHandle outHandle = datablock.outputValue( aOutputMesh ); outHandle.set( newOutputData ); datablock.setClean( plug ); } else if ( plug == aOutputSkeleton || plug == aOutputGesture ) { if(pCurrentFrame) { MFnPluginData fnSkeletonDataCreator; MTypeId tmpSkeletonId( NuiMayaSkeletonData::id ); fnSkeletonDataCreator.create( tmpSkeletonId, &returnStatus ); MCHECKERROR( returnStatus, "compute : error creating skeleton data") NuiMayaSkeletonData * newSkeletonData = (NuiMayaSkeletonData*)fnSkeletonDataCreator.data( &returnStatus ); MCHECKERROR( returnStatus, "compute : error gettin at proxy skeleton data object") NuiSkeletonJoints* pSkeleton = newSkeletonData->m_pSkeletonData.get(); assert(pSkeleton); pSkeleton->SetInvalid(); MFnPluginData fnGestureDataCreator; MTypeId tmpGestureId( NuiMayaGestureData::id ); fnGestureDataCreator.create( tmpGestureId, &returnStatus ); MCHECKERROR( returnStatus, "compute : error creating gesture data") NuiMayaGestureData* newGestureData = (NuiMayaGestureData*)fnGestureDataCreator.data( &returnStatus ); MCHECKERROR( returnStatus, "compute : error gettin at proxy gesture data object") NuiGestureResult* pGesture = newGestureData->m_pGestureResult; assert(pGesture); for (UINT iBody = 0; iBody < pCurrentFrame->m_skeletonFrame.GetBodyCount(); ++iBody) { if( pCurrentFrame->m_skeletonFrame.ReadSkeleton(iBody, pSkeleton) ) { pCurrentFrame->m_gestureFrame.ReadGestureResult(iBody, pGesture); // Assign the first available skeleton. // break; } } MDataHandle outSkeletonHandle = datablock.outputValue( aOutputSkeleton ); outSkeletonHandle.set( newSkeletonData ); datablock.setClean( aOutputSkeleton ); MDataHandle outGestureHandle = datablock.outputValue( aOutputGesture ); outGestureHandle.set( newGestureData ); datablock.setClean( aOutputGesture ); } else { MGlobal::displayError( " Failed to acquire the frame from the cache." ); } } else if (plug == aOutputFacialModel) { if(pCurrentFrame) { // Create some user defined geometry data and access the // geometry so we can set it // MFnPluginData fnDataCreator; MTypeId tmpid( NuiMayaFacialModelData::id ); fnDataCreator.create( tmpid, &returnStatus ); MCHECKERROR( returnStatus, "compute : error creating faceData") NuiMayaFacialModelData * newData = (NuiMayaFacialModelData*)fnDataCreator.data( &returnStatus ); MCHECKERROR( returnStatus, "compute : error gettin at proxy face data object") NuiFacialModel* pFacialModel = newData->m_pFacialModel; assert(pFacialModel); for (UINT iBody = 0; iBody < pCurrentFrame->m_facialModelFrame.GetBodyCount(); ++iBody) { if( pCurrentFrame->m_facialModelFrame.ReadFacialModel(iBody, pFacialModel) ) { // Assign the first available facial model. // break; } } MDataHandle outHandle = datablock.outputValue( aOutputFacialModel ); outHandle.set( newData ); datablock.setClean( plug ); } else { MGlobal::displayError( " Failed to acquire the frame from the cache." ); } } else if(plug == aFaceRotate || plug == aFaceRotateX || plug == aFaceRotateY || plug == aFaceRotateZ ) { if(pCurrentFrame) { NuiTrackedFace face; for (UINT iBody = 0; iBody < pCurrentFrame->m_faceTrackingFrame.GetBodyCount(); ++iBody) { if( pCurrentFrame->m_faceTrackingFrame.ReadTrackedFace(iBody, &face) ) { // Assign the first available face. // double rotationXYZ[3]; face.GetRotationXYZ(&rotationXYZ[0], &rotationXYZ[1], &rotationXYZ[2]); MDataHandle otHandle = datablock.outputValue( aFaceRotate ); otHandle.set( rotationXYZ[0], rotationXYZ[1], rotationXYZ[2] ); break; } } datablock.setClean(aFaceRotate); } else { MGlobal::displayError( " Failed to acquire the frame from the cache." ); } } else if(plug == aCameraRotate || plug == aCameraRotateX || plug == aCameraRotateY || plug == aCameraRotateZ || plug == aCameraTranslate || plug == aCameraTranslateX || plug == aCameraTranslateY || plug == aCameraTranslateZ) { NuiCameraPos cam; bool received = false; if(pCurrentFrame) { //cam = pCurrentFrame->GetCameraParams(); received = true; } else if(m_pSLAM) { cam = m_pSLAM->m_tracker.getLatestCameraPose(); received = true; } if(received) { //Eigen::Quaternion<float> cameraRot (affine.rotation()); //double x = cameraRot.x(); //double y = cameraRot.y(); //double z = cameraRot.z(); //double w = cameraRot.w(); //// convert rotation quaternion to Euler angles in degrees //double pitch = atan2( 2 * ( y * z + w * x ), w * w - x * x - y * y + z * z ) / M_PI * 180.0; //double yaw = asin( 2 * ( w * y - x * z ) ) / M_PI * 180.0; //double roll = atan2( 2 * ( x * y + w * z ), w * w + x * x - y * y - z * z ) / M_PI * 180.0; //MDataHandle otHandle = datablock.outputValue( aCameraRotate ); //otHandle.set( pitch, yaw + 180.0, roll ); datablock.setClean(aCameraRotate); Vector3f trans = cam.getGlobalTranslation(); trans[2] = trans[2] - 4.0f; trans = cam.getRotation() * trans; MDataHandle otHandle = datablock.outputValue( aCameraTranslate ); otHandle.set( (double)trans[0], (double)-trans[1], (double)trans[2] ); datablock.setClean(aCameraTranslate); } } return returnStatus; } bool NuiMayaDeviceGrabber::updateDevice() { assert(m_pDevice); if(!m_pDevice) return false; MStatus returnStatus; MDataBlock datablock = forceCache(); bool bDeviceOn = false; MDataHandle inputHandle = datablock.inputValue( aDeviceOn, &returnStatus ); if(returnStatus == MS::kSuccess) bDeviceOn = inputHandle.asBool(); if(bDeviceOn) { short deviceMode = NuiRGBDDeviceController::EDeviceMode_DepthColor; MDataHandle inputHandle = datablock.inputValue( aDeviceMode, &returnStatus ); if(returnStatus == MS::kSuccess) deviceMode = inputHandle.asShort(); bool bUseCache = false; inputHandle = datablock.inputValue( aUseCache, &returnStatus ); if(returnStatus == MS::kSuccess) bUseCache = inputHandle.asBool(); if(bUseCache) { if( !m_pDevice->initializeFileLoader(sTestDataFolder) ) { MGlobal::displayError( " Failed to start the file Loader." ); return false; } } else { bool bKinfuOn = false; MDataHandle inputHandle = datablock.inputValue(aKinFuOn, &returnStatus); if (returnStatus == MS::kSuccess) bKinfuOn = inputHandle.asBool(); if (bKinfuOn) { deviceMode = NuiRGBDDeviceController::EDeviceMode_VertexColorCamera; } if( !m_pDevice->initializeDevice((DWORD)deviceMode) ) { MGlobal::displayError( " Failed to setup the device." ); return false; } } } else if(m_pDevice) { m_pDevice->stopDevice(); } return true; } void NuiMayaDeviceGrabber::updateaElevationAngle() { MStatus returnStatus; MDataBlock datablock = forceCache(); int elevationAngle = 0; MDataHandle inputHandle = datablock.inputValue( aElevationAngle, &returnStatus ); if(returnStatus == MS::kSuccess) elevationAngle = inputHandle.asInt(); if(m_pDevice) m_pDevice->UpdateElevationAngle(elevationAngle); } bool NuiMayaDeviceGrabber::updateNearMode() { MStatus returnStatus; MDataBlock datablock = forceCache(); bool bNearMode = false; MDataHandle inputHandle = datablock.inputValue( aNearMode, &returnStatus ); if(returnStatus == MS::kSuccess) bNearMode = inputHandle.asBool(); return (m_pDevice ? m_pDevice->UpdateNearMode(bNearMode) : false); } void NuiMayaDeviceGrabber::startPreviewer() { /*if(!m_pPreviewer) { m_pPreviewer = new NuiMayaCacheTimer(PreviewerCallingBack); } assert(m_pPreviewer); int interval = 100; m_pPreviewer->start(interval);*/ } void NuiMayaDeviceGrabber::stopPreviewer() { /*if(m_pPreviewer) { m_pPreviewer->stop(); }*/ } void NuiMayaDeviceGrabber::updatePreviewer() { MStatus returnStatus; MDataBlock datablock = forceCache(); bool bPreviewerOn = false; MDataHandle inputHandle = datablock.inputValue( aPreviewerOn, &returnStatus ); if(returnStatus == MS::kSuccess) bPreviewerOn = inputHandle.asBool(); updatePreviewRendererMode(); if(bPreviewerOn) startPreviewer(); else stopPreviewer(); } bool NuiMayaDeviceGrabber::updatePreviewRendererMode() { MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); if (!renderer) return false; NuiMayaPreviewerRenderOverride* renderOverrideInstance = (NuiMayaPreviewerRenderOverride*) renderer->findRenderOverride(NuiMayaPreviewerRenderOverride::kNuiPreviewerRendererName); if (!renderOverrideInstance) return false; int flags = NuiMayaPreviewerRenderOverride::EPreview_ColorMode; renderOverrideInstance->updatePreviewerMode((NuiMayaPreviewerRenderOverride::PreviewModeFlag)flags); return true; } void NuiMayaDeviceGrabber::PreviewerCallingBack(void* pVoid) { MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); if (!renderer) return; NuiMayaPreviewerRenderOverride* renderOverrideInstance = (NuiMayaPreviewerRenderOverride*) renderer->findRenderOverride(NuiMayaPreviewerRenderOverride::kNuiPreviewerRendererName); if (!renderOverrideInstance) return; NuiFrameCacheImpl* pCache = reinterpret_cast<NuiFrameCacheImpl*>(pVoid); if (!pCache) return; if( renderOverrideInstance->updatePreviewerTexture(pCache) ) renderOverrideInstance->refreshView(); } void NuiMayaDeviceGrabber::updateKinfu() { if(!m_pDevice) return; MStatus returnStatus; MDataBlock datablock = forceCache(); bool bKinfuOn = false; MDataHandle inputHandle = datablock.inputValue( aKinFuOn, &returnStatus ); if(returnStatus == MS::kSuccess) bKinfuOn = inputHandle.asBool(); if(bKinfuOn) { if(!m_pSLAM) { if(!m_pSLAM) m_pSLAM = new NuiSLAMEngine::NuiSLAMController(); m_pSLAM->m_tracker.pauseThread(); float voxelSize = 0.01f; inputHandle = datablock.inputValue( aVolumeVoxelSize, &returnStatus ); if(returnStatus == MS::kSuccess) voxelSize = inputHandle.asFloat(); m_pSLAM->setVolume(voxelSize, NuiSLAMEngine::NuiSLAMController::eScene_FusionVolume); m_pSLAM->m_tracker.startThread(); } } else { SafeDelete(m_pSLAM); } } bool NuiMayaDeviceGrabber::getBooleanValue(const MObject &attribute) { MDataBlock block = forceCache(); MDataHandle handle = block.inputValue(attribute); return handle.asBool(); } UINT16 NuiMayaDeviceGrabber::getShortValue(const MObject &attribute) { MDataBlock block = forceCache(); MDataHandle handle = block.inputValue(attribute); return handle.asShort(); } void NuiMayaDeviceGrabber::createEmptyMesh( MObject& out_empytMesh ) { MStatus status; MFnMeshData meshData; out_empytMesh = meshData.create( &status ); CHECK_MSTATUS( status ); MFloatPointArray vertexArray; MIntArray polygonCounts; MIntArray polygonConnects; MFnMesh meshCreator; MObject newMeshObject = meshCreator.create( 0, // nb vertices 0, // nb triangles vertexArray, polygonCounts, polygonConnects, out_empytMesh ); } MStatus NuiMayaDeviceGrabber::assignMeshUV( MObject& meshData, const MIntArray& polygonCounts, const MIntArray& uvIds ) { MStatus stat = MS::kSuccess; MString uvSetName("uvset1"); MFnMesh meshFn(meshData); stat = meshFn.getCurrentUVSetName(uvSetName); if ( stat != MS::kSuccess ) { uvSetName = MString ("uvset1"); stat = meshFn.createUVSet(uvSetName); stat = meshFn.setCurrentUVSetName(uvSetName); } //stat = meshFn.clearUVs(); //stat = meshFn.setUVs(uArray,vArray,&uvSetName); stat = meshFn.assignUVs(polygonCounts, uvIds, &uvSetName); if(stat != MS::kSuccess) MGlobal::displayError( " Failed to assign UVs." ); return stat; } MStatus NuiMayaDeviceGrabber::computeOutputMesh( NuiMeshShape* pMesh, MDataBlock& datablock, MObject& meshData) // // Description // // This function takes an input surface of type kMeshData and converts // the geometry into this nodes attributes. // Returns kFailure if nothing is connected. // { if ( NULL == pMesh ) { cerr << "NULL pointCloudGeom found\n"; return MS::kFailure; } double distanceUnit = 1.0; MDistance::Unit currentUnit = MDistance::internalUnit(); if(currentUnit != MDistance::kInvalid) { distanceUnit = MDistance(1.0, MDistance::kMeters).as(currentUnit); } else { MGlobal::displayError( " Invalid distance unit." ); return MS::kFailure; } MFloatPointArray vertexArray; MIntArray polygonCounts; MIntArray polygonConnects; MFloatArray uArray; MFloatArray vArray; MColorArray colorArray; MIntArray vertexIndices; const UINT numPoints = (UINT)pMesh->pointsNum(); for (UINT i = 0; i < numPoints; ++i) { const SgVec3f& pt = pMesh->getPoint(i); MPoint pnt(pt[0], pt[1], pt[2]); vertexArray.append(pnt); SgVec2f uv = pMesh->getUV(i); uArray.append(uv[0]); vArray.append(uv[1]); SgVec3f color = pMesh->getColor(i); colorArray.append(color[0], color[1], color[2]); vertexIndices.append(i); } const UINT numTris = (UINT)pMesh->trianglesNum(); for (UINT i = 0; i < numTris; ++i) { int index1 = pMesh->triangleIndex(3*i); int index2 = pMesh->triangleIndex(3*i+1); int index3 = pMesh->triangleIndex(3*i+2); if(index1 < 0 || index1 >= (int)numPoints || index2 < 0 || index2 >= (int)numPoints || index3 < 0 || index3 >= (int)numPoints) continue; polygonConnects.append(index1); polygonConnects.append(index2); polygonConnects.append(index3); polygonCounts.append(3); } MStatus stat; MFnMesh meshFn; meshFn.create(vertexArray.length(), polygonCounts.length(), vertexArray, polygonCounts, polygonConnects, uArray, vArray, meshData, &stat); meshFn.setVertexColors(colorArray, vertexIndices); bool needAssignUV = true; /*MDataHandle inputHandle = datablock.inputValue( aAssignUV, &stat ); if(stat == MS::kSuccess) needAssignUV = inputHandle.asBool();*/ if(needAssignUV) // assignMeshUV(meshData, polygonCounts, polygonConnects); { MString uvSetName("uvset1"); MFnMesh meshFn(meshData); stat = meshFn.getCurrentUVSetName(uvSetName); if ( stat != MS::kSuccess ) { uvSetName = MString ("uvset1"); stat = meshFn.createUVSet(uvSetName); stat = meshFn.setCurrentUVSetName(uvSetName); } stat = meshFn.clearUVs(); stat = meshFn.setUVs(uArray,vArray,&uvSetName); stat = meshFn.assignUVs(polygonCounts, polygonConnects, &uvSetName); if(stat != MS::kSuccess) MGlobal::displayError( " Failed to assign UVs." ); } return stat; }
34.549259
182
0.707858
[ "mesh", "geometry", "object", "shape", "model" ]
c3dde5d9bf869d279d92b0058feed6e2c066e5d2
20,166
cpp
C++
WaveletTL/ring/ring_basis.cpp
kedingagnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
3
2018-05-20T15:25:58.000Z
2021-01-19T18:46:48.000Z
WaveletTL/ring/ring_basis.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
null
null
null
WaveletTL/ring/ring_basis.cpp
agnumerikunimarburg/Marburg_Software_Library
fe53c3ae9db23fc3cb260a735b13a1c6d2329c17
[ "MIT" ]
2
2019-04-24T18:23:26.000Z
2020-09-17T10:00:27.000Z
// implementation for ring_basis.h #include <set> #include <numerics/quadrature.h> #include <numerics/iteratsolv.h> #include <algebra/sparse_matrix.h> #include <algebra/kronecker_matrix.h> using MathTL::KroneckerMatrix; namespace WaveletTL { template <int d, int dt, int s0, int s1> RingBasis<d,dt,s0,s1>::RingBasis(const double r0, const double r1) : r0_(r0), r1_(r1), chart_(r0,r1) { } template <int d, int dt, int s0, int s1> typename RingBasis<d,dt,s0,s1>::Index RingBasis<d,dt,s0,s1>::first_generator(const int j) { assert(j >= j0()); typename Index::type_type e; typename Index::translation_type k (PeriodicBasis<CDFBasis<d,dt> >::DeltaLmin(), SplineBasis<d,dt,P_construction,s0,s1,0,0,SplineBasisData_j0<d,dt,P_construction,s0,s1,0,0>::j0>::DeltaLmin()); return Index(j, e, k); } template <int d, int dt, int s0, int s1> typename RingBasis<d,dt,s0,s1>::Index RingBasis<d,dt,s0,s1>::last_generator(const int j) { assert(j >= j0()); typename Index::type_type e; typename Index::translation_type k (PeriodicBasis<CDFBasis<d,dt> >::DeltaRmax(j), SplineBasis<d,dt,P_construction,s0,s1,0,0,SplineBasisData_j0<d,dt,P_construction,s0,s1,0,0>::j0>::DeltaRmax(j)); return Index(j, e, k); } template <int d, int dt, int s0, int s1> typename RingBasis<d,dt,s0,s1>::Index RingBasis<d,dt,s0,s1>::first_wavelet(const int j) { assert(j >= j0()); typename Index::type_type e(0, 1); typename Index::translation_type k (PeriodicBasis<CDFBasis<d,dt> >::DeltaLmin(), SplineBasis<d,dt,P_construction,s0,s1,0,0,SplineBasisData_j0<d,dt,P_construction,s0,s1,0,0>::j0>::Nablamin()); return Index(j, e, k); } template <int d, int dt, int s0, int s1> typename RingBasis<d,dt,s0,s1>::Index RingBasis<d,dt,s0,s1>::last_wavelet(const int j) { assert(j >= j0()); typename Index::type_type e(1, 1); typename Index::translation_type k (PeriodicBasis<CDFBasis<d,dt> >::Nablamax(j), SplineBasis<d,dt,P_construction,s0,s1,0,0,SplineBasisData_j0<d,dt,P_construction,s0,s1,0,0>::j0>::Nablamax(j)); return Index(j, e, k); } template <int d, int dt, int s0, int s1> inline int RingBasis<d,dt,s0,s1>::Deltasize(const int j) { assert(j >= j0()); return Basis0::Deltasize(j) * Basis1::Deltasize(j); } template <int d, int dt, int s0, int s1> inline int RingBasis<d,dt,s0,s1>::Nabla01size(const int j) { assert(j >= j0()); return Basis0::Deltasize(j) * (1<<j); } template <int d, int dt, int s0, int s1> inline int RingBasis<d,dt,s0,s1>::Nabla10size(const int j) { assert(j >= j0()); return Basis1::Deltasize(j) * (1<<j); } template <int d, int dt, int s0, int s1> inline int RingBasis<d,dt,s0,s1>::Nabla11size(const int j) { assert(j >= j0()); return 1<<(2*j); } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Mj0(const int j, const V& x, V& y, const size_type x_offset, const size_type y_offset, const bool add_to) const { basis0_.Mj0_.set_level(j); basis1_.Mj0_.set_level(j); KroneckerHelper<double, typename Basis0::QuasiStationaryMatrixType, typename Basis1::QuasiStationaryMatrixType> K(basis0_.Mj0_, basis1_.Mj0_); K.apply(x, y, x_offset, y_offset, add_to); } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Mj1_01(const int j, const V& x, V& y, const size_type x_offset, const size_type y_offset, const bool add_to) const { basis0_.Mj0_.set_level(j); basis1_.Mj1_.set_level(j); KroneckerHelper<double, typename Basis0::QuasiStationaryMatrixType, typename Basis1::QuasiStationaryMatrixType> K(basis0_.Mj0_, basis1_.Mj1_); K.apply(x, y, x_offset, y_offset, add_to); } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Mj1_10(const int j, const V& x, V& y, const size_type x_offset, const size_type y_offset, const bool add_to) const { basis0_.Mj1_.set_level(j); basis1_.Mj0_.set_level(j); KroneckerHelper<double, typename Basis0::QuasiStationaryMatrixType, typename Basis1::QuasiStationaryMatrixType> K(basis0_.Mj1_, basis1_.Mj0_); K.apply(x, y, x_offset, y_offset, add_to); } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Mj1_11(const int j, const V& x, V& y, const size_type x_offset, const size_type y_offset, const bool add_to) const { basis0_.Mj1_.set_level(j); basis1_.Mj1_.set_level(j); KroneckerHelper<double, typename Basis0::QuasiStationaryMatrixType, typename Basis1::QuasiStationaryMatrixType> K(basis0_.Mj1_, basis1_.Mj1_); K.apply(x, y, x_offset, y_offset, add_to); } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Mj0T_transposed(const int j, const V& x, V& y, const size_type x_offset, const size_type y_offset, const bool add_to) const { basis0_.Mj0T_.set_level(j); basis1_.Mj0T_.set_level(j); KroneckerHelper<double, typename Basis0::QuasiStationaryMatrixType, typename Basis1::QuasiStationaryMatrixType> K(basis0_.Mj0T_, basis1_.Mj0T_); K.apply_transposed(x, y, x_offset, y_offset, add_to); } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Mj1T_01_transposed(const int j, const V& x, V& y, const size_type x_offset, const size_type y_offset, const bool add_to) const { basis0_.Mj0T_.set_level(j); basis1_.Mj1T_.set_level(j); KroneckerHelper<double, typename Basis0::QuasiStationaryMatrixType, typename Basis1::QuasiStationaryMatrixType> K(basis0_.Mj0T_, basis1_.Mj1T_); K.apply_transposed(x, y, x_offset, y_offset, add_to); } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Mj1T_10_transposed(const int j, const V& x, V& y, const size_type x_offset, const size_type y_offset, const bool add_to) const { basis0_.Mj1T_.set_level(j); basis1_.Mj0T_.set_level(j); KroneckerHelper<double, typename Basis0::QuasiStationaryMatrixType, typename Basis1::QuasiStationaryMatrixType> K(basis0_.Mj1T_, basis1_.Mj0T_); K.apply_transposed(x, y, x_offset, y_offset, add_to); } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Mj1T_11_transposed(const int j, const V& x, V& y, const size_type x_offset, const size_type y_offset, const bool add_to) const { basis0_.Mj1T_.set_level(j); basis1_.Mj1T_.set_level(j); KroneckerHelper<double, typename Basis0::QuasiStationaryMatrixType, typename Basis1::QuasiStationaryMatrixType> K(basis0_.Mj1T_, basis1_.Mj1T_); K.apply_transposed(x, y, x_offset, y_offset, add_to); } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Mj(const int j, const V& x, V& y) const { // decompose x appropriately apply_Mj0 (j, x, y, 0, 0, false); // apply Mj0 apply_Mj1_01(j, x, y, Deltasize(j), 0, true); // apply Mj1, e=(0,1) apply_Mj1_10(j, x, y, Deltasize(j)+Nabla01size(j), 0, true); // apply Mj1, e=(1,0) apply_Mj1_11(j, x, y, Deltasize(j)+Nabla01size(j)+Nabla10size(j), 0, true); // apply Mj1, e=(1,1) } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Gj(const int j, const V& x, V& y) const { // write into the block vector y apply_Mj0T_transposed (j, x, y, 0, 0, false); // write Mj0T block apply_Mj1T_01_transposed(j, x, y, 0, Deltasize(j), false); // write Mj1T block, e=(0,1) apply_Mj1T_10_transposed(j, x, y, 0, Deltasize(j)+Nabla01size(j), false); // write Mj1T block, e=(1,0) apply_Mj1T_11_transposed(j, x, y, 0, Deltasize(j)+Nabla01size(j)+Nabla10size(j), false); // write Mj1T block, e=(1,1) } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Tj(const int j, const V& x, V& y) const { y = x; V z(x); apply_Mj(j0(), z, y); for (int k = j0()+1; k <= j; k++) { apply_Mj(k, y, z); y.swap(z); } } template <int d, int dt, int s0, int s1> template <class V> void RingBasis<d,dt,s0,s1>::apply_Tjinv(const int j, const V& x, V& y) const { // T_j^{-1}=diag(G_{j0},I)*...*diag(G_{j-1},I)*G_j V z(x); apply_Gj(j, x, y); for (int k = j-1; k >= j0(); k--) { z.swap(y); apply_Gj(k, z, y); for (int i = Deltasize(k+1); i < Deltasize(j+1); i++) y[i] = z[i]; } } // // // point evaluation subroutines template <int d, int dt, int s0, int s1> SampledMapping<2> RingBasis<d,dt,s0,s1>::evaluate(const typename RingBasis<d,dt,s0,s1>::Index& lambda, const int resolution) const { FixedArray1D<Array1D<double>,2> values; // point values of the factors within psi_lambda values[0] = basis0_.evaluate(Index0(lambda.j(), lambda.e()[0], lambda.k()[0]), resolution).values(); values[1] = basis1_.evaluate(Index1(lambda.j(), lambda.e()[1], lambda.k()[1]), resolution).values(); // adjust "radial" values by the normalization factor const double help = sqrt(2*M_PI*(r1_-r0_)); for (unsigned int i = 0; i < values[1].size(); i++) { values[1][i] /= help*sqrt(r0_+i*ldexp(1.0, -resolution)*(r1_-r0_)); } SampledMapping<2> result(Point<2>(0), Point<2>(1), values); return result; // gcc 2.95 does not like these two lines melted into one } template <int d, int dt, int s0, int s1> SampledMapping<2> RingBasis<d,dt,s0,s1>::evaluate(const InfiniteVector<double, typename RingBasis<d,dt,s0,s1>::Index>& coeffs, const int resolution) const { Grid<2> grid(Point<2>(0), Point<2>(1), 1<<resolution); SampledMapping<2> result(grid); // zero typedef typename RingBasis<d,dt,s0,s1>::Index Index; for (typename InfiniteVector<double,Index>::const_iterator it(coeffs.begin()), itend(coeffs.end()); it != itend; ++it) result.add(*it, evaluate(it.index(), resolution)); return result; } // // // expansion subroutines template <int d, int dt, int s0, int s1> void RingBasis<d,dt,s0,s1>::expand(const Function<2>* f, const bool primal, const int jmax, InfiniteVector<double, Index>& coeffs) const { typedef typename RingBasis<d,dt,s0,s1>::Index Index; coeffs.clear(); for (Index lambda = first_generator(j0());;++lambda) { double integral = integrate(f, lambda); if (fabs(integral) < 1e-15) integral = 0; coeffs.set_coefficient(lambda, integral); if (lambda == last_wavelet(jmax)) break; } if (!primal) { // In the following, we setup the Gramian matrix A_Lambda, using all wavelets // up to the maximal level jmax. By the tensor product structure of the basis, // the entries of A_Lambda can be written as product of 1D integrals: // int_R psi_lambda(x) psi_mu(x) dx // = 2*pi * int_{r0}^{r1} int_0^1 psi_lambda(x) psi_mu(x) dphi r dr // = 2*pi*(r1-r0) * int_0^1 int_0^1 psi_lambda(x) psi_mu(x) dphi (r0+s*(r1-r0)) ds // with x=x(s,phi)=r(s)*(cos(2*pi*phi),sin(2*pi*phi)), r(s)=r0+s*(r1-r0). // Note that A_Lambda is not exactly a Kronecker product of the 1D Gramians, // since the order of 2D indices is defined somehow diffently. // Note also that due to the normalization of the mapped // wavelets, it suffices to compute the (1D) integrals // int_0^1 int_0^1 psi^0_lambda(phi,s) psi^0_mu(phi,s) dphi ds, // since both the 2*pi*(r1-r0) and the r(s) completely cancel out. typedef typename SparseMatrix<double>::size_type size_type; // setup active wavelet index set std::set<Index> Lambda; for (Index lambda = first_generator(j0());; ++lambda) { Lambda.insert(lambda); if (lambda == last_wavelet(jmax)) break; } // cout << "active index set:" << endl; // for (typename std::set<Index>::const_iterator it(Lambda.begin()), itend(Lambda.end()); // it != itend; ++it) // cout << *it << endl; // setup global Gramian A_Lambda SparseMatrix<double> A_Lambda(Lambda.size()); size_type row = 0; for (typename std::set<Index>::const_iterator it1(Lambda.begin()), itend(Lambda.end()); it1 != itend; ++it1, ++row) { std::list<size_type> indices; std::list<double> entries; size_type column = 0; for (typename std::set<Index>::const_iterator it2(Lambda.begin()); it2 != itend; ++it2, ++column) { double entry = integrate(*it2, *it1); if (fabs(entry) > 1e-15) { indices.push_back(column); entries.push_back(entry); } } A_Lambda.set_row(row, indices, entries); } // solve A_Lambda*x = b Vector<double> b(A_Lambda.row_dimension()); row = 0; for (Index lambda = first_generator(j0());; ++lambda, ++row) { b[row] = coeffs.get_coefficient(lambda); if (lambda == last_wavelet(jmax)) break; } // cout << "b=" << b << endl; Vector<double> x(b); unsigned int iterations; CG(A_Lambda, b, x, 1e-15, 500, iterations); coeffs.clear(); row = 0; for (typename std::set<Index>::const_iterator it(Lambda.begin()), itend(Lambda.end()); it != itend; ++it, ++row) { if (fabs(x[row]) > 1e-15) coeffs.set_coefficient(*it, x[row]); } } } template <int d, int dt, int s0, int s1> void RingBasis<d,dt,s0,s1>::expand(const Function<2>* f, const bool primal, const int jmax, Vector<double>& coeffs) const { InfiniteVector<double,Index> help; expand(f, primal, jmax, help); coeffs.resize(Deltasize(jmax+1)); for (typename InfiniteVector<double,Index>::const_iterator it(help.begin()); it != help.end(); ++it) coeffs[it.index().number()] = *it; } template <int d, int dt, int s0, int s1> double RingBasis<d,dt,s0,s1>::integrate (const Function<2>* f, const typename RingBasis<d,dt,s0,s1>::Index& lambda) const { // We have to compute // int_R f(x) psi_lambda(x) dx // = 2*pi * int_{r0}^{r1} int_0^1 f(x) psi_lambda(x) dphi r dr // = 2*pi*(r1-r0) * int_0^1 int_0^1 f(x(s,phi)) psi_lambda(x(s,phi)) dphi (r0+s*(r1-r0)) ds // with x=x(s,phi)=r(s)*(cos(2*pi*phi),sin(2*pi*phi)), r(s)=r0+s*(r1-r0). // Note that due to the normalization of the mapped // wavelets, it suffices to compute the integrals // sqrt(2*pi*(r1-r0)) int_0^1 int_0^1 f(x(s,phi)) psi^0_lambda(s,phi) dphi sqrt(r0+s*(r1-r0)) ds. double r = 0; // first compute supp(psi_lambda) const unsigned int jplus = multi_degree(lambda.e()) > 0 ? 1 : 0; int j = lambda.j() + jplus; int k1[2], k2[2], length[2]; basis0_.support(Index0(lambda.j(), lambda.e()[0], lambda.k()[0]), k1[0], k2[0]); basis1_.support(Index1(lambda.j(), lambda.e()[1], lambda.k()[1]), k1[1], k2[1]); if (jplus > 0) { // in case of a wavelet, adjust the granularity of eventual generator factors for (int i = 0; i < 2; i++) { if (lambda.e()[i] == 0) { k1[i] *= 2; k2[i] *= 2; } } } length[0] = (k2[0] > k1[0] ? k2[0]-k1[0] : k2[0]+(1<<j)-k1[0]); // number of "angular" subintervals length[1] = k2[1]-k1[1]; // cout << "RingBasis::integrate() called with lambda=" << lambda // << ", j=" << j // << ", k1[0]=" << k1[0] // << ", k2[0]=" << k2[0] // << ", k1[1]=" << k1[1] // << ", k2[1]=" << k2[1] // << endl; // setup Gauss points and weights for a composite quadrature formula: const int N_Gauss = 7; const double h = 1.0/(1<<j); // granularity for the quadrature FixedArray1D<Array1D<double>,2> gauss_points, gauss_weights, v_values; for (int i = 0; i < 2; i++) { const unsigned int lengthi = N_Gauss*length[i]; gauss_points[i].resize(lengthi); gauss_weights[i].resize(lengthi); v_values[i].resize(lengthi); } // angular direction int k = k1[0]; for (int patch = 0; patch < length[0]; patch++, k = dyadic_modulo(++k,j)) // work on 2^{-j}[k,k+1] for (int n = 0; n < N_Gauss; n++) { gauss_points[0][patch*N_Gauss+n] = h*(2*k+1+GaussPoints[N_Gauss-1][n])/2; gauss_weights[0][patch*N_Gauss+n] = h*GaussWeights[N_Gauss-1][n]; } // cout << "angular Gauss points: " << gauss_points[0] << endl; // cout << "angular Gauss weights: " << gauss_weights[0] << endl; // radial direction for (int patch = k1[1]; patch < k2[1]; patch++) for (int n = 0; n < N_Gauss; n++) { gauss_points[1][(patch-k1[1])*N_Gauss+n] = h*(2*patch+1+GaussPoints[N_Gauss-1][n])/2.; gauss_weights[1][(patch-k1[1])*N_Gauss+n] = h*GaussWeights[N_Gauss-1][n]; } // cout << "radial Gauss points: " << gauss_points[1] << endl; // cout << "radial Gauss weights: " << gauss_weights[1] << endl; // compute the point values of the wavelet (where we use that it is a tensor product) v_values[0].resize(gauss_points[0].size()); v_values[1].resize(gauss_points[1].size()); basis0_.evaluate(0, Index0(lambda.j(), lambda.e()[0], lambda.k()[0]), gauss_points[0], v_values[0]); basis1_.evaluate(0, Index1(lambda.j(), lambda.e()[1], lambda.k()[1]), gauss_points[1], v_values[1]); // cout << "angular point values of psi_lambda: " << v_values[0] << endl; // cout << "radial point values of psi_lambda: " << v_values[1] << endl; // iterate over all points, evaluate f, and sum up the integral shares int index[2]; // current multiindex for the point values for (unsigned int i = 0; i < 2; i++) index[i] = 0; Point<2> x; Point<2> x_ring; while (true) { // read (phi,s) for (unsigned int i = 0; i < 2; i++) x[i] = gauss_points[i][index[i]]; // map x into the ring chart_.map_point(x, x_ring); // compute integral share double share = f->value(x_ring) * chart_.Gram_factor(x); // sqrt(2*pi*(r1-r0))*f(x)*sqrt(r(s)) for (unsigned int i = 0; i < 2; i++) share *= gauss_weights[i][index[i]] * v_values[i][index[i]]; r += share; // "++index" bool exit = false; for (unsigned int i = 0; i < 2; i++) { if (index[i] == N_Gauss*length[i]-1) { index[i] = 0; exit = (i == 1); } else { index[i]++; break; } } if (exit) break; } return r; } template <int d, int dt, int s0, int s1> inline double RingBasis<d,dt,s0,s1>::integrate(const Index& lambda, const Index& mu) const { return basis0_.integrate(Index0(lambda.j(), lambda.e()[0], lambda.k()[0]), Index0(mu.j(), mu.e()[0], mu.k()[0])) * basis1_.integrate(Index1(lambda.j(), lambda.e()[1], lambda.k()[1]), Index1(mu.j(), mu.e()[1], mu.k()[1])); } template <int d, int dt, int s0, int s1> void RingBasis<d,dt,s0,s1>::setup_full_collection() { if (jmax_ == -1 || jmax_ < j0()) { cout << "RingBasis::setup_full_collection(): specify a maximal level of resolution first!" << endl; abort(); } int degrees_of_freedom = Deltasize(jmax_+1); cout << "total degrees of freedom between j0 and jmax_ is " << degrees_of_freedom << endl; cout << "setting up collection of wavelet indices..." << endl; full_collection.resize(degrees_of_freedom); int k = 0; for (Index ind = first_generator(j0()); ind <= last_wavelet(jmax_); ++ind) { //cout << ind << " " << ind.number() << endl; full_collection[k] = ind; k++; } cout << "done setting up collection of wavelet indices..." << endl; } }
33.554077
121
0.611128
[ "vector" ]
c3e2da45f1efa5e92223b048b645d3ea2a32662d
2,255
cpp
C++
leetcode-problems/easy-125-valid-palindrome.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/easy-125-valid-palindrome.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
leetcode-problems/easy-125-valid-palindrome.cpp
formatkaka/dsalgo
a7c7386c5c161e23bc94456f93cadd0f91f102fa
[ "Unlicense" ]
null
null
null
// // Created by Siddhant on 2019-09-10. // #include "iostream" #include "vector" #include "string" using namespace std; int main(){ string input = ".,,ab"; auto inputStart = input.begin(); auto inputEnd = input.end() - 1; while(inputStart < inputEnd){ /* Added while loops below because I didn't want the if condition to * be executed until I reach a valid character in the string * * Another way to write this is * * while(start<end) { * if (!isalnum(s[start])) start++; * else if (!isalnum(s[end])) end--; * else { * ... * ... * } * } * * Ref - https://leetcode.com/problems/valid-palindrome/discuss/40261/Passed-clean-c%2B%2B-code * */ while(!isalnum(*inputStart) && inputStart < inputEnd){ inputStart++; } while(!isalnum(*inputEnd) && inputStart < inputEnd){ inputEnd--; } bool isValidPalindromeTillNow = tolower(*inputStart) == tolower(*inputEnd); if(!isValidPalindromeTillNow) { return 0; } inputStart++; inputEnd--; } return 1; } // // Created by Siddhant on 2019-09-10. // // //#include "iostream" //#include "vector" //#include "string" // //using namespace std; // //int main(){ // // string input = ".aab"; // // // string middle = ""; // // for (auto str = input.begin(); str != input.end(); ++str) { // if(!isalnum(*str)) continue; // // middle = middle + *str; // } // // auto inputStart = middle.begin(); // auto inputEnd = middle.end() - 1; // // while(inputStart < inputEnd){ // // cout << "inputStart : " << *inputStart << endl; // cout << "inputEnd : " << *inputEnd << endl; // // // bool isValidPalindromeTillNow = tolower(*inputStart) == tolower(*inputEnd); // // // if(!isValidPalindromeTillNow) { // return 0; // } // // inputStart++; // inputEnd--; // // } // // // // return 1; //}
20.5
108
0.473614
[ "vector" ]
c3e710c27fafa1800a5b552f1c398631fa7c0ca1
2,824
cpp
C++
WonderBrush/src/tools/filters/SimpleBrightness.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
11
2018-11-10T11:14:11.000Z
2021-12-27T17:17:08.000Z
WonderBrush/src/tools/filters/SimpleBrightness.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
27
2018-11-11T00:06:25.000Z
2021-06-24T06:43:38.000Z
WonderBrush/src/tools/filters/SimpleBrightness.cpp
waddlesplash/WonderBrush-v2
df20b6a43115d02e4606c71f27d0712ac2aebb62
[ "MIT" ]
7
2018-11-10T20:32:49.000Z
2021-03-15T18:03:42.000Z
// SimpleBrightness.cpp #include <math.h> #include <stdio.h> #include <string.h> #include <Bitmap.h> #include <Message.h> #include "bitmap_compression.h" #include "bitmap_support.h" #include "blending.h" #include "defines.h" #include "support.h" #include "CommonPropertyIDs.h" #include "FilterFactory.h" #include "FloatProperty.h" #include "PropertyObject.h" #include "SimpleBrightness.h" // constructor SimpleBrightness::SimpleBrightness() : FilterObject(FILTER_SIMPLE_BRIGHTNESS), fBrightness(1.0) { } // copy constructor SimpleBrightness::SimpleBrightness(const SimpleBrightness& other) : FilterObject(other), fBrightness(other.fBrightness) { } // BArchivable constructor SimpleBrightness::SimpleBrightness(BMessage* archive) : FilterObject(archive), fBrightness(1.0) { if (!archive || archive->FindFloat("brightness", &fBrightness) < B_OK) { fBrightness = 1.0; SetFilterID(FILTER_SIMPLE_BRIGHTNESS); } } // destructor SimpleBrightness::~SimpleBrightness() { } // Clone Stroke* SimpleBrightness::Clone() const { return new SimpleBrightness(*this); } // SetTo bool SimpleBrightness::SetTo(const Stroke* from) { const SimpleBrightness* simpleBrightness = dynamic_cast<const SimpleBrightness*>(from); AutoNotificationSuspender _(this); if (simpleBrightness && FilterObject::SetTo(from)) { fBrightness = simpleBrightness->fBrightness; Notify(); return true; } return false; } // Instantiate BArchivable* SimpleBrightness::Instantiate(BMessage* archive) { if (validate_instantiation(archive, "SimpleBrightness")) return new SimpleBrightness(archive); return NULL; } // Archive status_t SimpleBrightness::Archive(BMessage* into, bool deep) const { status_t status = FilterObject::Archive(into, deep); if (status >= B_OK) status = into->AddFloat("brightness", fBrightness); // finish off if (status >= B_OK) status = into->AddString("class", "SimpleBrightness"); return status; } // ProcessBitmap void SimpleBrightness::ProcessBitmap(BBitmap* dest, BBitmap* strokeBitmap, BRect area) const { uint8 table[256]; for (int32 i = 0; i < 256; i++) { table[i] = min_c(255, (uint32)floorf(i * fBrightness + 0.5)); } remap_colors(dest, area, table); } // MakePropertyObject PropertyObject* SimpleBrightness::MakePropertyObject() const { PropertyObject* object = new PropertyObject(); object->AddProperty(new FloatProperty("brightness", PROPERTY_BRIGHTNESS, fBrightness, 0.0, 255.0)); return object; } // SetToPropertyObject bool SimpleBrightness::SetToPropertyObject(PropertyObject* object) { bool ret = false; if (object) { float f = object->FindFloatProperty(PROPERTY_BRIGHTNESS, fBrightness); if (f != fBrightness) ret = true; fBrightness = f; if (ret) { SaveSettings(); Notify(); } } return ret; }
19.611111
88
0.725212
[ "object" ]
c3efafe574b19f17e3a65d1610958e4b782c58e2
3,563
hpp
C++
src/libraries/regionModels/surfaceFilmModels/submodels/kinematic/injectionModel/drippingInjection/drippingInjection.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/regionModels/surfaceFilmModels/submodels/kinematic/injectionModel/drippingInjection/drippingInjection.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/regionModels/surfaceFilmModels/submodels/kinematic/injectionModel/drippingInjection/drippingInjection.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2018 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::regionModels::surfaceFilmModels::drippingInjection Description Film Dripping mass transfer model. If the film mass exceeds that needed to generate a valid parcel, the equivalent mass is removed from the film. New parcel diameters are sampled from a PDF. SourceFiles drippingInjection.C \*---------------------------------------------------------------------------*/ #ifndef drippingInjection_H #define drippingInjection_H #include "injectionModel.hpp" #include "distributionModel.hpp" #include "Random.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { namespace regionModels { namespace surfaceFilmModels { /*---------------------------------------------------------------------------*\ Class drippingInjection Declaration \*---------------------------------------------------------------------------*/ class drippingInjection : public injectionModel { private: // Private member functions //- Disallow default bitwise copy construct drippingInjection(const drippingInjection&); //- Disallow default bitwise assignment void operator=(const drippingInjection&); protected: // Protected data //- Stable film thickness - drips only formed if thickness // exceeds this threshold value scalar deltaStable_; //- Number of particles per parcel scalar particlesPerParcel_; //- Random number generator Random rndGen_; //- Parcel size PDF model const autoPtr<distributionModel> parcelDistribution_; //- Diameters of particles to inject into the dripping scalarList diameter_; public: //- Runtime type information TypeName("drippingInjection"); // Constructors //- Construct from surface film model drippingInjection ( surfaceFilmRegionModel& film, const dictionary& dict ); //- Destructor virtual ~drippingInjection(); // Member Functions // Evolution //- Correct virtual void correct ( scalarField& availableMass, scalarField& massToInject, scalarField& diameterToInject ); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace surfaceFilmModels } // End namespace regionModels } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
25.818841
79
0.536907
[ "model" ]
c3fab3055087686d90482db2a43ff7286dffd8a0
385
hpp
C++
modules/rep/kernel.hpp
hxmhuang/OpenArray_Dev
863866a6b7accf21fa253567b0e66143c7506cdf
[ "MIT" ]
3
2020-09-08T05:01:56.000Z
2020-11-23T13:11:25.000Z
modules/rep/kernel.hpp
hxmhuang/OpenArray_Dev
863866a6b7accf21fa253567b0e66143c7506cdf
[ "MIT" ]
null
null
null
modules/rep/kernel.hpp
hxmhuang/OpenArray_Dev
863866a6b7accf21fa253567b0e66143c7506cdf
[ "MIT" ]
2
2019-08-16T08:32:30.000Z
2020-02-10T08:44:04.000Z
#ifndef __REP_KERNEL_HPP__ #define __REP_KERNEL_HPP__ #include "../../NodePool.hpp" #include "../../NodeDesc.hpp" #include "../../Function.hpp" #include <vector> using namespace std; namespace oa{ namespace kernel{ ArrayPtr kernel_rep(vector<ArrayPtr> &ops_ap); ArrayPtr kernel_rep_with_partition(vector<ArrayPtr> &ops_ap, bool same_partition); } } #endif
18.333333
64
0.706494
[ "vector" ]
c3fb94ee731e7cb37ac71ff7b574e391adf94dd5
9,026
cpp
C++
python/pySpriteComponent.cpp
indigames/igeScene
caf6e5c7575ac9fb4d7e887764707d4faa5d168e
[ "MIT" ]
null
null
null
python/pySpriteComponent.cpp
indigames/igeScene
caf6e5c7575ac9fb4d7e887764707d4faa5d168e
[ "MIT" ]
null
null
null
python/pySpriteComponent.cpp
indigames/igeScene
caf6e5c7575ac9fb4d7e887764707d4faa5d168e
[ "MIT" ]
null
null
null
#include "python/pySpriteComponent.h" #include "python/pySpriteComponent_doc_en.h" #include "components/SpriteComponent.h" #include "utils/PyxieHeaders.h" using namespace pyxie; #include <pyVectorMath.h> #include <pythonResource.h> namespace ige::scene { void SpriteComponent_dealloc(PyObject_SpriteComponent *self) { if (self && self->component) { self->component = nullptr; } PyObject_Del(self); } PyObject *SpriteComponent_str(PyObject_SpriteComponent *self) { return PyUnicode_FromString("C++ SpriteComponent object"); } // Get path PyObject *SpriteComponent_getPath(PyObject_SpriteComponent *self) { return PyUnicode_FromString(self->component->getPath().c_str()); } // Set path int SpriteComponent_setPath(PyObject_SpriteComponent *self, PyObject *value) { if (PyUnicode_Check(value)) { const char* name = PyUnicode_AsUTF8(value); self->component->setPath(std::string(name)); return 0; } return -1; } // Get size PyObject *SpriteComponent_getSize(PyObject_SpriteComponent *self) { auto vec2Obj = PyObject_New(vec_obj, _Vec2Type); vmath_cpy(self->component->getSize().P(), 2, vec2Obj->v); vec2Obj->d = 2; return (PyObject *)vec2Obj; } // Set size int SpriteComponent_setSize(PyObject_SpriteComponent *self, PyObject *value) { int d; float buff[4]; auto v = pyObjToFloat((PyObject *)value, buff, d); if (!v) return -1; self->component->setSize(*((Vec2 *)v)); return 0; } PyObject* SpriteComponent_isBillboard(PyObject_SpriteComponent* self) { return PyBool_FromLong(self->component->isBillboard()); } int SpriteComponent_setBillboard(PyObject_SpriteComponent* self, PyObject* value) { if (PyLong_Check(value)) { auto isActive = (uint32_t)PyLong_AsLong(value) != 0; self->component->setBillboard(isActive); return 0; } return -1; } // Get color PyObject* SpriteComponent_getColor(PyObject_SpriteComponent* self) { auto vec4Obj = PyObject_New(vec_obj, _Vec4Type); vmath_cpy(self->component->getColor().P(), 4, vec4Obj->v); vec4Obj->d = 4; return (PyObject*)vec4Obj; } // Set color int SpriteComponent_setColor(PyObject_SpriteComponent* self, PyObject* value) { int d; float buff[4]; auto v = pyObjToFloat((PyObject*)value, buff, d); if (!v) return -1; self->component->setColor(*((Vec4*)v)); return 0; } // Get Fill Method PyObject* SpriteComponent_getFillMethod(PyObject_SpriteComponent* self) { return PyLong_FromLong((int)self->component->getFillMethod()); } // Set Fill Method int SpriteComponent_setFillMethod(PyObject_SpriteComponent* self, PyObject* value) { if (PyLong_Check(value)) { auto val = (uint32_t)PyLong_AsLong(value); self->component->setFillMethod(val); return 0; } return -1; } // Get Fill Origin PyObject* SpriteComponent_getFillOrigin(PyObject_SpriteComponent* self) { return PyLong_FromLong((int)self->component->getFillOrigin()); } // Set Fill Origin int SpriteComponent_setFillOrigin(PyObject_SpriteComponent* self, PyObject* value) { if (PyLong_Check(value)) { auto val = (uint32_t)PyLong_AsLong(value); self->component->setFillOrigin(val); return 0; } return -1; } // Get Fill Amount PyObject* SpriteComponent_getFillAmount(PyObject_SpriteComponent* self) { return PyFloat_FromDouble(self->component->getFillAmount()); } // Set Fill Amount int SpriteComponent_setFillAmount(PyObject_SpriteComponent* self, PyObject* value) { if (PyFloat_Check(value)) { auto val = (float)PyFloat_AsDouble(value); self->component->setFillAmount(val); return 0; } return -1; } // Get Fill Clockwise PyObject* SpriteComponent_getClockwise(PyObject_SpriteComponent* self) { return PyBool_FromLong(self->component->getClockwise()); } // Set Fill Clockwise int SpriteComponent_setClockwise(PyObject_SpriteComponent* self, PyObject* value) { if (PyLong_Check(value)) { auto val = (uint32_t)PyLong_AsLong(value) != 0; self->component->setClockwise(val); return 0; } return -1; } PyGetSetDef SpriteComponent_getsets[] = { {"path", (getter)SpriteComponent_getPath, (setter)SpriteComponent_setPath, SpriteComponent_path_doc, NULL}, {"size", (getter)SpriteComponent_getSize, (setter)SpriteComponent_setSize, SpriteComponent_size_doc, NULL}, {"isBillboard", (getter)SpriteComponent_isBillboard, (setter)SpriteComponent_setBillboard, SpriteComponent_isBillboard_doc, NULL}, {"color", (getter)SpriteComponent_getColor, (setter)SpriteComponent_setColor, NULL, NULL}, {"fillMethod", (getter)SpriteComponent_getFillMethod, (setter)SpriteComponent_setFillMethod, NULL, NULL}, {"fillOrigin", (getter)SpriteComponent_getFillOrigin, (setter)SpriteComponent_setFillOrigin, NULL, NULL}, {"fillAmount", (getter)SpriteComponent_getFillAmount, (setter)SpriteComponent_setFillAmount, NULL, NULL}, {"clockwise", (getter)SpriteComponent_getClockwise, (setter)SpriteComponent_setClockwise, NULL, NULL}, {NULL, NULL}}; PyTypeObject PyTypeObject_SpriteComponent = { PyVarObject_HEAD_INIT(NULL, 0) "igeScene.Sprite", /* tp_name */ sizeof(PyObject_SpriteComponent), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SpriteComponent_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)SpriteComponent_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ SpriteComponent_getsets, /* tp_getset */ &PyTypeObject_Component, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ }; } // namespace ige::scene
39.587719
138
0.481276
[ "object" ]
7f01341bdcacf40ebcd9aea022e41aa382eef871
456
hpp
C++
includes/components/mover.hpp
wagnrd/simple-graphics-engine
92e8277a267c364fadecb725ecd4af1b1a753e32
[ "MIT" ]
null
null
null
includes/components/mover.hpp
wagnrd/simple-graphics-engine
92e8277a267c364fadecb725ecd4af1b1a753e32
[ "MIT" ]
null
null
null
includes/components/mover.hpp
wagnrd/simple-graphics-engine
92e8277a267c364fadecb725ecd4af1b1a753e32
[ "MIT" ]
null
null
null
#ifndef SIMPLE_GRAPHICS_ENGINE_MOVER_HPP #define SIMPLE_GRAPHICS_ENGINE_MOVER_HPP #include <memory> #include <glm/vec2.hpp> #include "includes/component.hpp" class Transform; class Mover: public Component { std::shared_ptr<Transform> transform; glm::vec2 maxPosition; public: explicit Mover(const glm::vec2& maxPosition); void start() override; void update(float deltaTime) override; }; #endif //SIMPLE_GRAPHICS_ENGINE_MOVER_HPP
19.826087
49
0.765351
[ "transform" ]
7f046b3587b327df790b2389af8437674c21a34e
5,496
cpp
C++
src/utils.cpp
diegoob11/GalaxyOnFire
a694f10792743031da7500c20b676840d92b3b66
[ "Apache-2.0" ]
null
null
null
src/utils.cpp
diegoob11/GalaxyOnFire
a694f10792743031da7500c20b676840d92b3b66
[ "Apache-2.0" ]
null
null
null
src/utils.cpp
diegoob11/GalaxyOnFire
a694f10792743031da7500c20b676840d92b3b66
[ "Apache-2.0" ]
null
null
null
#include "utils.h" #ifdef WIN32 #include <windows.h> #else #include <sys/time.h> #endif #include "includes.h" #include "game.h" #include "camera.h" #include "shader.h" #include "extra/stb_easy_font.h" //quick dirty global GLuint grid_vao; GLuint grid_vbo_vert; GLuint grid_vbo_ind; GLuint grid_num_points; Shader* grid_shader; long getTime() { #ifdef WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv,NULL); return (int)(tv.tv_sec*1000 + (tv.tv_usec / 1000)); #endif } void genGrid(float dist, float n_step) { float xs = -dist / 2; float xe = dist / 2; float ys = -dist / 2; float ye = dist / 2; float zs = -dist / 2; float ze = dist / 2; float x_size = dist; float y_size = dist; float z_size = dist; float x_step = x_size / n_step; float y_step = y_size / n_step; float z_step = z_size / n_step; int n = (int)n_step + 1; std::vector<Vector3> grid; grid.resize(n*n*n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { Vector3 p(xs + x_step * i, ys + y_step * j, zs + z_step *k); grid[i + n*j + n*n*k] = p; } } } std::vector<unsigned int> indices; for (size_t i = 0; i < grid.size(); i++) { indices.push_back((unsigned int)i); } //bind vao to store state glGenVertexArrays(1, &grid_vao); glBindVertexArray(grid_vao); glGenBuffers(1, &grid_vbo_vert); //generate one handler (id) glBindBuffer(GL_ARRAY_BUFFER, grid_vbo_vert); //bind the handler glBufferData(GL_ARRAY_BUFFER, grid.size() * 3 * sizeof(float), &grid[0], GL_STATIC_DRAW); //upload data glEnableVertexAttribArray(VERTEX_ATTRIBUTE_LOCATION); glVertexAttribPointer(VERTEX_ATTRIBUTE_LOCATION, 3, GL_FLOAT, GL_FALSE, 0, NULL); glGenBuffers(1, &grid_vbo_ind); //create more new buffers glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, grid_vbo_ind); //bind them as element array glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), &indices[0], GL_STATIC_DRAW); grid_shader = new Shader(); if (!grid_shader->load("data/shaders/simple.vert", "data/shaders/simple.frag")) { std::cout << "grid shader not found or error" << std::endl; exit(0); } grid_num_points = (GLuint)grid.size(); glBindVertexArray(0); //unbind VAO glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind buffers } //Draw the grid void drawGrid() { Matrix44 m; grid_shader->enable(); grid_shader->setMatrix44("u_model", m); grid_shader->setMatrix44("u_mvp", m); glBindVertexArray(grid_vao); glDrawElements(GL_LINES, grid_num_points, GL_UNSIGNED_INT, 0); glBindVertexArray(0); //disable the shader grid_shader->disable(); } //this function is used to access OpenGL Extensions (special features not supported by all cards) void* getGLProcAddress(const char* name) { return SDL_GL_GetProcAddress(name); } //Retrieve the current path of the application #ifdef __APPLE__ #include "CoreFoundation/CoreFoundation.h" #endif #ifdef WIN32 #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif std::string getPath() { std::string fullpath; // ---------------------------------------------------------------------------- // This makes relative paths work in C++ in Xcode by changing directory to the Resources folder inside the .app bundle #ifdef __APPLE__ CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char path[PATH_MAX]; if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) { // error! } CFRelease(resourcesURL); chdir(path); fullpath = path; #else char cCurrentPath[1024]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) return ""; cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; fullpath = cCurrentPath; #endif return fullpath; } bool checkGLErrors() { #ifdef _DEBUG GLenum errCode; const GLubyte *errString; if ((errCode = glGetError()) != GL_NO_ERROR) { errString = gluErrorString(errCode); std::cerr << "OpenGL Error: " << errString << std::endl; return false; } #endif return true; } std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } Vector2 getDesktopSize( int display_index ) { SDL_DisplayMode current; // Get current display mode of all displays. int should_be_zero = SDL_GetCurrentDisplayMode(display_index, &current); return Vector2( (float)current.w, (float)current.h ); } bool drawText(float x, float y, std::string text, Vector3 c, float scale ) { static char buffer[99999]; // ~500 chars int num_quads; num_quads = stb_easy_font_print(x, y, (char*)(text.c_str()), NULL, buffer, sizeof(buffer)); Camera cam; cam.setOrthographic(0, Game::instance->window_width / scale, Game::instance->window_height / scale, 0, -1, 1); cam.set(); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); /*#ifndef __APPLE__ glColor3f(c.x, c.y, c.z); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 16, buffer); glDrawArrays(GL_QUADS, 0, num_quads * 4); glDisableClientState(GL_VERTEX_ARRAY); #endif */ glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); return true; }
24.105263
122
0.689592
[ "vector" ]
7f0e4ff91e408d21fbd1dd792373f90106595347
2,294
cc
C++
cpp/Codeforces/451-500/489B_BerSU_Ball.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/451-500/489B_BerSU_Ball.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/451-500/489B_BerSU_Ball.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <vector> #include <unordered_map> #include <stdint.h> #include <cmath> using namespace std; typedef int64_t Int; typedef uint64_t UInt; void quickSort(Int *intArr, Int first, Int last) { Int left = first; Int right = last; Int pivot = intArr[(left + right) / 2]; if (first >= last) return; do { while (intArr[left] < pivot) ++left; while (intArr[right] > pivot) --right; if (left <= right) { Int temp = intArr[left]; intArr[left] = intArr[right]; intArr[right] = temp; ++left; --right; } } while (left <= right); quickSort(intArr, first, right); quickSort(intArr, left, last); } Int countPairs(Int *bArr, Int bArrLength, Int *gArr, Int gArrLength) { Int bArrIdx = 0; Int gArrIdx = 0; Int pairsCount = 0; while ((bArrIdx < bArrLength) && (gArrIdx < gArrLength)) { if (abs(bArr[bArrIdx] - gArr[gArrIdx]) <= 1) { ++pairsCount; ++bArrIdx; ++gArrIdx; } else { if (bArr[bArrIdx] < gArr[gArrIdx]) { ++bArrIdx; } else if (bArr[bArrIdx] > gArr[gArrIdx]) { ++gArrIdx; } } } return pairsCount; } int main(int argc, char **argv) { Int n = 0; // Read the first line string line = ""; if (getline(cin, line)) { stringstream ss(line); ss >> n; } Int boysArr[n]; Int boysArrIdx = 0; // Read the second line if (getline(cin, line)) { stringstream ss(line); while (boysArrIdx < n) { ss >> boysArr[boysArrIdx++]; } } Int m = 0; // Read the third line if (getline(cin, line)) { stringstream ss(line); ss >> m; } Int girlsArr[m]; Int girlsArrIdx = 0; // Read the fourth line if (getline(cin, line)) { stringstream ss(line); while (girlsArrIdx < m) { ss >> girlsArr[girlsArrIdx++]; } } // Logic starts here quickSort(boysArr, 0, n - 1); quickSort(girlsArr, 0, m - 1); cout << countPairs(boysArr, n, girlsArr, m); return 0; }
19.606838
70
0.512642
[ "vector" ]
7f1646945be13ec926ccdbd0e9170e46160fef2a
880
cpp
C++
Test/Cpp/ACM/HDU/1014.cpp
intLyc/Undergraduate-Courses
8eba20b6b8c43d4eee0af4b0ebca68d708f27aa9
[ "Apache-2.0" ]
null
null
null
Test/Cpp/ACM/HDU/1014.cpp
intLyc/Undergraduate-Courses
8eba20b6b8c43d4eee0af4b0ebca68d708f27aa9
[ "Apache-2.0" ]
null
null
null
Test/Cpp/ACM/HDU/1014.cpp
intLyc/Undergraduate-Courses
8eba20b6b8c43d4eee0af4b0ebca68d708f27aa9
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <iomanip> #include <vector> #include <string> using namespace std; int main() { int step,mod; string str(" Good Choice"); string bad(" Bad Choice"); while (cin >> step >> mod) { vector<int> arr; int temp; temp = (step)%mod; arr.push_back(temp); for (int i = 1; i<mod; i++) { temp = (arr[i-1]+step)%mod; arr.push_back(temp); } vector<int> count(arr.size(), 0); for (int i = 0; i<arr.size(); i++) { if (count[arr[i]] == 1) str = bad; count[arr[i]] = 1; } cout << setiosflags(ios::right) << setw(10) << step << setiosflags(ios::right) << setw(10) << mod << setiosflags(ios::left) << str << endl << endl; } return 0; }
25.882353
63
0.45
[ "vector" ]
7f230d91ea4be41f22d34ad830e8a95ab7757606
435
hpp
C++
src/tank/include/tank/tank_base.hpp
northdk/ros2practice
8ed919169585faa36b052363e05b817f3c54b71d
[ "MIT" ]
null
null
null
src/tank/include/tank/tank_base.hpp
northdk/ros2practice
8ed919169585faa36b052363e05b817f3c54b71d
[ "MIT" ]
null
null
null
src/tank/include/tank/tank_base.hpp
northdk/ros2practice
8ed919169585faa36b052363e05b817f3c54b71d
[ "MIT" ]
null
null
null
/** * @file tank_base.h * @author North.D.K (north24@qq.com) * @brief plugin base for tank model, all actions start here * @version 0.1 * @date 2021-11-30 * * @copyright See the LICENSE file. * */ #ifndef TANK_BASE_HPP #define TANK_BASE_HPP #include <string> class Tank { public: virtual void init(const std::string& name) = 0; virtual void action() = 0; // virtual ~Tank() {} protected: Tank(){} }; #endif
17.4
60
0.641379
[ "model" ]
b525c81ee5a304e3ea237d32fb7d399b9c881598
11,336
cpp
C++
data/555.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/555.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/555.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
int FVaP, hS , wewN // ,// XZG ,u, JX , T2 , H , hPXC , IjMce ,UfDe , J8 , crRNW//j , vcr ,STGz,Lyf ,BEDFG,/*0*/ LzbBlv , /*JPo*/Xkl ,/*ez*/ Slfl , M5S , IZ , OAS2,dEq//u0 , W,Ku9//XQf , c5f , gjGyHu3 ,U, D1xf, Djn , wK,LB ,jU, K4 , OT9 , MD//3 , K6AP ; void f_f0//LOm (){ int Nz; volatile int/*2l*/ mmV5E, z9 ,f4v ,zyT6jh , tq1l3X , wWj ; for(int i=1 ; i< //uG 1;++i ){ int di //ah ; volatile int yrJ ,bOjx8e ,e /*s*/ , z , GGbp; di= GGbp+ yrJ+ bOjx8e+e + z ;/*pDx*/{ volatile int kr ,n/**/, rX,R6e ; for (int i=1; i< 2;++i) return//t //E ; {for (int i=1;i< 3 ;++i){ }}{{ ;; } return ; {}} K6AP /*h*///8 = R6e +kr +/*DAG*/n +rX; return ;} return ; }for(int i=1; i< 4 ;++i ) {{ {if (true ){{} ;/*a0*/} else {return ; {}// }{{ } } ; } {/*T*/ for(int i=1; i<5 ;++i ) { volatile int dhJi ,o6 ;for (int //n i=1 ;i<6 ;++i) {} FVaP = o6 + dhJi /*o6Q*/ ; ; } } { { }} }{ int L ; volatile int KN,Vv,hz , g/*mQbW*/,/*m*/H7 ;L=H7+ KN +/*tpb*/Vv + hz//kBY +g ; ; { { }}} //N { /*liQau*/volatile int UqC, zEGU, hnq,/*d*/ fc7; ;hS //JoJ =fc7 +UqC +zEGU+ hnq ;{ {//Wi { }{ //40 } } return ; } } /**/} for/*I*/(int i=1/*sM*/ ;i<7;++i)for (int i=1; i< 8;++i ){ int fwl/*XI*/; volatile int YkZ ,wL , dN,H2kC, Ee/*0*/, RZsjr/*e*/, nW ,/*y*/ dv1 ,//fe BYpA,yud, FFt; for//fh (int i=1 ; i< 9;++i ) if//lT (//G true )wewN//jD = FFt /*i*/+ YkZ+wL+dN+H2kC +Ee ;else {; { {} {}{ {//ime } {}{ }} } ; {;} } { {{ // {} } { int IPl; volatile int GYDeo ,JS; ;{ for/*Bwv*/ (int i=1 ;i<10;++i ){/*D4A*/} } IPl = JS+GYDeo; } }{ if( true ) for(int i=1;i<11 /*W*/ ;++i);else {if ( true){ } else{} } }{if ( true) {}else{ } for (int i=1 ;/**/ i< 12 /*V*/;++i//sX ){ volatile int k ,/**/GBUDH , LYT ; ;XZG= LYT + k +GBUDH //yx4 ;/*qGt8*/} } }fwl = RZsjr+ nW + dv1+BYpA + yud /*P*/; }for(int i=1 ; i< 13;++i ) if( true)Nz =wWj + mmV5E+ z9+ f4v +zyT6jh //r /*o*/+ tq1l3X ; else{ int MEv ; volatile int RVH9yGgG, Jpk , Pw0b ,D ; MEv = D + RVH9yGgG+//n41V Jpk+ Pw0b;return ;/*n6b*/{// ;{ /*l*/; {}} return ; { { { } }{} }} }return ; return ; } void f_f1() {for(int i=1 ; i< 14;++i /*TLyv*//*gd*/)//zXg { for (int i=1 ;i< 15 ;++i){int jj0H ;volatile int j ,T, ltBs/*rY*/, UPz , zF ,bH,MDhUC , sf ;//f1 for (int i=1; i<16 ;++i ) jj0H = sf +j/*ku*/+ T +ltBs/*v*/ +UPz ; u = zF +bH +MDhUC; return ;} { { {{} } //p8FI } if( true ) { volatile int uHR,eHLq ,lCGkyEk ; for(int i=1 ; i< 17 ;++i) ; {} JX=lCGkyEk+ uHR/*l*/+eHLq; } else if ( true) { { for (int i=1; i< 18 ;++i ) { }; }}else { if ( true ){ }else { {}} //e } } ; ; } return ; { int CV0S; volatile int Za , c, Rx , bYR; CV0S = bYR + Za+c +Rx ;{ int K ;volatile int PNIx , khxT ,HkK/**/, TUN ; ; K= TUN +PNIx+khxT+HkK ; } for (int i=1 ; i<//o3a 19;++i ){ { {/*0*//*swCe*/ } };} { return ; { for (int i=1 ;//Zq i<// 20 ;++i){ ;/*re*/ { } } {}if (true ) {} else/**/ if /**/( true)for(int i=1 ;i< 21 ;++i ) if ( true)/**/{ int Nrz// ; volatile int Wr;{} /*vj*/if ( true)Nrz/*f*/ =//j /*iV*/Wr /*3L*/ ;else return ;; }//y else//TuDe {if (true ){} else return ; }else { /*9JyS*/ int ls ;volatile int ebNA ;{ ; } ls/*6cJU*/= ebNA; }{ for (int i=1;i< 22 ;++i ) { }} }{/*lA*/if/*Mrh*/ (true )//aSs {{ for/*IC*/ (int i=1;i<23;++i)if (true //w ) { } else{ } if(true) { }else if( true ) {{ } //d }else { } }// }//a5 else ; {; }//iNA } } {volatile int djn6,lnK , I , sM ,Ul ,yCgqg; for (int i=1 ; i< 24 ;++i )//U ; {{} } {volatile int zlzp , BCWLO,/*d8*/NSG ;return ; if /*c*/( true)for(int i=1;i<25 ;++i) ;else T2 =NSG//qQk8h +zlzp + BCWLO; } H =//6n yCgqg +djn6 + lnK +I +sM + Ul; {// { }{ volatile int X4o ,AV//IBL ; hPXC=AV+ X4o ;/*Xd*/for //b (int i=1 ; i<26 ;++i )/*gR*/ /*H*/return ; }} } }/*7o*/;return/*f0*/ ;} void f_f2() { /*iR*/{volatile int idw, J1, X ,lwhl ,cmn , //3D Pf,uLRr , YfSNs , bri ,WRV, pQt ;/*jg*/;IjMce=pQt/*P*/ + idw + J1+X+ lwhl/*wR*/ + cmn; for (int i=1// ;i< 27 ;++i ) if ( true ) /*cf*/UfDe= Pf+ uLRr+YfSNs + bri +WRV ;else//7 { /*rf*/{{ return ;} { {} } if (/*Um*/true) {{ }}else{{ }{ }} } ;}}{ //az { ; {{ { } { } //wt { } }}}{ if /*ONe*/ ( true)if( true ) for (int i=1 ; i<28 ;++i ) return ; else{ volatile int/*MWbF*/ eaa7, lcA ,yb ; if(true ){/*M*///FB for (int i=1 ;i< 29;++i) return ; }else//5t { volatile int LC3QLg ; J8 =LC3QLg ; } crRNW=yb +eaa7+// lcA ;}else {return ; ; }{if (true );else{ } { volatile int EU ,zLsYc;/*pJ*/{ }vcr =zLsYc+ EU ; }/*71*/}/**/ { ; }{ return ; for(int i=1;//8 i< 30;++i ) { for(int i=1;i<//h 31 ;++i){ for(int i=1 ;i</*AjZT*/32 ;++i/*EP*/) for (int i=1 ;i< 33 ;++i )for (int i=1 ; i< 34 ;++i) { } } {for (int i=1 ; i<35/*E*/ ;++i// ){ int g1sZAh ;volatile int//S B;//dWd //tN g1sZAh = B ; /**/{}} for (int i=1//rZV ; i<36 ;++i ){} } ;}for (int i=1;i< 37 ;++i ) { }} } { { volatile int mBw, TKvwj,/*OB*///jw3BN aM1OU ;for /*w*/(int i=1 ;i<38 ;++i )STGz = aM1OU +mBw + TKvwj;{int BBw ; volatile int XX ;; BBw= XX ; { } }} for (int i=1 ;i<39 ;++i ) {for (int i=1;i<40 ;++i )return ; //D {int dNX; volatile int t4pZ, Ov7 ;if ( true )//UP7 dNX = Ov7+t4pZ ; else ; } } }} {volatile int JsJs ,gXn3, oX//Nn , amS ,DOF, XUN; { int IqG3 ; volatile int CpWg, zL92UH, Rn/*T8L*/ ; {/*KB*/if/*Ky*/(true )return ; else{ {/*t*/}} { }} IqG3 =/*X*/ Rn+ CpWg +/**/zL92UH; {{ {}} { if(// true//0 ) return ;else{ /*0DW*/ { } } }} } {volatile int Pb,jQ , IBLe , IBm ,VG ; { {} ; };Lyf= VG + Pb + jQ+ IBLe+IBm ; }{if ( true ){ volatile int O , FFXa, Dm6Cej ,Wx, /*B*/CFwy , Sf9KBz ; BEDFG = Sf9KBz//WFq + O//L + FFXa;{}{}LzbBlv = Dm6Cej +//O Wx +CFwy; }else{; if//ci (true );else for (int i=1/*A2CT*/ ; i< 41 ;++i /*P*/)return ;} if ( true) return //kVN //O ; else ; }Xkl =XUN+ JsJs + gXn3+oX + amS+DOF ;{ {//jeXd {{} {}/*VX*/ } {{}}{ {volatile int qks; Slfl= qks; }}{} } { if( true ) {} else{{ } { volatile int SE ; for(int i=1//2o ; i< 42 ;++i) /*B*/M5S =SE ; { }} }// return ; } if ( /**/true) {{volatile int DTtxpy ,HF6;//1 IZ = HF6 + DTtxpy ; } } else {{volatile int vcU ;if( true ) { } else OAS2= vcU ;{ { } } }{ } }} } ; { for(int i=1 ; i< 43;++i ) { { return ;;}//Z4c {for(int i=1 ; i< 44 ;++i ) { }; return ; }}{ { //YoSf { ; } /*Nq*/}{; }return ; } {for (int i=1;i<45 ;++i) for (int i=1; i<46//VGS ;++i){for(int i=1 ; i<47 ;++i){ }if ( true) { } else {}} return ;} ;for (int i=1 ; i< 48;++i ){ {/*dl*/int t7g; volatile int PZ ,Ei , CA,zY ; for (int i=1; i< /*e*/49 ;++i)if /*3uN*/ (true ){}else for (int i=1;i<50 ;++i) {//R {}if( true){ { } } else{ } }t7g = zY + PZ+Ei +CA /*G1A*/;}for (int i=1 /*HO*/; i<51 ;++i ) {/*ZXn*/; //kJ } } }if ( true ) {{ int oxLYy; volatile int jNb, eg9 ,gC ; /*Jh*/{ { if (true); else{ {}} } }for(int i=1; i< 52;++i ) for (int i=1; i< 53;++i )oxLYy=gC+jNb + eg9//MA ; { { //t int AXI ;volatile int/*A1*/ hAg;for(int i=1 ;i< 54;++i ){ { { }}/*4L*/ } AXI=hAg ; } // for(int i=1; i<55;++i ){ } { {//Mx } }return ; }} { { return ; { ;//7b }} { { return/*Ss*/ ;} } { for (int i=1;//n i<56;++i ) return ; }/*2*/}{ volatile int hjLP , // A3E , Zgf ,sUeEt ; ; {{ { }/*zg*/} { for(int /*zA*/i=1 ;i<57 ;++i ) ; }for (int i=1/*bP*/; i<58 ;++i) { }//a9 }if ( true ) {/*oE*/ { volatile int T0U0 , eT , NJ ; { } if ( true) {}else{} ;dEq =NJ; W = T0U0 +eT ;}{ { }//mPj } }else/*JRMN*/ Ku9 = //6Y0N sUeEt+hjLP+ A3E +Zgf ; }} else{volatile int rnzs//0Qw8to ,RZ ,LVLV ,y , t7 , r3a1, hq// ,//42 Id4jO2 , uY1 , G ;{ int m3/*6Q*/ /*sh*/;volatile int /*0f2*/ wt , Sq9e ,//rP wj , WgW0T, xz ;{{ ; } return ; //OoD } if ( true ) { for (int i=1; i< 59//V ;++i) return/*eI*/ ; return ;} else if ( true)return ; else m3= xz/*uCSI*/ +wt+//E Sq9e+wj+WgW0T ;{{//Jy47I ;} } { int//bEZ GX,Kld; volatile int IrCQ , hE,zGC, gK , bRx ,ewm ; Kld=ewm +IrCQ+ hE;GX =zGC +gK +bRx; //Uu }}//l return ;c5f = /*A*/ G +/*Zv*/rnzs +//jb RZ + LVLV+y;for (int i=1;i< 60 ;++i/*K*/) gjGyHu3 =t7 + r3a1 +/*M*//**/ hq +//O Id4jO2 + uY1; for(int i=1//DvS ; i< 61 ;++i )if ( true ) ; else{//pK ; ; } } return ;} int main/*rl*/() { int YP5r4 ,/*4K*/o2mT //M ; volatile int pAH , /*rC*/oszxFM ,/*a*/t , hy6 , oRD,Dt5 , qSad5 , U9mm, Z/*Ah*/,lT ,COm ,/*E*//**/DU07hn , EjUXAn , bL2Q/*6*/ , AwC, n4, ixM , XYt ; o2mT=XYt + pAH//a9Ixx + oszxFM + //YG t+ hy6 + oRD; for (int i=1 ; i< 62;++i/*T9aK*/ ) { int OA//Md5 ; volatile int/*f*/ V , XU4g ,m7Cwjl8,Sr ,YetR , bQU, J , Jp, h,FXe//17 ; U=/*M*/ FXe +V+XU4g +m7Cwjl8+ Sr ;OA= YetR + bQU/*7*/ + J//t + Jp + h;{ /*r*/{{} if// ( true){/*Vza*/{ } }//jb else { { } }{{ }for (int i=1;i< 63 ;++i) ; } }if ( true ){ int Rp;volatile int jby ,Ft ,w1Us;Rp=w1Us+ jby+Ft ;for(int i=1 ; i< 64 ;++i)for (int /*81*/ i=1;i< 65;++i ); return//x 1785524902; }else ;return 1762400894 ; if ( true);else if(true){{ }} else { ;{for (int i=1 ; i<66 ;++i) { } } /*zGu*/ };}}; {volatile int Y9Cx , //H4a rlt , t9, YeC/*Tu*/,G7z , //o AQ/**/, oxo , GRiU ,i2M , Gny ; /*I8*/{ {for(int //D4 i=1 ; i< 67 ;++i )//Z for (int i=1 ;i<//j7v 68;++i ) return 2027427885;for (int i=1 ; i<69 ;++i ) ; for (int i=1 ;i<70 ;++i )if( true ) ; else ; { { }}} if(true/*1*/){{ } }else{if( true) ; else if ( true ){}else{ { for(int i=1 ;i< 71;++i //zL )if (true//x ){}else for(int i=1 ;i< 72 ;++i ){ } if ( true){ }else ; { } } }/*J*///E2 for (int i=1 ;i< 73;++i /**/ ) ;} if //81c ( true ) { volatile int qJ, tqBi ,b9Viy; ;D1xf /*fC*/= b9Viy +qJ +tqBi ;;}else { int CE ; volatile int fTf , nPb6J ;//FxN { volatile int Vt ,// yEvGu ,MYS,AY/*Oi0*/ ,/**/ EP; Djn = EP+Vt; wK =yEvGu + MYS + AY ; } for(int i=1 ; i< 74 ;++i)/*pA*/CE =nPb6J + fTf;}/**/} for (int i=1 ; i< 75;++i/*Tu*/ ) { /*T2*/{ { { } } { { ; }{ } } }if ( true ) { { for(int i=1 ;i< 76 ;++i ) ;return 1549646730;} { } } else{{ {} } ; {/*nYN8*/}}{ {} return 500213244 ; } { { ; } } } if(//SM true){ { volatile int el , GEs/*f5l*/, oDO; ; for(int i=1 ; i<77;++i ) LB=// oDO//zj + el +GEs; { { int my ;volatile int OZq//KO ;for (int i=1;i< 78;++i )if(true)my =// OZq ;else ; //H6 }} } { ; //xw } } else//R9x if( true ) return 1916269576; /*C3qq*/else jU=Gny + Y9Cx+rlt+ t9 +YeC ;{ volatile int sn,ws72 ,o , v ;for (int i=1 ;//tq /*VE*/i<79 ;++i ) ;for /*u3b*/(int i=1; i< 80;++i )K4// =v+ sn//dTU +ws72 + o ;{ { int P ; volatile int dJ1//c ,QDLb ;P/*2K7*/=QDLb+dJ1 ; }{ { }/*5Dyc3*/} } return 275843545;}if/*XPM*/ (true )OT9 //A3G = G7z+AQ+ oxo+GRiU +//D i2M;else { for (int i=1; i< 81 ;++i ) ; {{ return 1735766904 ; }} return 1202425677 ; }}MD /*K*/ =//3d0 Dt5+ qSad5 + U9mm// +Z+ lT +COm; YP5r4 /*1QIlA*/=//EhCr DU07hn +EjUXAn + bL2Q+ AwC + n4+ixM ;}
10.343066
68
0.443278
[ "3d" ]
b5273461478f0156abdccdf0f5508505d20b6156
11,726
cpp
C++
MenuToolsHook/MenuToolsHook.cpp
kokolorix/MenuTools
c13f966feb4a4851e7909a52d9e9e25b85a69c07
[ "MIT" ]
null
null
null
MenuToolsHook/MenuToolsHook.cpp
kokolorix/MenuTools
c13f966feb4a4851e7909a52d9e9e25b85a69c07
[ "MIT" ]
null
null
null
MenuToolsHook/MenuToolsHook.cpp
kokolorix/MenuTools
c13f966feb4a4851e7909a52d9e9e25b85a69c07
[ "MIT" ]
null
null
null
// MenuToolsHook.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include <windowsx.h> #include <sstream> #include <chrono> #include <future> #include "MenuTools.h" #include "MenuCommon/Logger.h" #include "MenuCommon/TrayIcon.h" #include "MenuCommon/ScreenToolWnd.h" #include <Shlwapi.h> #pragma comment(lib, "Shlwapi.lib") #define WM_GETSYSMENU 0x313 extern HINSTANCE hInst; void InflateWnd(const LONG& diff, const HWND& hWnd); // Process messages LRESULT CALLBACK HookProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { using namespace std::chrono; static high_resolution_clock::time_point last_lbutton_down; static POINT lastButtonDown = { 0 }; static WPARAM lastHitTest = 0; static bool dblClick = false; //static const UINT_PTR TIMER_ID = 13578; //static UINT_PTR timer = NULL; //if(!timer) // timer = SetTimer(hWnd, TIMER_ID, 300, (TIMERPROC)NULL); switch (message) { //case WM_TIMER: //{ // if (wParam == TIMER_ID) // { // if (HIBYTE(GetAsyncKeyState(VK_LSHIFT)) && HIBYTE(GetAsyncKeyState(VK_LCONTROL)) && HIBYTE(GetAsyncKeyState(0x41))) // { // log_debug(L"Thats i!: {}", message); // RECT wr; // GetWindowRect(hWnd, &wr); // int caption = GetSystemMetrics(SM_CYCAPTION); // POINT pt = { // wr.left + ((wr.right - wr.left) / 2), // wr.top + (caption / 2) // }; // PostMessage(hWnd, WM_SHOW_WIN_POS, wParam, MAKELPARAM(pt.x, pt.y)); // } // return TRUE; // } // break; //} //case WM_KEYDOWN: //{ // log_debug(L"Hello"); //} case WM_CONTEXTMENU: case WM_INITMENU: case WM_INITMENUPOPUP: case WM_GETSYSMENU: { // Install custom menus if (MenuTools::Install(hWnd)) { // Update menu MenuTools::Status(hWnd); return TRUE; } break; } case MT_HOOK_MSG_TRAY: { // Process tray messages MenuTools::TrayProc(hWnd, wParam, lParam); return TRUE; break; } case WM_COMMAND: case WM_SYSCOMMAND: { // Process menu messages MenuTools::WndProc(hWnd, wParam, lParam); return TRUE; break; } //case WM_LBUTTONDOWN: case WM_NCLBUTTONDOWN: { dblClick = false; last_lbutton_down = std::chrono::high_resolution_clock::now(); POINT bd = { // button down GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; ClientToScreen(hWnd, &bd); auto ch = GetSystemMetrics(SM_CYCAPTION); // caption height RECT cr; // caption rect GetWindowRect(hWnd, &cr); cr.bottom = cr.top + ch; //if (!PtInRect(&cr, bd)) if (wParam == HTCAPTION) { lastButtonDown = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; log_debug(L"LButtonDown: {}, {}", GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); if (ScreenToolWnd::pWnd) { ScreenToolWnd::pWnd.reset(); return TRUE; } //BYTE ks = HIBYTE(GetAsyncKeyState(VK_CONTROL) + GetAsyncKeyState(VK_SHIFT)); //if(!ks) //if (!is_one_of((signed)wParam, MK_CONTROL, MK_SHIFT)) //{ POINT lbd = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; std::thread t([hWnd, wParam, lbd]() { auto toWait = GetDoubleClickTime() / 2; Sleep(toWait); if (!HIBYTE(GetAsyncKeyState(VK_LBUTTON))) { POINT pt; GetCursorPos(&pt); const LONG XTOL = GetSystemMetrics(SM_CXDOUBLECLK) / 2; const LONG YTOL = GetSystemMetrics(SM_CYDOUBLECLK) / 2; RECT tolerance = { lbd.x - XTOL, lbd.y - YTOL, lbd.x + XTOL, lbd.y + YTOL }; log_debug(L"LButton is up: {}, {}", pt.x, pt.y); if (PtInRect(&tolerance, pt)) { if (HIBYTE(GetAsyncKeyState(VK_CONTROL)) || HIBYTE(GetAsyncKeyState(VK_SHIFT))) { LONG diff = HIBYTE(GetAsyncKeyState(VK_CONTROL)) ? 10 : -10; InflateWnd(diff, hWnd); } else { log_debug(L"ScreenToolWnd::pWnd: {}", (void*)ScreenToolWnd::pWnd.get()); { if (!dblClick) { PostMessage(hWnd, WM_SHOW_WIN_POS, wParam, MAKELPARAM(pt.x, pt.y)); } } } } } } ); t.detach(); //TCHAR buffer[MAX_PATH] = { 0 }; //TCHAR* out; //DWORD bufSize = sizeof(buffer) / sizeof(*buffer); //// Get the fully-qualified path of the executable //if (GetModuleFileName(NULL, buffer, bufSize) < bufSize) //{ // // now buffer = "c:\whatever\yourexecutable.exe" // // Go to the beginning of the file name // out = PathFindFileName(buffer); // // now out = "yourexecutable.exe" // // Set the dot before the extension to 0 (terminate the string there) // *(PathFindExtension(out)) = 0; // // now out = "yourexecutable" // std::wstring exeName = out; // std::transform(exeName.begin(), exeName.end(), exeName.begin(), // [](wchar_t c) { return std::tolower(c); }); // //if (exeName == L"code") // { // } //} //} } else { lastButtonDown = { 0, 0 }; } return TRUE; break; } case WM_LBUTTONDBLCLK: case WM_NCLBUTTONDBLCLK: { dblClick = true; //ScreenToolWnd::pWnd.reset(); auto now = std::chrono::high_resolution_clock::now(); POINT bu = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; std::chrono::duration<double, std::milli> millis = now - last_lbutton_down; //double dbl_click = GetDoubleClickTime(); log_debug(L"LButtonDblClick: {}, {}, duration: {}", GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), millis.count()); break; } case WM_LBUTTONUP: { auto now = std::chrono::high_resolution_clock::now(); // //POINT& lbd = lastButtonDown; // POINT bu = { // button up // GET_X_LPARAM(lParam), // GET_Y_LPARAM(lParam) // }; // ClientToScreen(hWnd, &bu); // std::chrono::duration<double, std::milli> millis = now - last_lbutton_down; // //double dbl_click = GetDoubleClickTime(); // log_debug(L"LButtonUp: {}, {}, duration: {}", GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), millis.count()); // //if (millis.count() <= dbl_click) // //return FALSE; // //static const LONG TOL = 1; // //RECT tolerance = { lbd.x - TOL, lbd.y - TOL, lbd.x + TOL, lbd.y + TOL }; // //if (!PtInRect(&tolerance, bu)) // //{ // // return FALSE; // //} // auto ch = GetSystemMetrics(SM_CYCAPTION); // caption height // RECT cr; // caption rect // GetWindowRect(hWnd, &cr); // cr.bottom = cr.top + ch; // if(!PtInRect(&cr, bu)) // //if (SendMessage(hWnd, WM_NCHITTEST, wParam, MAKELPARAM(bu.x, bu.y)) != HTCAPTION) // return FALSE; // if (is_one_of((signed)wParam, MK_CONTROL, MK_SHIFT)) // { // LONG diff = wParam == MK_CONTROL ? 10 : -10; // InflateWnd(diff, hWnd); // } // else // { // //wParam = SendMessage(hWnd, WM_NCHITTEST, wParam, lParam); // //// Title bar // //if(!ScreenToolWnd::IsScreenToolWnd(hWnd)) // //{ // // log_debug(L"ScreenToolWnd::pWnd: {}", (void*)ScreenToolWnd::pWnd.get()); // // if (ScreenToolWnd::pWnd) // // { // // ScreenToolWnd::pWnd.reset(); // // } // // else // // { // // /*PostMessage(hWnd, WM_SHOW_WIN_POS, wParam, MAKELPARAM(bu.x, bu.y));*/ // // //std::async(std::launch::async, [hWnd, wParam, bu]() // // std::thread t([hWnd, wParam, bu]() // // { // // Sleep(100); // // if (!dblClick) // // { // // PostMessage(hWnd, WM_SHOW_WIN_POS, wParam, MAKELPARAM(bu.x, bu.y)); // // //ScreenToolWnd::pWnd = ScreenToolWnd::ShowWindow(hInst, hWnd, WM_LBUTTONUP, wParam, MAKELPARAM(bu.x, bu.y)); // // } // // } // // ); // // t.detach(); // // //if (SendMessage(hWnd, WM_NCHITTEST, wParam, MAKELPARAM(bu.x, bu.y)) == HTCAPTION) // // //if (!dblClick) // // // ScreenToolWnd::pWnd = ScreenToolWnd::ShowWindow(hInst, hWnd, WM_LBUTTONUP, wParam, MAKELPARAM(bu.x, bu.y)); // // } // //} // } return FALSE; } case WM_SHOW_WIN_POS: { log_debug(L"ShowWonPos: {}, {}", wParam, lParam); ScreenToolWnd::pWnd = ScreenToolWnd::ShowWindow(hInst, hWnd, WM_LBUTTONUP, wParam, lParam); break; } // Roll-up/Unroll (hard coded for now) case WM_NCRBUTTONUP:{ // Title bar if (wParam == HTCAPTION) { // Original window position RECT rect = { 0 }; if (GetWindowRect(hWnd, &rect)) { long width = rect.right - rect.left; long height = rect.bottom - rect.top; // The minimum tracking height of a window int minTrack = GetSystemMetrics(SM_CYMINTRACK); // Roll-up if (height != minTrack) { // Save old values wndOldWidth = width; wndOldHeight = height; height = minTrack; } // Unroll else { height = wndOldHeight; } // Resize window SetWindowPos(hWnd, NULL, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER | SWP_NOSENDCHANGING); } else { // On error, try to unroll with old values if (wndOldWidth != -1 && wndOldHeight != -1) { SetWindowPos(hWnd, NULL, 0, 0, wndOldWidth, wndOldHeight, SWP_NOMOVE | SWP_NOZORDER | SWP_NOSENDCHANGING); } } } return TRUE; } default: { // Quit message if (message == MT_HOOK_MSG_QUIT) { // Restore previous windows for (Tray_It it = mTrays.begin(); it != mTrays.end(); it++) { ShowWindow(it->first, SW_SHOW); } // Destroy all tray icons mTrays.clear(); // Uninstall menus MenuTools::Uninstall(hWnd); //FreeLibraryAndExitThread(hInst, 0); return TRUE; } } } return FALSE; } void InflateWnd(const LONG& diff, const HWND& hWnd) { WINDOWPLACEMENT wp = { sizeof(WINDOWPLACEMENT) }; GetWindowPlacement(hWnd, &wp); if (wp.showCmd == SW_MAXIMIZE && diff > 0) return; RECT wr = { 0 }; GetWindowRect(hWnd, &wr); InflateRect(&wr, diff, diff); //auto width = r.right - r.left; auto height = wr.bottom - wr.top; auto captionHeight = GetSystemMetrics(SM_CYCAPTION); if (height <= captionHeight) return; HMONITOR hMon = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST); MONITORINFO mi = { sizeof(MONITORINFO) }; GetMonitorInfo(hMon, &mi); auto mr = mi.rcWork; if (height >= (mr.bottom - mr.top)) { wp.showCmd = SW_MAXIMIZE; SetWindowPlacement(hWnd, &wp); return; } POINT pt = { 0 }; GetCursorPos(&pt); //ScreenToClient(hWnd, &pt); SetCursorPos(pt.x, pt.y - diff); wp.rcNormalPosition = wr; wp.showCmd = SW_NORMAL; SetWindowPlacement(hWnd, &wp); //if(wp.showCmd == SW_MAXIMIZE) //ShowWindow(hWnd, SW_NORMAL); //int l = //SetWindowPos(hWnd, HWND_NOTOPMOST, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_SHOWWINDOW); } // Sent messages LRESULT CALLBACK CallWndProc( _In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam ) { switch (nCode) { case HC_ACTION: { CWPSTRUCT* sMsg = (CWPSTRUCT*)lParam; HookProc(sMsg->hwnd, sMsg->message, sMsg->wParam, sMsg->lParam); } } return CallNextHookEx(NULL, nCode, wParam, lParam); } // Post messages LRESULT CALLBACK GetMsgProc( _In_ int code, _In_ WPARAM wParam, _In_ LPARAM lParam ) { switch (code) { case HC_ACTION: { if (wParam == PM_REMOVE) { MSG* pMsg = (MSG*)lParam; HookProc(pMsg->hwnd, pMsg->message, pMsg->wParam, pMsg->lParam); } } } return CallNextHookEx(NULL, code, wParam, lParam); } // Keyboard messages LRESULT CALLBACK CallKeyboardMsg( _In_ int code, _In_ WPARAM wParam, _In_ LPARAM lParam ) { switch (code) { case HC_ACTION: { if (ScreenToolWnd::pWnd && wParam == VK_ESCAPE) { ScreenToolWnd::pWnd.reset(); } if(ScreenToolWnd::pWnd) { //BOOL upFlag = (HIWORD(lParam) & KF_UP) == KF_UP; // transition-state flag, 1 on keyup //ScreenToolWnd::pWnd->WndProc(ScreenToolWnd::pWnd->GetHwnd(), upFlag ? WM_KEYUP:WM_KEYDOWN, wParam, lParam); } } } return CallNextHookEx(NULL, code, wParam, lParam); } HOOKPROC hkCallWndProc = CallWndProc; HOOKPROC hkGetMsgProc = GetMsgProc; HOOKPROC hkCallKeyboardMsg = CallKeyboardMsg;
24.078029
121
0.624851
[ "transform" ]
b52775210b4752d7d2d0f9a636194636ef5ef6a3
2,876
cpp
C++
problems/elementarymath/output_validators/jeroen/check.cpp
stoman/CompetitiveProgramming
0000b64369b50e31c6f48939e837bdf6cece8ce4
[ "MIT" ]
2
2020-12-22T13:21:25.000Z
2021-12-12T22:26:26.000Z
problems/elementarymath/output_validators/jeroen/check.cpp
stoman/CompetitiveProgramming
0000b64369b50e31c6f48939e837bdf6cece8ce4
[ "MIT" ]
null
null
null
problems/elementarymath/output_validators/jeroen/check.cpp
stoman/CompetitiveProgramming
0000b64369b50e31c6f48939e837bdf6cece8ce4
[ "MIT" ]
null
null
null
#include <vector> #include <map> #include <iostream> #include <cstring> #include "streamcorr.h" using namespace std; int n; vector<int> a; vector<int> b; struct equation { int a; char op; int b; long long ans; }; struct solution { equation *eqs; // NULL means impossible, otherwise length == n }; solution read_sol(istream& in, void (*error)(const char *err, ...)) { solution ret; while (isspace(in.peek())) in.get(); if(in.peek() == 'i' || in.peek() == 'I') { // must be impossible string line; in >> line; if(strcasecmp(line.c_str(), "impossible") != 0) error("Invalid first line: %s", line.c_str()); ret.eqs = NULL; } else { // Must contain exactly n equations ret.eqs = new equation[n]; for(int i = 0; i < n; i++) { char eqsign; if(!(in >> ret.eqs[i].a >> ret.eqs[i].op >> ret.eqs[i].b >> eqsign >> ret.eqs[i].ans) || eqsign != '=') error("Equation %d is invalid", i + 1); } } return ret; } void check_valid(solution sol, void (*error)(const char *err, ...)) { if(sol.eqs == NULL) return; map<long long, int> used; for(int i = 0; i < n; i++) { if(sol.eqs[i].a != a[i]) error("First number in equation %d is %d but must be %d", i+1, sol.eqs[i].a, a[i]); if(sol.eqs[i].b != b[i]) error("Second number in equation %d is %d but must be %d", i+1, sol.eqs[i].b, b[i]); if(sol.eqs[i].op != '+' && sol.eqs[i].op != '-' && sol.eqs[i].op != '*') error("Invalid operator '%c' in equation %d", sol.eqs[i].op, i+1); long long ans; if(sol.eqs[i].op == '+') ans = (long long)a[i] + (long long)b[i]; if(sol.eqs[i].op == '-') ans = (long long)a[i] - (long long)b[i]; if(sol.eqs[i].op == '*') ans = (long long)a[i] * (long long)b[i]; if(sol.eqs[i].ans != ans) error("Answer in equation %d is %lld but must be %lld", i+1, sol.eqs[i].ans, ans); if(used.find(ans) != used.end()) error("Duplicate answer %lld in equations %d and %d", ans, used[ans], i+1); used[ans] = i + 1; } } int main(int argc, char **argv) { init_io(argc, argv); // reading input judge_in >> n; for(int i = 0; i < n; i++) { int na, nb; judge_in >> na >> nb; a.push_back(na); b.push_back(nb); } // Read judge and contestant output solution judge = read_sol(judge_ans, judge_error); solution team = read_sol(author_out, report_error); // do the real checking check_valid(judge, judge_error); check_valid(team, report_error); if(judge.eqs == NULL && team.eqs != NULL) { judge_error("Team found a valid solution but jury said 'impossible'"); } else if(judge.eqs != NULL && team.eqs == NULL) { report_error("Team said 'impossible' but jury has a valid solution"); } /* Check for trailing output in author file. */ string trash; if (judge_ans >> trash) judge_error("Trailing output in judge data"); if (author_out >> trash) report_error("Trailing output in team output"); /* Yay! */ accept(); return 0; }
26.878505
111
0.608136
[ "vector" ]
b53130d0237d363e303f9c6d6b38fae37c2d988f
839
cpp
C++
vm/builtin/weakref.cpp
godfat/rubinius
d6a7a3323af0348800118ccd0b13fdf80adbbcef
[ "BSD-3-Clause" ]
3
2015-02-02T01:21:27.000Z
2016-04-29T22:30:01.000Z
vm/builtin/weakref.cpp
godfat/rubinius
d6a7a3323af0348800118ccd0b13fdf80adbbcef
[ "BSD-3-Clause" ]
null
null
null
vm/builtin/weakref.cpp
godfat/rubinius
d6a7a3323af0348800118ccd0b13fdf80adbbcef
[ "BSD-3-Clause" ]
1
2018-03-04T03:19:02.000Z
2018-03-04T03:19:02.000Z
#include "builtin/weakref.hpp" #include "builtin/class.hpp" #include "object_utils.hpp" #include "gc/gc.hpp" #include "ontology.hpp" #include "configuration.hpp" namespace rubinius { void WeakRef::init(STATE) { Class* super_class; if(!LANGUAGE_18_ENABLED(state)) { super_class = G(basicobject); } else { super_class = G(object); } GO(cls_weakref).set(ontology::new_class(state, "WeakRef", super_class)); G(cls_weakref)->set_object_type(state, WeakRefType); } WeakRef* WeakRef::create(STATE, Object* obj) { WeakRef* ref = state->new_object<WeakRef>(G(cls_weakref)); ref->set_object(state, obj); return ref; } void WeakRef::Info::mark(Object* obj, ObjectMark& mark) { WeakRef* ref = as<WeakRef>(obj); if(ref->alive_p()) { mark.gc->add_weak_ref(obj); } } }
23.305556
76
0.656734
[ "object" ]
b53c041ad9c66eaa00cb92201192a62affe6cf46
925
cpp
C++
geeksforgeeks/Transitive closure of a Graph.cpp
him1411/algorithmic-coding-and-data-structures
685aa95539692daca68ce79c20467c335aa9bb7f
[ "MIT" ]
null
null
null
geeksforgeeks/Transitive closure of a Graph.cpp
him1411/algorithmic-coding-and-data-structures
685aa95539692daca68ce79c20467c335aa9bb7f
[ "MIT" ]
null
null
null
geeksforgeeks/Transitive closure of a Graph.cpp
him1411/algorithmic-coding-and-data-structures
685aa95539692daca68ce79c20467c335aa9bb7f
[ "MIT" ]
2
2018-10-04T19:01:52.000Z
2018-10-05T08:49:57.000Z
using namespace std; void dfs(vector<int> graph[],int adj[][1000],int i,int k,int visited[]) { visited[i]=1; for(int x=0;x<graph[i].size();x++) { if(!visited[graph[i][x]]) { adj[k][graph[i][x]]=1; dfs(graph,adj,graph[i][x],k,visited); } } } int main() { //code int t; cin>>t; while(t--) { int v; cin>>v; int adj[1000][1000]; vector<int > graph[v]; int visited[v]={0}; for(int i=0;i<v;i++) { for(int j=0;j<v;j++) { cin>>adj[i][j]; if(i==j) { adj[i][j]=1; } if(adj[i][j]==1) { graph[i].push_back(j); } } } for(int i=0;i<v;i++) { dfs(graph,adj,i,i,visited); memset(visited,0,sizeof(visited)); } for(int i=0;i<v;i++) { for(int j=0;j<v;j++) { cout<<adj[i][j]<<" "; } } cout<<endl; } return 0; }
16.517857
71
0.422703
[ "vector" ]
b53d4c5db615a374224f79dff0c124651a919cb0
4,350
cpp
C++
src/llvm/Random.cpp
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
src/llvm/Random.cpp
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
src/llvm/Random.cpp
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
/* * Random.cpp * * Created on: Sep 23, 2014 * Author: andy */ #include "Random.h" #include "ModelGeneratorContext.h" #include "LLVMIncludes.h" #include "rrLogger.h" #include "rrConfig.h" #include "rrUtils.h" #include <stdint.h> #if INTPTR_MAX == INT32_MAX #define RR_32BIT #elif INTPTR_MAX == INT64_MAX #define RR_64BIT #else #error "Environment not 32 or 64-bit." #endif using rr::Logger; using rr::Config; using rr::getMicroSeconds; using namespace llvm; namespace rrllvm { typedef cxx11_ns::normal_distribution<double> NormalDist; static int randomCount = 0; /** * random uniform distribution */ static double distrib_uniform(Random *random, double _min, double _max); static double distrib_normal(Random* random, double mu, double sigma); static Function* createGlobalMappingFunction(const char* funcName, llvm::FunctionType *funcType, Module *module); static void addGlobalMappings(const ModelGeneratorContext& ctx); static int64_t defaultSeed() { int64_t seed = Config::getValue(Config::RANDOM_SEED).convert<int>(); if (seed < 0) { // system time in mirsoseconds since 1970 seed = getMicroSeconds(); } return seed; } Random::Random(ModelGeneratorContext& ctx) { addGlobalMappings(ctx); setRandomSeed(defaultSeed()); randomCount++; } Random::Random(const Random& other) { *this = other; setRandomSeed(defaultSeed()); randomCount++; } Random::Random() { setRandomSeed(defaultSeed()); randomCount++; } Random& Random::operator =(const Random& rhs) { engine = rhs.engine; return *this; } Function* createGlobalMappingFunction(const char* funcName, llvm::FunctionType *funcType, Module *module) { return Function::Create(funcType, Function::InternalLinkage, funcName, module); } void addGlobalMappings(const ModelGeneratorContext& ctx) { llvm::Module *module = ctx.getModule(); LLVMContext& context = module->getContext(); llvm::ExecutionEngine *executionEngine = &ctx.getExecutionEngine(); Type *double_type = Type::getDoubleTy(context); Type *int_type = Type::getInt32Ty(context); // LLVM does not appear to have a true void ptr, so just use a pointer // to a byte, pointers are all the same size anyway. // used for the LLVMModelData::random which is not accessed by // generated llvm code anyway. // see also, llvm::StructType *ModelDataIRBuilder::createModelDataStructType(...) Type *voidPtrType = Type::getInt8PtrTy(context); Type* args_void_double_double[] = { voidPtrType, double_type, double_type }; executionEngine->addGlobalMapping( createGlobalMappingFunction("rr_distrib_uniform", FunctionType::get(double_type, args_void_double_double, false), module), (void*) distrib_uniform); executionEngine->addGlobalMapping( createGlobalMappingFunction("rr_distrib_normal", FunctionType::get(double_type, args_void_double_double, false), module), (void*) distrib_normal); } double distrib_uniform(Random *random, double _min, double _max) { Log(Logger::LOG_DEBUG) << "distrib_uniform(" << static_cast<void*>(random) << ", " << _min << ", " << _max << ")"; #ifdef CXX11_RANDOM cxx11_ns::uniform_real_distribution<double> dist(_min, _max); #else cxx11_ns::uniform_real<double> dist(_min, _max); #endif return dist(*random); } double distrib_normal(Random* random, double mu, double sigma) { Log(Logger::LOG_DEBUG) << "distrib_normal(" << static_cast<void*>(random) << ", " << mu << ", " << sigma << ")"; NormalDist normal(mu, sigma); return normal(*random); } Random::~Random() { --randomCount; Log(Logger::LOG_TRACE) << "deleted Random object, count: " << randomCount; } double Random::operator ()() { double range = engine.max() - engine.min(); return engine() / range; } void Random::setRandomSeed(int64_t val) { #ifdef RR_32BIT unsigned long maxl = std::numeric_limits<unsigned long>::max() - 2; unsigned long seed = val % maxl; engine.seed(seed); randomSeed = seed; #else engine.seed(val); randomSeed = val; #endif } int64_t Random::getRandomSeed() { return randomSeed; } } /* namespace rrllvm */
24.033149
92
0.672874
[ "object" ]
b53eaa529ac8a8f06a23d3f03c4a0671b64941fa
8,440
cpp
C++
plugins/robobo_imu_sensor.cpp
BPRamos/robobo-gazebo-simulator
105ef054d8e352f89a3b5dd3521f42a18c16c61a
[ "Apache-2.0" ]
3
2020-12-24T11:54:20.000Z
2021-02-16T20:26:17.000Z
plugins/robobo_imu_sensor.cpp
BPRamos/robobo-gazebo-simulator
105ef054d8e352f89a3b5dd3521f42a18c16c61a
[ "Apache-2.0" ]
2
2020-10-20T08:10:35.000Z
2020-10-20T11:27:16.000Z
plugins/robobo_imu_sensor.cpp
BPRamos/robobo-gazebo-simulator
105ef054d8e352f89a3b5dd3521f42a18c16c61a
[ "Apache-2.0" ]
5
2020-06-14T11:32:43.000Z
2021-11-25T23:57:27.000Z
/*This work has been funded by rosin.org (contract agreement 732287) through EP project "Robobo AI"*/ /******************************************************************************* * * Copyright 2019, Manufactura de Ingenios Tecnológicos S.L. * <http://www.mintforpeople.com> * * Redistribution, modification and use of this software are permitted under * terms of the Apache 2.0 License. * * This software is distributed in the hope that it will be useful, * but WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Apache 2.0 License for more details. * * You should have received a copy of the Apache 2.0 License along with * this software. If not, see <http://www.apache.org/licenses/>. * ******************************************************************************/ /* Derived from the work : /* Copyright [2015] [Alessandro Settimi] * * email: ale.settimi@gmail.com * * 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 "include/robobo/robobo_imu_sensor.h" namespace gazebo { GZ_REGISTER_SENSOR_PLUGIN(RoboboImuSensor) RoboboImuSensor::RoboboImuSensor() : SensorPlugin() { accelerometer_data = ignition::math::Vector3d(0, 0, 0); // gyroscope_data = ignition::math::Vector3d(0, 0, 0); orientation = ignition::math::Quaterniond(1, 0, 0, 0); seed = 0; sensor = NULL; } RoboboImuSensor::~RoboboImuSensor() { if (connection.get()) { connection.reset(); connection = event::ConnectionPtr(); } node->shutdown(); } void RoboboImuSensor::Load(sensors::SensorPtr sensor_, sdf::ElementPtr sdf_) { sdf = sdf_; sensor = dynamic_cast<sensors::ImuSensor *>(sensor_.get()); if (sensor == NULL) { ROS_FATAL("Error: Sensor pointer is NULL!"); return; } sensor->SetActive(true); robot_namespace = GetRobotNamespace(sensor_, sdf, "IMU Sensor"); if (!LoadParameters()) { ROS_FATAL("Error Loading Parameters!"); return; } if (!ros::isInitialized()) { ROS_FATAL("ROS has not been initialized!"); return; } node = new ros::NodeHandle(this->robot_namespace); accelPub = node->advertise<geometry_msgs::Accel>(robot_namespace + "accel", 1); orientationPub = node->advertise<geometry_msgs::Quaternion>(robot_namespace + "orientation", 1); orientationEulerPub = node->advertise<robobo_msgs::OrientationEuler>(robot_namespace + "orientation_euler", 1); init_pose.Pos()=(0,0,0); init_pose.Rot()=ignition::math::Quaterniond(ignition::math::Vector3d(3.1416,-1.5708,0)); sensor->SetPose(init_pose); connection = event::Events::ConnectWorldUpdateBegin(boost::bind(&RoboboImuSensor::UpdateChild, this, _1)); last_time = sensor->LastUpdateTime(); } void RoboboImuSensor::UpdateChild(const common::UpdateInfo & /*_info*/) { common::Time current_time = sensor->LastUpdateTime(); ignition::math::Vector3d newAccelData = sensor->LinearAcceleration(); ignition::math::Quaterniond newOrientationData = offset.Rot() * sensor->Orientation(); if (update_rate > 0 && (current_time - last_time).Double() < 1.0 / update_rate) // update rate check return; if (orientationPub.getNumSubscribers() > 0 && orientation.X() != newOrientationData.X() && orientation.Y() != newOrientationData.Y() && orientation.Z() != newOrientationData.Z() && orientation.W() != newOrientationData.W()) { // gyroscope_data = sensor->AngularVelocity(); orientation = newOrientationData; // applying offsets to the orientation measurement // Guassian noise is applied to all measurements orient_msg.x = orientation.X() + GuassianKernel(0, gaussian_noise); orient_msg.y = orientation.Y() + GuassianKernel(0, gaussian_noise); orient_msg.z = orientation.Z() + GuassianKernel(0, gaussian_noise); orient_msg.w = orientation.W() + GuassianKernel(0, gaussian_noise); orientationPub.publish(orient_msg); } ignition::math::Vector3d newOrientationEulerData=newOrientationData.Euler(); if (orientationEulerPub.getNumSubscribers() > 0 && orientationEuler.X() != newOrientationEulerData.X() && orientationEuler.Y() != newOrientationEulerData.Y() && orientationEuler.Z() != newOrientationEulerData.Z()) { orientationEuler = newOrientationEulerData; orientEuler_msg.roll.data=orientationEuler.X()*57.3; orientEuler_msg.pitch.data=orientationEuler.Y()*57.3; orientEuler_msg.yaw.data=orientationEuler.Z()*57.3; orientEuler_msg.vector.x=orientEuler_msg.roll.data; orientEuler_msg.vector.y=orientEuler_msg.pitch.data; orientEuler_msg.vector.z=orientEuler_msg.yaw.data; orientationEulerPub.publish(orientEuler_msg); } if (accelPub.getNumSubscribers() > 0 && accelerometer_data.X() != newAccelData.X() && accelerometer_data.Y() != newAccelData.Y() && accelerometer_data.Z() != newAccelData.Z()) { accelerometer_data = newAccelData; accel_msg.linear.x = accelerometer_data.X()+9.8*sin(newOrientationEulerData.Y()) - GuassianKernel(0, gaussian_noise); accel_msg.linear.y = accelerometer_data.Y() + GuassianKernel(0, gaussian_noise); accel_msg.linear.z = accelerometer_data.Z()-9.8*cos(newOrientationEulerData.Y()) - GuassianKernel(0, gaussian_noise); // publishing data accelPub.publish(accel_msg); } ros::spinOnce(); last_time = current_time; } double RoboboImuSensor::GuassianKernel(double mu, double sigma) { // generation of two normalized uniform random variables double U1 = static_cast<double>(rand_r(&seed)) / static_cast<double>(RAND_MAX); double U2 = static_cast<double>(rand_r(&seed)) / static_cast<double>(RAND_MAX); // using Box-Muller transform to obtain a varaible with a standard normal distribution double Z0 = sqrt(-2.0 * ::log(U1)) * cos(2.0 * M_PI * U2); // scaling Z0 = sigma * Z0 + mu; return Z0; } bool RoboboImuSensor::LoadParameters() { // loading parameters from the sdf file // NAMESPACE // std::string scoped_name = sensor->ParentName(); // std::size_t it = scoped_name.find(":"); // robot_namespace = "/" +scoped_name.substr(0,it)+"/"; // UPDATE RATE if (sdf->HasElement("updateRateHZ")) { update_rate = sdf->Get<double>("updateRateHZ"); ROS_INFO_STREAM("<updateRateHZ> set to: " << update_rate); } else { update_rate = 1.0; ROS_WARN_STREAM("missing <updateRateHZ>, set to default: " << update_rate); } // NOISE if (sdf->HasElement("gaussianNoise")) { gaussian_noise = sdf->Get<double>("gaussianNoise"); ROS_INFO_STREAM("<gaussianNoise> set to: " << gaussian_noise); } else { gaussian_noise = 0.0; ROS_WARN_STREAM("missing <gaussianNoise>, set to default: " << gaussian_noise); } // POSITION OFFSET, UNUSED if (sdf->HasElement("xyzOffset")) { offset.Pos() = sdf->Get<ignition::math::Vector3d>("xyzOffset"); ROS_INFO_STREAM("<xyzOffset> set to: " << offset.Pos()[0] << ' ' << offset.Pos()[1] << ' ' << offset.Pos()[2]); } else { offset.Pos() = ignition::math::Vector3d(0, 0, 0); ROS_WARN_STREAM("missing <xyzOffset>, set to default: " << offset.Pos()[0] << ' ' << offset.Pos()[1] << ' ' << offset.Pos()[2]); } // ORIENTATION OFFSET if (sdf->HasElement("rpyOffset")) { offset.Rot() = ignition::math::Quaterniond(sdf->Get<ignition::math::Vector3d>("rpyOffset")); ROS_INFO_STREAM("<rpyOffset> set to: " << offset.Rot().Roll() << ' ' << offset.Rot().Pitch() << ' ' << offset.Rot().Yaw()); } else { offset.Rot() = ignition::math::Quaterniond::Identity; ROS_WARN_STREAM("missing <rpyOffset>, set to default: " << offset.Rot().Roll() << ' ' << offset.Rot().Pitch() << ' ' << offset.Rot().Yaw()); } return true; } } // namespace gazebo
34.590164
121
0.663152
[ "vector", "transform" ]
b54125ac4452b7b8b05eea04ff6b00c761faa565
1,642
hxx
C++
MddProxyGit/WorkDispatcher.hxx
dkhedekar/ProxyDataRouter
db49040de93085d397b7a057bf2d759dd65f48ac
[ "0BSD" ]
2
2015-05-28T20:25:32.000Z
2015-05-29T13:15:35.000Z
MddProxyGit/WorkDispatcher.hxx
dkhedekar/ProxyDataRouter
db49040de93085d397b7a057bf2d759dd65f48ac
[ "0BSD" ]
null
null
null
MddProxyGit/WorkDispatcher.hxx
dkhedekar/ProxyDataRouter
db49040de93085d397b7a057bf2d759dd65f48ac
[ "0BSD" ]
null
null
null
/* * WorkDispatcher.hxx * * Created on: May 12, 2015 * Author: kheddar */ #ifndef WORKDISPATCHER_HXX_ #define WORKDISPATCHER_HXX_ #include "PendingWorkQueue.hxx" #include "Worker.hxx" #include "Socket.hxx" #include <vector> #include <map> #include <sys/epoll.h> #define MAX_WORKER_THREADS 10 namespace mdm { namespace mddproxy { /** * @brief * Dispatches work from the work queue to the worker threads * Spawns more worker threads if needed */ typedef std::map<int,Socket*> WorkItemsT; typedef WorkItemsT::iterator WorkItemsItT; class WorkDispatcher { public: explicit WorkDispatcher(WorkItemsT* rcvrs, size_t maxWorkerThreads = MAX_WORKER_THREADS); virtual ~WorkDispatcher(); void ProcessData(struct epoll_event* evList, int eventCount); void OnWorkComplete(Worker* worker); void JoinThreads(); int AddWorkers(size_t count=1); void WakeUpAllThreads(); private: WorkItemsT* receivers; PendingWorkQueue<Socket*>* pendingItems; std::deque<Worker*>* freeWorkers; std::deque<Worker*>* busyWorkers; std::vector<Worker*> workers; size_t totalWorkerCount; boost::mutex sync_lock; Worker* CreateNewWorker(); bool GetFreeWorker(Worker* &worker); void RecordNewBusyWorker(Worker* worker); size_t ReturnFreeWorker(Worker* worker); }; inline void WorkDispatcher::OnWorkComplete(Worker* worker) { if (pendingItems->Count() > 0) { worker->GetParams()->state = RESUME; worker->GetParams()->receiverSocket = pendingItems->Pop(); } else { worker->GetParams()->state = SLEEP_WAIT; ReturnFreeWorker(worker); } } } /* namespace mddproxy */ } /* namespace mdm */ #endif /* WORKDISPATCHER_HXX_ */
20.02439
90
0.735688
[ "vector" ]
b5431435458b84b3cddfb816153a6e5c6d4b6e97
1,761
cpp
C++
tables/typetable.cpp
Paracetamol56/Observeur2
d15e0adfaf9a517a01383abafb601673cda9fbfe
[ "Apache-2.0" ]
1
2022-01-19T21:40:25.000Z
2022-01-19T21:40:25.000Z
tables/typetable.cpp
Paracetamol56/Observeur2
d15e0adfaf9a517a01383abafb601673cda9fbfe
[ "Apache-2.0" ]
25
2021-08-22T23:07:48.000Z
2022-03-11T16:12:52.000Z
tables/typetable.cpp
Paracetamol56/Observeur2
d15e0adfaf9a517a01383abafb601673cda9fbfe
[ "Apache-2.0" ]
null
null
null
/** * Created on Tue Jul 31 2021 * * Copyright (c) 2021 - Mathéo G - All Right Reserved * * Licensed under the Apache License, Version 2.0 * Available on GitHub at https://github.com/Paracetamol56/Observeur2 */ #include "typetable.h" #include "ui_tabledialog.h" TypeTable::TypeTable(QWidget *parent, QSqlDatabase *db) : TableDialog(parent, db) { setWindowIcon(QIcon(":/Ressources/icons/icons8-nebula-96.png")); setWindowTitle("Tous les types"); m_ui->label->setText("Tous les types"); tablePopulate(); } void TypeTable::tablePopulate() { m_db->open(); QSqlQuery query; // Set the query query.prepare( "SELECT " "`category_name` AS `Nom`, " "`category_description` AS `Description` " "FROM `categories` " "WHERE 1"); if (query.exec() == false) { SqlError sqlError(ErrorPriority::Critical, "Impossible de selectionner les types", &query); sqlError.printMessage(); } // Setup a query model to hold the data QSqlQueryModel *model = new QSqlQueryModel(); model->setQuery(query); // Convert to a QSortFilterProxyModel QSortFilterProxyModel *sortModel = new QSortFilterProxyModel(); sortModel->setSourceModel(model); // Put the model into the table view m_ui->tableView->setModel(sortModel); // Table style m_ui->tableView->setSelectionMode(QAbstractItemView::NoSelection); m_ui->tableView->verticalHeader()->setVisible(false); m_ui->tableView->horizontalHeader()->setStretchLastSection(true); m_ui->tableView->resizeColumnToContents(0); m_ui->tableView->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); m_db->close(); }
27.952381
99
0.661556
[ "model" ]
b543e6d9f43f56a0a34b87f7c05ef1e4ee93f12b
3,921
cc
C++
PWGGA/NtuplizerTask/GJNtuples/example/photon_ml/update_ntuple.cc
nashimiz/AliPhysics
b688b622bdcb9926e09fe8652a2aa5bd1b3e775d
[ "BSD-3-Clause" ]
null
null
null
PWGGA/NtuplizerTask/GJNtuples/example/photon_ml/update_ntuple.cc
nashimiz/AliPhysics
b688b622bdcb9926e09fe8652a2aa5bd1b3e775d
[ "BSD-3-Clause" ]
null
null
null
PWGGA/NtuplizerTask/GJNtuples/example/photon_ml/update_ntuple.cc
nashimiz/AliPhysics
b688b622bdcb9926e09fe8652a2aa5bd1b3e775d
[ "BSD-3-Clause" ]
null
null
null
#include <numeric> #include <TFile.h> #include <TTree.h> #include <TLorentzVector.h> #include <TROOT.h> #include <TApplication.h> #include <TCanvas.h> #include <TStyle.h> #include <TH2D.h> #include <TProfile.h> #include <H5Cpp.h> #include <emcal.h> #define RANK 2 #define NCLUSTER_MAX (1U << 17) int main(int argc, char *argv[]) { if (argc < 3) { exit(EXIT_FAILURE); } KerasModel model; model.LoadModel("../../photon_discr.model"); TFile *root_file_in = TFile::Open(argv[1]); if (root_file_in == NULL) { return EXIT_FAILURE; } TDirectoryFile *df_in = dynamic_cast<TDirectoryFile *> (root_file_in->Get("AliAnalysisTaskNTGJ")); if (df_in == NULL) { return EXIT_FAILURE; } TTree *tree_event_in = dynamic_cast<TTree *> (df_in->Get("_tree_event")); if (tree_event_in == NULL) { return EXIT_FAILURE; } Float_t multiplicity_v0[64]; UInt_t ncluster; Float_t cluster_e[NCLUSTER_MAX]; Float_t cluster_eta[NCLUSTER_MAX]; Float_t cluster_phi[NCLUSTER_MAX]; Float_t cluster_s_nphoton[NCLUSTER_MAX][4]; UShort_t cluster_cell_id_max[NCLUSTER_MAX]; Float_t cell_e[17664]; tree_event_in->SetBranchAddress("multiplicity_v0", multiplicity_v0); tree_event_in->SetBranchAddress("ncluster", &ncluster); tree_event_in->SetBranchAddress("cluster_e", cluster_e); tree_event_in->SetBranchAddress("cluster_eta", cluster_eta); tree_event_in->SetBranchAddress("cluster_phi", cluster_phi); tree_event_in->SetBranchAddress("cluster_s_nphoton", cluster_s_nphoton); tree_event_in->SetBranchAddress("cluster_cell_id_max", cluster_cell_id_max); tree_event_in->SetBranchAddress("cell_e", cell_e); TFile *root_file_out = TFile::Open(argv[2], "recreate"); root_file_out->mkdir("AliAnalysisTaskNTGJ"); root_file_out->cd("AliAnalysisTaskNTGJ"); TTree *tree_event_out = tree_event_in->CloneTree(0); for (Long64_t i = 0; i < tree_event_in->GetEntries(); i++) { tree_event_in->GetEntry(i); for (UInt_t j = 0; j < ncluster; j++) { const double pt = cluster_e[j] / cosh(cluster_eta[j]); AliVCluster cluster; AliVCaloCells cell; AliVVZERO v0; const double vertex[3] = { 0 }; cluster._momentum.SetPtEtaPhiM(pt, cluster_eta[j], cluster_phi[j], 0); unsigned int sm_max; unsigned int nphi_max; to_sm_nphi(sm_max, nphi_max, cluster_cell_id_max[j]); unsigned int cell_id_5_5[25]; cell_5_5(cell_id_5_5, cluster_cell_id_max[j]); for (Int_t k = 0; k < 25; k++) { unsigned int sm; unsigned int nphi; to_sm_nphi(sm, nphi, cell_id_5_5[k]); cell._amplitude[cluster.GetCellsAbsId()[k]] = sm == sm_max ? cell_e[cell_id_5_5[k]] : 0; } v0._multiplicity_sum = 0; for (size_t k = 0; k < 64; k++) { v0._multiplicity_sum += multiplicity_v0[k]; } std::vector<float> activation = cluster_cell_keras_inference(&cluster, &cell, vertex, &v0, model); #if 0 if (cluster_e[j] >= 8) { fprintf(stderr, "%s:%d: %f %f %f %f %f\n", __FILE__, __LINE__, cluster_e[j], activation[0], activation[1], cluster_s_nphoton[j][1], cluster_s_nphoton[j][2]); } #endif std::copy(activation.begin(), activation.end(), cluster_s_nphoton[j] + 1); } tree_event_out->Fill(); } tree_event_out->AutoSave(); delete root_file_in; delete root_file_out; return EXIT_SUCCESS; }
29.044444
80
0.58735
[ "vector", "model" ]
b54f03aa42e45517036cc0e3d38a374a962d6f82
220
cpp
C++
Leetcode2/215.cpp
nolink/algorithm
29d15403a2d720771cf266a1ab04b0ab29d4cb6c
[ "MIT" ]
null
null
null
Leetcode2/215.cpp
nolink/algorithm
29d15403a2d720771cf266a1ab04b0ab29d4cb6c
[ "MIT" ]
null
null
null
Leetcode2/215.cpp
nolink/algorithm
29d15403a2d720771cf266a1ab04b0ab29d4cb6c
[ "MIT" ]
null
null
null
class Solution { public: int findKthLargest(vector<int>& nums, int k) { priority_queue<int> q; for(auto num : nums) q.push(num); for(int i=1;i<k;i++) q.pop(); return q.top(); } };
22
50
0.536364
[ "vector" ]
b54fc8cf805750deedb01e1a84c98e2339a8f995
5,238
hpp
C++
lib/Bitboard.hpp
waegemans/MChessTS
c84851d923308a605f8926b7a2ecf52c6478cc31
[ "MIT" ]
null
null
null
lib/Bitboard.hpp
waegemans/MChessTS
c84851d923308a605f8926b7a2ecf52c6478cc31
[ "MIT" ]
null
null
null
lib/Bitboard.hpp
waegemans/MChessTS
c84851d923308a605f8926b7a2ecf52c6478cc31
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <string> #include <string_view> #include <bitset> #include <vector> #include <cstring> #include <stdexcept> #include "Move.hpp" namespace chess { class Bitboard { private: uint64_t kings; uint64_t queens; uint64_t rooks; uint64_t knights; uint64_t bishops; uint64_t pawns; uint64_t occupiedWhite; uint64_t occupiedBlack; bool pov; std::bitset<4> castlingRights; std::optional<unsigned> enPassantFile; unsigned moveCounter; unsigned halfMoveCounter; mutable uint64_t controlled; mutable uint64_t pinnedHorizontal; mutable uint64_t pinnedVertical; mutable uint64_t pinnedDiagonal; mutable uint64_t pinnedAntidiagonal; mutable uint64_t pinnedEnPassant; mutable uint64_t checks; mutable bool cachedAttack; mutable std::optional<std::vector<Move>> legalMovesCache; private: void evalPawnAttack() const; void evalQueenLikeAttack() const; void evalQueenLikeAttackXray(int dleft, int dup) const; void evalKingAttack() const; void evalKnightAttack() const; void evalEnPassantPin() const; uint64_t &relevantPinMap(int dx, int dy) const; uint64_t pinnedAny() const; uint64_t pinnedForDirection(int dx, int dy) const; void resetCachedAttack() const; public: [[nodiscard]] uint64_t getKings() const { return kings; }; [[nodiscard]] uint64_t getQueens() const { return queens; }; [[nodiscard]] uint64_t getRooks() const { return rooks; }; [[nodiscard]] uint64_t getKnights() const { return knights; }; [[nodiscard]] uint64_t getBishops() const { return bishops; }; [[nodiscard]] uint64_t getPawns() const { return pawns; }; [[nodiscard]] bool getPov() const { return pov; }; [[nodiscard]] const std::bitset<4> &getCastlingRights() const { return castlingRights; }; [[nodiscard]] const std::optional<unsigned int> &getEnPassantFile() const { return enPassantFile; }; [[nodiscard]] uint64_t getOccupied(bool color) const { return color ? occupiedWhite : occupiedBlack; }; [[nodiscard]] uint64_t occupied() const { return occupiedWhite | occupiedBlack; }; [[nodiscard]] uint64_t getControlled() const { return controlled; }; unsigned int getMoveCounter() const { return moveCounter; }; unsigned int getHalfMoveCounter() const { return halfMoveCounter; }; uint64_t getPinnedHorizontal() const { return pinnedHorizontal; }; uint64_t getPinnedVertical() const { return pinnedVertical; }; uint64_t getPinnedDiagonal() const { return pinnedDiagonal; }; uint64_t getPinnedAntidiagonal() const { return pinnedAntidiagonal; }; bool isCachedAttack() const { return cachedAttack; }; [[nodiscard]] uint64_t getChecks() const { return checks; }; void evalAttack() const; void startpos(); void parseFEN(std::string_view fen); std::vector<Move> legalMoves() const; private: void kingMoves(std::vector<Move> &result) const; uint64_t getCheckBlockCaptureSquares() const; void queenLikeMoves(std::vector<Move> &result, uint64_t targetSquares) const; void queenLikeMovesSingleRay(std::vector<Move> &result, uint64_t targetSquares, int dx, int dy) const; void knightMoves(std::vector<Move> &result, uint64_t targetSquares) const; void pawnMoves(std::vector<Move> &result, uint64_t targetSquares) const; void castlingMoves(std::vector<Move> &result) const; private: void parseBoardFEN(std::string_view boardFen); void parsePovFEN(std::string_view povFen); void parseCastlingFEN(std::string_view castlingFen); void parseEnPassantFEN(std::string_view enPassantFen); void parseHalfMoveFEN(std::string_view halfMoveFen); public: std::string to_fen() const; [[nodiscard]] std::string to_string() const; void applyMoveSelf(const Move &move); Bitboard applyMoveCopy(const Move &move) const; private: void preApplyPromotion(uint64_t fromMask, const Move &move); void preApplyCastling(const Move &move); void preApplyToggleEnPassant(const Move &move); void preApplyEnPassantCapture(unsigned toSquare); void preApplyRemoveCastlingKingMove(); void preApplyRemoveCastlingRook(const Move &move); void movePiece(unsigned fromSquare, unsigned toSquare); void evalEnPassantLegality(); public: bool operator==(const Bitboard &other) const; static constexpr uint64_t canMoveToMask(int left, int up); static constexpr uint64_t applyOffset(int left, int up, uint64_t board); static void appendMoves(std::vector<Move>& result, uint64_t movablePieces, int dx, int dy, uint64_t promotable = 0); bool isGameOver() const; bool isCheck() const; bool isDraw50() const; bool isDrawInsufficient() const; }; // class Bitboard } // namespace chess
28.78022
124
0.66323
[ "vector" ]
b55ff85e5f59fb4922623b4ff07b64ac2ac3c1b0
257
cpp
C++
strings/shiftingLetters.cpp
Gooner1886/DSA-101
44092e10ad39bebbf7da93e897927106d5a45ae7
[ "MIT" ]
20
2022-01-04T19:36:14.000Z
2022-03-21T15:35:09.000Z
strings/shiftingLetters.cpp
Gooner1886/DSA-101
44092e10ad39bebbf7da93e897927106d5a45ae7
[ "MIT" ]
null
null
null
strings/shiftingLetters.cpp
Gooner1886/DSA-101
44092e10ad39bebbf7da93e897927106d5a45ae7
[ "MIT" ]
null
null
null
// Leetcode - 848 - Shifting Letters string shiftingLetters(string s, vector<int> &shifts) { int k = 0; for (int i = s.size() - 1; i >= 0; i--) { k = (k + shifts[i]) % 26; s[i] = (s[i] - 'a' + k) % 26 + 'a'; } return s; }
23.363636
53
0.455253
[ "vector" ]
b56db69d5079073867afdd617620d80a11aad000
15,028
cpp
C++
Enose_Simul/GasMapModelBase.cpp
OpenMORA/uma-olfaction-pkg
5c9caa3da605035e80a0f7eb5af39dc65a191983
[ "BSD-3-Clause" ]
1
2016-04-13T09:58:06.000Z
2016-04-13T09:58:06.000Z
Enose_Simul/GasMapModelBase.cpp
OpenMORA/uma-olfaction-pkg
5c9caa3da605035e80a0f7eb5af39dc65a191983
[ "BSD-3-Clause" ]
null
null
null
Enose_Simul/GasMapModelBase.cpp
OpenMORA/uma-olfaction-pkg
5c9caa3da605035e80a0f7eb5af39dc65a191983
[ "BSD-3-Clause" ]
null
null
null
/* +---------------------------------------------------------------------------+ | Open MORA (MObile Robot Arquitecture) | | | | http://sourceforge.net/p/openmora/home/ | | | | Copyright (C) 2010 University of Malaga | | | | This software was written by the Machine Perception and Intelligent | | Robotics (MAPIR) Lab, University of Malaga (Spain). | | Contact: Javier Gonzalez Monroy <jgmonroy@isa.uma.es> | | | | This file is part of the MORA project. | | | | MORA 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. | | | | MORA 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 MORA. If not, see <http://www.gnu.org/licenses/>. | | | +---------------------------------------------------------------------------+ */ #include "GasMapModels.h" // Include all, for the class factory #include <mrpt/system/string_utils.h> #include <mrpt/utils/color_maps.h> #include <mrpt/opengl.h> #include <mrpt/random.h> using namespace std; using namespace mrpt; using namespace mrpt::system; using namespace mrpt::obs; using namespace mrpt::maps; using namespace mrpt::utils; using namespace mrpt::random; // Class factory: GasMapModelBase * GasMapModelBase::createFromName( const std::string &className, const mrpt::utils::CConfigFileBase &config_source ) { if (strCmpI(className, "GasMapModel_Static")) return new GasMapModel_Static(config_source); else if (strCmpI(className, "GasMapModel_Dynamic")) return new GasMapModel_Dynamic(config_source); else return NULL; } /** Constructor: call with \a m_ini (member of any CMapirMOOSApp) as parameter from your MOOS module. */ GasMapModelBase::GasMapModelBase(const mrpt::utils::CConfigFileBase &config_source) { // Load # of maps: //! @moos_param num_gas_maps Number of gasMaps to simulate const int num_maps = config_source.read_int("","num_gas_maps",0,true); //! @moos_param voltage_max All sensor output concentrations data are normalized scaled by this value m_voltage_max = config_source.read_double("","voltage_max",5.0); // Load & create each map: m_all_gas_grid_maps.resize(num_maps); printf("[GasMapModelBase] Creating %i GasMap(s)\n",num_maps); for (int i=0;i<num_maps;i++) { // Create map: mrpt::maps::CGasConcentrationGridMap2DPtr &gasmap_ptr = m_all_gas_grid_maps[i].second; gasmap_ptr = mrpt::maps::CGasConcentrationGridMap2D::Create(); mrpt::maps::CGasConcentrationGridMap2D & gasmap = *gasmap_ptr; // Extra info field: InfoPerMap &info = m_all_gas_grid_maps[i].first; // Set all params from .moos file: // ------------------------------------------------------------ std::stringstream ss; //! @moos_param map_gastype The ID of the gasMap. Usually is the model of a gas sensor (0x2620) const std::string sType = trim( config_source.read_string("",format("map%i_gastype",i),"",true) ); if (sType.size()>=2 && sType[0]=='0' && sType[1]=='x') sscanf(sType.c_str(),"%X",&info.gas_type); else sscanf(sType.c_str(),"%u",&info.gas_type); printf("[GasMapModelBase] map%i_gastype = %X\n",i,info.gas_type); // Initialization type: //! @moos_param map_init_from Possible values: "bitmap", "uniform" const std::string sInitType = trim( config_source.read_string("",format("map%i_init_from",i),"",true) ); printf("[GasMapModelBase] map%i_init_from = %s\n",i,sInitType.c_str()); if (strCmpI("bitmap",sInitType)) { //! @moos_param map_x0 [bitmap] Position on the simulation reference system to position the gasmap (m) const double x0 = config_source.read_double("",format("map%i_x0",i),0,true); //! @moos_param map_y0 [bitmap] Position on the simulation reference system to position the gasmap (m) const double y0 = config_source.read_double("",format("map%i_y0",i),0,true); //! @moos_param map_resolution [bitmap] (meters/pixel) const double res = config_source.read_double("",format("map%i_resolution",i),0,true); //! @moos_param map_bitmap [bitmap] Path to the initial bitmap image used to initialize the gas concentration const string sFil = config_source.read_string("",format("map%i_bitmap",i),"",true); printf("[GasMapModelBase] map%i_initial_bitmap = %s\n",i,sFil.c_str()); mrpt::utils::CImage img; if (!img.loadFromFile(sFil, 0 /* force grayscale */)) { cout << "Error loading bitmap image for gas map: " << sFil.c_str() << endl; throw std::runtime_error(mrpt::format("Error loading bitmap image for gas map: '%s'",sFil.c_str() )); } ASSERT_(!img.isColor()) //flip gasmap to fit the gridmap img.flipVertical(); const unsigned int w=img.getWidth(); const unsigned int h=img.getHeight(); gasmap.setSize(x0,x0+res*w, y0,y0+res*h, res); const double K = 1./255.; for (unsigned int y=0;y<h;y++) { unsigned int yy=h-1-y; const unsigned char * ptr_img = img.get_unsafe(0,yy,0); for (unsigned int xx=0;xx<w;xx++) { mrpt::maps::TRandomFieldCell * cell = gasmap.cellByIndex(xx,yy); cell->kf_mean = (*ptr_img++) * K; } } } else if (strCmpI("uniform",sInitType)) { //! @moos_param map_x0 [uniform] Coordinates of the initial point (meters) const double x0 = config_source.read_double("",format("map%i_x0",i),0,true); //! @moos_param map_y0 [uniform] Coordinates of the initial point (meters) const double y0 = config_source.read_double("",format("map%i_y0",i),0,true); //! @moos_param map_x1 [uniform] Coordinates of the final point (meters) const double x1 = config_source.read_double("",format("map%i_x1",i),0,true); //! @moos_param map_y1 [uniform] Coordinates of the final point (meters) const double y1 = config_source.read_double("",format("map%i_y1",i),0,true); //! @moos_param map_resolution [uniform] meters/pixel const double res = config_source.read_double("",format("map%i_resolution",i),0,true); //! @moos_param map_value [uniform] Value to asign to the uniform gasMap const double value = config_source.read_double("",format("map%i_value",i),0,true); // Set size: gasmap.setSize(x0,x1,y0,y1,res); // Fill all cells with default value: mrpt::maps::TRandomFieldCell defCell; defCell.kf_mean = value; gasmap.fill(defCell); } else throw std::runtime_error("Invalid value found in 'map%i_init_from'"); // Derived classes will continue reading from the .moos file any other extra params at their contructors. } } /** Simulate the passage of time in all the gas maps. * \param[in] At Time increment, in seconds. * This method internally call impl_simulateTimeInterval() for each individual map. * \exception std::exception Upon any error. */ void GasMapModelBase::simulateTimeInterval(const double At) { ASSERT_ABOVEEQ_(At,0) if (At==0 || m_all_gas_grid_maps.empty()) return; // Nothing to do. for (size_t i=0;i<m_all_gas_grid_maps.size();i++) { InfoPerMap &info = m_all_gas_grid_maps[i].first; CGasConcentrationGridMap2D & gasMap = *(m_all_gas_grid_maps[i].second); this->impl_simulateTimeInterval(At,info,gasMap); } } /** Obtain a 3D view of the current state of all gas maps: */ void GasMapModelBase::getAs3DObject(mrpt::opengl::CSetOfObjectsPtr &glObj) const { glObj->clear(); // TODO Javi: represent maps as a plan gridmap with transparency & some special colormap, // each map (each "chemical") can be in a different color, colormaps, etc. // New options can be created and loaded from the .moos file at start up. std::string m_3D_map_mode = "default"; mrpt::utils::TColormap color_map_type = mrpt::utils::cmJET; for (size_t i=0;i<m_all_gas_grid_maps.size();i++) { const CGasConcentrationGridMap2D & gasmap = *(m_all_gas_grid_maps[i].second); mrpt::opengl::CSetOfObjectsPtr obj = mrpt::opengl::CSetOfObjects::Create(); if (strCmpI(m_3D_map_mode,"default")) { const size_t w = gasmap.getSizeX(); const size_t h = gasmap.getSizeY(); CImage img(w,h, CH_RGB); CImage img_transparency(w,h, CH_GRAY); for (size_t y=0;y<h;y++) { const size_t yy=h-1-y; unsigned char * ptr_img = img.get_unsafe(0,yy,0); unsigned char * ptr_img_transp = img_transparency.get_unsafe(0,yy,0); for (size_t xx=0;xx<w;xx++) { const mrpt::maps::TRandomFieldCell * cell = gasmap.cellByIndex(xx,yy); const float in_gray = cell->kf_mean; // RGB color: mrpt::utils::TColorf col; mrpt::utils::colormap(color_map_type, in_gray, col.R,col.G,col.B); (*ptr_img++) = static_cast<unsigned char>(col.R * 255.f); (*ptr_img++) = static_cast<unsigned char>(col.G * 255.f); (*ptr_img++) = static_cast<unsigned char>(col.B * 255.f); // Transparency: (There're many possibilities here...) (*ptr_img_transp++) = static_cast<unsigned char>(col.R * 255.f); } } mrpt::opengl::CTexturedPlanePtr gl_pl = mrpt::opengl::CTexturedPlane::Create(); gl_pl->setPlaneCorners( gasmap.getXMin(), gasmap.getXMax(), gasmap.getYMin(), gasmap.getYMax() ); gl_pl->assignImage_fast(img,img_transparency); // _fast: move semantics obj->insert(gl_pl); } // else if (mrpt::utils::StrCmpI(m_3D_map_mode,"XXX")) // { // // obj... // } // Append to output: glObj->insert(obj); } } /** Simulate all the noisy & low-passed readings from a set of enoses. */ void GasMapModelBase::simulateReadings( const mrpt::poses::CPose2D &robotPose2D, std::vector<InfoPerENose> &eNoses, const mrpt::system::TTimeStamp &timestamp, const double At_since_last_seconds, const std::string &sensorLabel, mrpt::obs::CObservationGasSensors &obs ) { obs.timestamp = timestamp; obs.sensorLabel = sensorLabel; for (size_t nEnose=0;nEnose<eNoses.size();nEnose++) { InfoPerENose & enose = eNoses[nEnose]; mrpt::obs::CObservationGasSensors::TObservationENose eNoseData; eNoseData.hasTemperature = false; eNoseData.isActive = false; eNoseData.eNosePoseOnTheRobot.x = enose.x; eNoseData.eNosePoseOnTheRobot.y = enose.y; eNoseData.eNosePoseOnTheRobot.z = 0.0; // Position of this eNose: mrpt::math::TPoint2D sensorPose2D; robotPose2D.composePoint( enose.x,enose.y, // local sensorPose2D.x,sensorPose2D.y // global ); // For the first iteration: const size_t nMaps = m_all_gas_grid_maps.size(); if (enose.last_real_concentrations.size()!=nMaps) enose.last_real_concentrations.resize(nMaps); if (enose.last_outputs.size()!=nMaps) enose.last_outputs.resize(nMaps); // Simulate readings in each gas map: for (size_t nMap=0; nMap<nMaps;nMap++) { // get map data: const mrpt::maps::CGasConcentrationGridMap2DPtr &gasmap_ptr = m_all_gas_grid_maps[nMap].second; const mrpt::maps::CGasConcentrationGridMap2D & gasmap = *gasmap_ptr; InfoPerMap &mapinfo = m_all_gas_grid_maps[nMap].first; // Simulate noise-free reading: const double real_gas_concentration = getRealConcentration(gasmap,sensorPose2D); const double real_last_concentration = enose.last_real_concentrations[nMap]; // Rise or decay? //const double tau = (real_gas_concentration>=real_last_concentration) ? enose.tau_rise : enose.tau_decay; const double tau = (real_gas_concentration >= enose.last_outputs[nMap]) ? enose.tau_rise : enose.tau_decay; // 1st order model: // B(z) 1 // H(z) = ------------ = --------------- // A(Z) 1 - a*z^{-1} // // Time impulse response: ... // // 1st order implementation! const double last_output = enose.last_outputs[nMap]; const double no_noise_reading = last_output+(1.-std::exp(-At_since_last_seconds / tau))*(real_gas_concentration-last_output); // Add noises: const double final_reading = no_noise_reading + randomGenerator.drawGaussian1D(enose.noise_offset, enose.noise_std ); const double final_reading_volt = std::max(0.,std::min(1.,final_reading)) *m_voltage_max; // save data to eNose observation: eNoseData.sensorTypes.push_back(mapinfo.gas_type); eNoseData.readingsVoltage.push_back(final_reading_volt); #if 1 cout << "eNose #"<< nEnose << " Map #"<< nMap << " -> Real: " << real_gas_concentration << " Sensed [0-1]: " << final_reading << endl; #endif // Write values for next iter: enose.last_real_concentrations[nMap] = real_gas_concentration; enose.last_outputs[nMap] = final_reading; } // Done with this eNose obs.m_readings.push_back( eNoseData ); } } /** Static method that returns the REAL instantaneous concentration at any point of a map (or 0 if it's out of the map) */ double GasMapModelBase::getRealConcentration( const mrpt::maps::CGasConcentrationGridMap2D & gasmap, const mrpt::math::TPoint2D &pt ) { // TODO JAVI: This can be done better with linear interpolation of neighbors, etc. // See methods: cellByIndex(), x2idx(), y2idx()... const mrpt::maps::TRandomFieldCell * cell_xy = gasmap.cellByPos(pt.x,pt.y); if (cell_xy) { return cell_xy->kf_mean; } else { return 0; } } /** save the current state of all gas maps: */ void GasMapModelBase::getAsMatrix(mrpt::math::CMatrix &mat) const { bool first = true; for (size_t i=0;i<m_all_gas_grid_maps.size();i++) { const CGasConcentrationGridMap2D & gasmap = *(m_all_gas_grid_maps[i].second); const size_t w = gasmap.getSizeX(); const size_t h = gasmap.getSizeY(); mrpt::math::CMatrix M(h,w); try { for (size_t i=0; i<h; i++) { for (size_t j=0; j<w; j++) { M(i,j) = gasmap.cellByIndex(j,i)->kf_mean; } } // Append to output: if (first) { mat.resize(h,w); mat.fill(0.0); first = false; } mat += M; } catch (std::exception e) { cout << "exception: " << e.what() << endl; } } }
36.833333
138
0.638475
[ "vector", "model", "3d" ]
b57326de2ad9edfe189437a24f089cdbcfba9a38
7,930
cpp
C++
aegisub/src/ass_file.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
1
2018-02-12T02:44:57.000Z
2018-02-12T02:44:57.000Z
aegisub/src/ass_file.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
null
null
null
aegisub/src/ass_file.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
2
2018-02-12T03:46:24.000Z
2018-02-12T14:36:07.000Z
// Copyright (c) 2005, Rodrigo Braz Monteiro // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the Aegisub Group nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Aegisub Project http://www.aegisub.org/ /// @file ass_file.cpp /// @brief Overall storage of subtitle files, undo management and more /// @ingroup subs_storage #include "config.h" #include "ass_file.h" #include "ass_attachment.h" #include "ass_dialogue.h" #include "ass_info.h" #include "ass_style.h" #include "options.h" #include "utils.h" #include <libaegisub/dispatch.h> #include <libaegisub/of_type_adaptor.h> #include <algorithm> #include <boost/algorithm/string/case_conv.hpp> #include <boost/filesystem/path.hpp> namespace std { template<> void swap(AssFile &lft, AssFile &rgt) { lft.swap(rgt); } } AssFile::~AssFile() { auto copy = new EntryList; copy->swap(Line); agi::dispatch::Background().Async([=]{ copy->clear_and_dispose([](AssEntry *e) { delete e; }); delete copy; }); } void AssFile::LoadDefault(bool defline) { Line.push_back(*new AssInfo("Title", "Default Aegisub file")); Line.push_back(*new AssInfo("ScriptType", "v4.00+")); Line.push_back(*new AssInfo("WrapStyle", "0")); Line.push_back(*new AssInfo("ScaledBorderAndShadow", "yes")); if (!OPT_GET("Subtitle/Default Resolution/Auto")->GetBool()) { Line.push_back(*new AssInfo("PlayResX", std::to_string(OPT_GET("Subtitle/Default Resolution/Width")->GetInt()))); Line.push_back(*new AssInfo("PlayResY", std::to_string(OPT_GET("Subtitle/Default Resolution/Height")->GetInt()))); } Line.push_back(*new AssInfo("YCbCr Matrix", "None")); Line.push_back(*new AssStyle); if (defline) Line.push_back(*new AssDialogue); } void AssFile::swap(AssFile &that) throw() { Line.swap(that.Line); } AssFile::AssFile(const AssFile &from) { Line.clone_from(from.Line, std::mem_fun_ref(&AssEntry::Clone), [](AssEntry *e) { delete e; }); } AssFile& AssFile::operator=(AssFile from) { std::swap(*this, from); return *this; } void AssFile::InsertLine(AssEntry *entry) { if (Line.empty()) { Line.push_back(*entry); return; } // Search for insertion point entryIter it = Line.end(); do { --it; if (it->Group() <= entry->Group()) { Line.insert(++it, *entry); return; } } while (it != Line.begin()); Line.push_front(*entry); } void AssFile::InsertAttachment(agi::fs::path const& filename) { AssEntryGroup group = AssEntryGroup::GRAPHIC; auto ext = boost::to_lower_copy(filename.extension().string()); if (ext == ".ttf" || ext == ".ttc" || ext == ".pfb") group = AssEntryGroup::FONT; InsertLine(new AssAttachment(filename, group)); } std::string AssFile::GetScriptInfo(std::string const& key) const { for (const auto info : Line | agi::of_type<AssInfo>()) { if (boost::iequals(key, info->Key())) return info->Value(); } return ""; } int AssFile::GetScriptInfoAsInt(std::string const& key) const { return atoi(GetScriptInfo(key).c_str()); } std::string AssFile::GetUIState(std::string const& key) const { auto value = GetScriptInfo("Aegisub " + key); if (value.empty()) value = GetScriptInfo(key); return value; } int AssFile::GetUIStateAsInt(std::string const& key) const { return atoi(GetUIState(key).c_str()); } void AssFile::SaveUIState(std::string const& key, std::string const& value) { if (OPT_GET("App/Save UI State")->GetBool()) SetScriptInfo("Aegisub " + key, value); } void AssFile::SetScriptInfo(std::string const& key, std::string const& value) { for (auto info : Line | agi::of_type<AssInfo>()) { if (boost::iequals(key, info->Key())) { if (value.empty()) delete info; else info->SetValue(value); return; } } if (!value.empty()) InsertLine(new AssInfo(key, value)); } void AssFile::GetResolution(int &sw,int &sh) const { sw = GetScriptInfoAsInt("PlayResX"); sh = GetScriptInfoAsInt("PlayResY"); // Gabest logic? if (sw == 0 && sh == 0) { sw = 384; sh = 288; } else if (sw == 0) { if (sh == 1024) sw = 1280; else sw = sh * 4 / 3; } else if (sh == 0) { // you are not crazy; this doesn't make any sense if (sw == 1280) sh = 1024; else sh = sw * 3 / 4; } } std::vector<std::string> AssFile::GetStyles() const { std::vector<std::string> styles; for (auto style : Line | agi::of_type<AssStyle>()) styles.push_back(style->name); return styles; } AssStyle *AssFile::GetStyle(std::string const& name) { for (auto style : Line | agi::of_type<AssStyle>()) { if (boost::iequals(style->name, name)) return style; } return nullptr; } int AssFile::Commit(wxString const& desc, int type, int amend_id, AssEntry *single_line) { AssFileCommit c = { desc, &amend_id, single_line }; PushState(c); std::set<const AssEntry*> changed_lines; if (single_line) changed_lines.insert(single_line); AnnounceCommit(type, changed_lines); return amend_id; } bool AssFile::CompStart(const AssDialogue* lft, const AssDialogue* rgt) { return lft->Start < rgt->Start; } bool AssFile::CompEnd(const AssDialogue* lft, const AssDialogue* rgt) { return lft->End < rgt->End; } bool AssFile::CompStyle(const AssDialogue* lft, const AssDialogue* rgt) { return lft->Style < rgt->Style; } bool AssFile::CompActor(const AssDialogue* lft, const AssDialogue* rgt) { return lft->Actor < rgt->Actor; } bool AssFile::CompEffect(const AssDialogue* lft, const AssDialogue* rgt) { return lft->Effect < rgt->Effect; } bool AssFile::CompLayer(const AssDialogue* lft, const AssDialogue* rgt) { return lft->Layer < rgt->Layer; } void AssFile::Sort(CompFunc comp, std::set<AssDialogue*> const& limit) { Sort(Line, comp, limit); } namespace { inline bool is_dialogue(AssEntry *e, std::set<AssDialogue*> const& limit) { AssDialogue *d = dynamic_cast<AssDialogue*>(e); return d && (limit.empty() || limit.count(d)); } } void AssFile::Sort(EntryList &lst, CompFunc comp, std::set<AssDialogue*> const& limit) { auto compE = [&](AssEntry const& a, AssEntry const& b) { return comp(static_cast<const AssDialogue*>(&a), static_cast<const AssDialogue*>(&b)); }; // Sort each block of AssDialogues separately, leaving everything else untouched for (entryIter begin = lst.begin(); begin != lst.end(); ++begin) { if (!is_dialogue(&*begin, limit)) continue; entryIter end = begin; while (end != lst.end() && is_dialogue(&*end, limit)) ++end; // used instead of std::list::sort for partial list sorting EntryList tmp; tmp.splice(tmp.begin(), lst, begin, end); tmp.sort(compE); lst.splice(end, tmp); begin = --end; } }
29.37037
116
0.696091
[ "vector" ]
b5761c9da68c9cd79a5d016f79140c114cc3f20d
15,533
cpp
C++
Sources/Elastos/Packages/Providers/MediaProvider/src/elastos/droid/providers/media/MediaScannerService.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Packages/Providers/MediaProvider/src/elastos/droid/providers/media/MediaScannerService.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Packages/Providers/MediaProvider/src/elastos/droid/providers/media/MediaScannerService.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/providers/media/MediaProvider.h" #include "elastos/droid/providers/media/MediaScannerService.h" #include "elastos/droid/providers/media/CIMediaScannerService.h" #include "Elastos.Droid.App.h" #include "Elastos.Droid.Content.h" #include "Elastos.Droid.Media.h" #include "Elastos.Droid.Net.h" #include "Elastos.Droid.Os.h" #include "Elastos.Droid.Provider.h" #include "Elastos.CoreLibrary.h" #include "Elastos.CoreLibrary.IO.h" #include "Elastos.CoreLibrary.Utility.h" #include <elastos/utility/logging/Logger.h> #include <elastos/utility/Arrays.h> #include <elastos/droid/os/Process.h> #include <elastos/droid/os/Looper.h> #include <elastos/droid/os/Environment.h> #include <elastos/core/Thread.h> #include <elastos/core/AutoLock.h> using Elastos::Droid::App::IService; using Elastos::Droid::Content::CIntent; using Elastos::Droid::Content::CContentValues; using Elastos::Droid::Content::IContentValues; using Elastos::Droid::Content::IContentResolver; using Elastos::Droid::Content::Res::IResources; using Elastos::Droid::Content::Res::IConfiguration; using Elastos::Droid::Content::IContext; using Elastos::Droid::Media::CMediaScanner; using Elastos::Droid::Net::CUriHelper; using Elastos::Droid::Net::IUri; using Elastos::Droid::Net::IUriHelper; using Elastos::Droid::Os::CBundle; using Elastos::Droid::Os::Environment; using Elastos::Droid::Os::EIID_IHandler; using Elastos::Droid::Os::IBundle; using Elastos::Droid::Os::IProcess; using Elastos::Droid::Os::ILooper; using Elastos::Droid::Os::Looper; using Elastos::Droid::Os::IPowerManager; using Elastos::Droid::Os::Process; using Elastos::Droid::Os::Storage::IStorageManager; using Elastos::Droid::Os::EIID_IBinder; using Elastos::Droid::Provider::CMediaStore; using Elastos::Droid::Provider::IMediaStore; using Elastos::Utility::Arrays; using Elastos::Utility::ILocale; using Elastos::Utility::Logging::Logger; using Elastos::IO::CFile; using Elastos::IO::IFile; using Elastos::Core::AutoLock; using Elastos::Core::CThread; using Elastos::Core::IThread; using Elastos::Core::EIID_IRunnable; namespace Elastos { namespace Droid { namespace Providers { namespace Media { const String MediaScannerService::TAG("MediaScannerService"); AutoPtr<ArrayOf<String> > MediaScannerService::mExternalStoragePaths; CAR_INTERFACE_IMPL_2(MediaScannerService, Service, IMediaScannerService, IRunnable) ECode MediaScannerService::constructor() { CIMediaScannerService::New(this, (IIMediaScannerService**)&mBinder); return Service::constructor(); } void MediaScannerService::OpenDatabase( /* [in] */ const String& volumeName) { // try { ECode ec = NOERROR; AutoPtr<IContentValues> values; CContentValues::New((IContentValues**)&values); ec = values->Put(String("name"), volumeName); if (ec == (ECode)E_ILLEGAL_ARGUMENT_EXCEPTION) { Logger::W(TAG, "failed to open media database"); } AutoPtr<IContentResolver> resolver; ec = GetContentResolver((IContentResolver**)&resolver); if (ec == (ECode)E_ILLEGAL_ARGUMENT_EXCEPTION) { Logger::W(TAG, "failed to open media database"); } AutoPtr<IUriHelper> uh; CUriHelper::AcquireSingleton((IUriHelper**)&uh); AutoPtr<IUri> uri; ec = uh->Parse(String("content://media/"), (IUri**)&uri); if (ec == (ECode)E_ILLEGAL_ARGUMENT_EXCEPTION) { Logger::W(TAG, "failed to open media database"); } AutoPtr<IUri> oUri; ec = resolver->Insert(uri, values, (IUri**)&oUri); if (ec == (ECode)E_ILLEGAL_ARGUMENT_EXCEPTION) { Logger::W(TAG, "failed to open media database"); } // } catch (IllegalArgumentException ex) { // Log.w(TAG, "failed to open media database"); // } } AutoPtr<IMediaScanner> MediaScannerService::CreateMediaScanner() { AutoPtr<IMediaScanner> scanner; CMediaScanner::New((IContext*)this, (IMediaScanner**)&scanner); AutoPtr<IResources> res; GetResources((IResources**)&res); AutoPtr<IConfiguration> cfg; res->GetConfiguration((IConfiguration**)&cfg); AutoPtr<ILocale> locale; cfg->GetLocale((ILocale**)&locale); if (locale != NULL) { String language; locale->GetLanguage(&language); String country; locale->GetCountry(&country); String localeString; if (!language.IsNull()) { if (!country.IsNull()) { scanner->SetLocale(language + "_" + country); } else { scanner->SetLocale(language); } } } return scanner; } void MediaScannerService::Scan( /* [in] */ ArrayOf<String>* directories, /* [in] */ const String& volumeName) { AutoPtr<IUri> uri; AutoPtr<IUriHelper> uh; CUriHelper::AcquireSingleton((IUriHelper**)&uh); uh->Parse(String("file://") + (*directories)[0], (IUri**)&uri); // don't sleep while scanning mWakeLock->AcquireLock(); AutoPtr<IContentValues> values; CContentValues::New((IContentValues**)&values); values->Put(IMediaStore::MEDIA_SCANNER_VOLUME, volumeName); AutoPtr<IContentResolver> resolver; GetContentResolver((IContentResolver**)&resolver); AutoPtr<IMediaStore> ms; CMediaStore::AcquireSingleton((IMediaStore**)&ms); AutoPtr<IUri> iUri; ms->GetMediaScannerUri((IUri**)&iUri); AutoPtr<IUri> scanUri; resolver->Insert(iUri, values, (IUri**)&scanUri); AutoPtr<IIntent> intent; CIntent::New(IIntent::ACTION_MEDIA_SCANNER_STARTED, uri, (IIntent**)&intent); SendBroadcast(intent); // try { if (volumeName.Equals(MediaProvider::EXTERNAL_VOLUME)) { OpenDatabase(volumeName); } AutoPtr<IMediaScanner> scanner = CreateMediaScanner(); ECode ec = scanner->ScanDirectories(directories, volumeName); // } catch (Exception e) { if (FAILED(ec)) { Logger::E(TAG, "exception in MediaScanner.scan()%0x", ec); } // } Int32 vol; resolver->Delete(scanUri, String(NULL), NULL, &vol); intent = NULL; CIntent::New(IIntent::ACTION_MEDIA_SCANNER_FINISHED, uri, (IIntent**)&intent); SendBroadcast(intent); mWakeLock->ReleaseLock(); } ECode MediaScannerService::OnCreate() { AutoPtr<IInterface> obj; GetSystemService(IContext::POWER_SERVICE, (IInterface**)&obj); AutoPtr<IPowerManager> pm = IPowerManager::Probe(obj); mWakeLock = NULL; pm->NewWakeLock(IPowerManager::PARTIAL_WAKE_LOCK, TAG, (IPowerManagerWakeLock**)&mWakeLock); obj = NULL; GetSystemService(IContext::STORAGE_SERVICE, (IInterface**)&obj); AutoPtr<IStorageManager> storageManager = IStorageManager::Probe(obj); mExternalStoragePaths = NULL; storageManager->GetVolumePaths((ArrayOf<String>**)&mExternalStoragePaths); // Start up the thread running the service. Note that we create a // separate thread because the service normally runs in the process's // main thread, which we don't want to block. AutoPtr<IThread> thr; CThread::New(NULL, (IRunnable*)this, String("MediaScannerService"), (IThread**)&thr); return thr->Start(); } ECode MediaScannerService::OnStartCommand( /* [in] */ IIntent* intent, /* [in] */ Int32 flags, /* [in] */ Int32 startId, /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = FALSE; while (mServiceHandler == NULL) { { AutoLock syncLock(this); // try { Wait(100); // } catch (InterruptedException e) { // } } } if (intent == NULL) { Logger::E(TAG, "Intent is null in onStartCommand: %0x", E_NULL_POINTER_EXCEPTION); *result = IService::START_NOT_STICKY; return NOERROR; } AutoPtr<IMessage> msg; mServiceHandler->ObtainMessage((IMessage**)&msg); msg->SetArg1(startId); AutoPtr<IBundle> bd; intent->GetExtras((IBundle**)&bd); msg->SetObj(bd); Boolean flag = FALSE; mServiceHandler->SendMessage(msg, &flag); // Try again later if we are killed before we can finish scanning. *result = IService::START_REDELIVER_INTENT; return NOERROR; } ECode MediaScannerService::OnDestroy() { // Make sure thread has started before telling it to quit. while (mServiceLooper == NULL) { { AutoLock syncLock(this); // try { Wait(100); // } catch (InterruptedException e) { // } } } return mServiceLooper->Quit(); } ECode MediaScannerService::Run() { // reduce priority below other background threads to avoid interfering // with other services at boot time. Process::SetThreadPriority(IProcess::THREAD_PRIORITY_BACKGROUND + IProcess::THREAD_PRIORITY_LESS_FAVORABLE); Looper::Prepare(); mServiceLooper = Looper::GetMyLooper(); mServiceHandler = new ServiceHandler(this); mServiceHandler->constructor(); return Looper::Loop(); } ECode MediaScannerService::ScanFile( /* [in] */ const String& path, /* [in] */ const String& mimeType, /* [out] */ IUri** result) { VALIDATE_NOT_NULL(result) String volumeName = MediaProvider::EXTERNAL_VOLUME; OpenDatabase(volumeName); AutoPtr<IMediaScanner> scanner = CreateMediaScanner(); // try { // make sure the file path is in canonical form AutoPtr<IFile> file; CFile::New(path, (IFile**)&file); String canonicalPath; ECode ec = NOERROR; ec = file->GetCanonicalPath(&canonicalPath); FAIL_GOTO(ec, _EXIT_); ec = scanner->ScanSingleFile(canonicalPath, volumeName, mimeType, result); if (SUCCEEDED(ec)) { return ec; } FAIL_GOTO(ec, _EXIT_); _EXIT_: // } catch (Exception e) { Logger::E(TAG, "bad path %s in scanFile()%0x", path.string(), ec); *result = NULL; return NOERROR; // } } ECode MediaScannerService::OnBind( /* [in] */ IIntent* intent, /* [out] */ IBinder** result) { VALIDATE_NOT_NULL(result) *result = IBinder::Probe(mBinder); REFCOUNT_ADD(*result); return NOERROR; } //=========================================================== // MediaScannerService::MyMediaScannerService //=========================================================== CAR_INTERFACE_IMPL_2(MediaScannerService::MyMediaScannerService, Object, IIMediaScannerService, IBinder) MediaScannerService::MyMediaScannerService::MyMediaScannerService() {} MediaScannerService::MyMediaScannerService::~MyMediaScannerService() {} ECode MediaScannerService::MyMediaScannerService::constructor( /* [in] */ IMediaScannerService* owner) { mOwner = (MediaScannerService*)owner; return NOERROR; } ECode MediaScannerService::MyMediaScannerService::RequestScanFile( /* [in] */ const String& path, /* [in] */ const String& mimeType, /* [in] */ IIMediaScannerListener* listener) { if (FALSE) { Logger::D(TAG, "IMediaScannerService.scanFile: %s mimeType: ", path.string(), mimeType.string()); } AutoPtr<IBundle> args; CBundle::New((IBundle**)&args); args->PutString(String("filepath"), path); args->PutString(String("mimetype"), mimeType); if (listener != NULL) { AutoPtr<IBinder> bdListener = IBinder::Probe(listener); args->PutIBinder(String("listener"), bdListener); } AutoPtr<IIntent> intent; CIntent::New((IContext*)this, ECLSID_CMediaScannerService, (IIntent**)&intent); intent->PutExtras(args); AutoPtr<IComponentName> cn; return ((IContext*)((IMediaScannerService*)mOwner))->StartService(intent, (IComponentName**)&cn); } ECode MediaScannerService::MyMediaScannerService::ScanFile( /* [in] */ const String& path, /* [in] */ const String& mimeType) { return RequestScanFile(path, mimeType, NULL); } ECode MediaScannerService::MyMediaScannerService::ToString( /* [out] */ String* str) { VALIDATE_NOT_NULL(str) return NOERROR; } //=========================================================== // MediaScannerService::ServiceHandler //=========================================================== MediaScannerService::ServiceHandler::ServiceHandler( /* [in] */ MediaScannerService* owner) : mOwner(owner) { Handler::constructor(); } ECode MediaScannerService::ServiceHandler::HandleMessage( /* [in] */ IMessage* msg) { AutoPtr<IInterface> obj; msg->GetObj((IInterface**)&obj); AutoPtr<IBundle> arguments = IBundle::Probe(obj); String filePath; arguments->GetString(String("filepath"), &filePath); if (!filePath.IsNull()) { AutoPtr<IBinder> binder; arguments->GetIBinder(String("listener"), (IBinder**)&binder); AutoPtr<IIMediaScannerListener> listener = IIMediaScannerListener::Probe(binder); AutoPtr<IUri> uri; String mimeType; ECode ec = arguments->GetString(String("mimetype"), &mimeType); FAIL_GOTO(ec, _EXIT_); ec = mOwner->ScanFile(filePath, mimeType, (IUri**)&uri); FAIL_GOTO(ec, _EXIT_); _EXIT_: if (FAILED(ec)) { Logger::E(TAG, "Exception scanning file, ec=%08x", ec); } if (listener != NULL) { listener->ScanCompleted(filePath, uri); } } else { String volume; arguments->GetString(String("volume"), &volume); AutoPtr<ArrayOf<String> > directories = ArrayOf<String>::Alloc(2); if (MediaProvider::INTERNAL_VOLUME.Equals(volume)) { // scan internal media storage String rootDirectory, oemDirectory; AutoPtr<IFile> rdf = Environment::GetRootDirectory(); AutoPtr<IFile> odf = Environment::GetOemDirectory(); rdf->ToString(&rootDirectory); odf->ToString(&oemDirectory); (*directories)[0] = rootDirectory + String("/media"); (*directories)[1] = oemDirectory + String("/media"); } else if (MediaProvider::EXTERNAL_VOLUME.Equals(volume)) { // scan external storage volumes Int32 esLength = mExternalStoragePaths->GetLength(); for (Int32 i = 0; i < esLength; ++i) { directories->Set(i, (*mExternalStoragePaths)[i]); } } if (directories != NULL) { String str; str = Arrays::ToString(directories); if (FALSE) Logger::D(TAG, "start scanning volume %s: %s", volume.string(), str.string()); mOwner->Scan(directories, volume); if (FALSE) Logger::D(TAG, "done scanning volume %s", volume.string()); } } Int32 arg1; msg->GetArg1(&arg1); mOwner->StopSelf(arg1); return NOERROR; } } // namespace Media } // namespace Providers } // namespace Droid } // namespace Elastos
33.404301
105
0.646366
[ "object" ]
b577321f8ddf704c7758db2541f7fd97ab324a9a
3,494
cpp
C++
KernelObjectView/ObjectManager.cpp
zodiacon/KernelObjectView
d62c9db6a959dcb00642c8741a92952121ab48ac
[ "MIT" ]
45
2019-07-23T18:44:44.000Z
2022-02-01T08:09:22.000Z
KernelObjectView/ObjectManager.cpp
c3358/KernelObjectView
d62c9db6a959dcb00642c8741a92952121ab48ac
[ "MIT" ]
null
null
null
KernelObjectView/ObjectManager.cpp
c3358/KernelObjectView
d62c9db6a959dcb00642c8741a92952121ab48ac
[ "MIT" ]
18
2019-07-24T05:14:20.000Z
2022-01-12T21:28:22.000Z
#include "stdafx.h" #include "ObjectManager.h" #include <assert.h> #pragma comment(lib, "ntdll") ObjectManager::ObjectManager() { } ObjectManager::~ObjectManager() { } int ObjectManager::EnumObjectTypes() { ULONG len = 1 << 17; auto buffer = std::make_unique<BYTE[]>(len); if (!NT_SUCCESS(NT::NtQueryObject(nullptr, NT::ObjectTypesInformation, buffer.get(), len, &len))) return 0; auto p = reinterpret_cast<NT::OBJECT_TYPES_INFORMATION*>(buffer.get()); bool empty = _types.empty(); auto count = p->NumberOfTypes; if (empty) { _types.reserve(count); _typesMap.reserve(count); _changes.reserve(32); } else { _changes.clear(); assert(count == _types.size()); } auto raw = &p->TypeInformation[0]; _totalHandles = _totalObjects = 0; for (ULONG i = 0; i < count; i++) { auto type = empty ? std::make_shared<ObjectType>() : _typesMap[raw->TypeIndex]; if (empty) { type->GenericMapping = raw->GenericMapping; type->TypeIndex = raw->TypeIndex; type->DefaultNonPagedPoolCharge = raw->DefaultNonPagedPoolCharge; type->DefaultPagedPoolCharge = raw->DefaultPagedPoolCharge; type->TypeName = CString(raw->TypeName.Buffer, raw->TypeName.Length / 2); type->PoolType = (PoolType)raw->PoolType; type->DefaultNonPagedPoolCharge = raw->DefaultNonPagedPoolCharge; type->DefaultPagedPoolCharge = raw->DefaultPagedPoolCharge; type->ValidAccessMask = raw->ValidAccessMask; } else { if (type->TotalNumberOfHandles != raw->TotalNumberOfHandles) _changes.push_back({ type, ChangeType::TotalHandles, (int32_t)raw->TotalNumberOfHandles - (int32_t)type->TotalNumberOfHandles }); if (type->TotalNumberOfObjects != raw->TotalNumberOfObjects) _changes.push_back({ type, ChangeType::TotalObjects, (int32_t)raw->TotalNumberOfObjects - (int32_t)type->TotalNumberOfObjects }); if (type->HighWaterNumberOfHandles != raw->HighWaterNumberOfHandles) _changes.push_back({ type, ChangeType::PeakHandles, (int32_t)raw->HighWaterNumberOfHandles - (int32_t)type->HighWaterNumberOfHandles }); if (type->HighWaterNumberOfObjects != raw->HighWaterNumberOfObjects) _changes.push_back({ type, ChangeType::PeakObjects, (int32_t)raw->HighWaterNumberOfObjects - (int32_t)type->HighWaterNumberOfObjects }); } type->TotalNumberOfHandles = raw->TotalNumberOfHandles; type->TotalNumberOfObjects = raw->TotalNumberOfObjects; type->TotalNonPagedPoolUsage = raw->TotalNonPagedPoolUsage; type->TotalPagedPoolUsage = raw->TotalPagedPoolUsage; type->HighWaterNumberOfObjects = raw->HighWaterNumberOfObjects; type->HighWaterNumberOfHandles = raw->HighWaterNumberOfHandles; type->TotalNamePoolUsage = raw->TotalNamePoolUsage; _totalObjects += raw->TotalNumberOfObjects; _totalHandles += raw->TotalNumberOfHandles; if (empty) { _types.emplace_back(type); _typesMap.insert({ type->TypeIndex, type }); } auto temp = (BYTE*)raw + sizeof(NT::OBJECT_TYPE_INFORMATION) + raw->TypeName.MaximumLength; temp += sizeof(PVOID) - 1; raw = reinterpret_cast<NT::OBJECT_TYPE_INFORMATION*>((ULONG_PTR)temp / sizeof(PVOID) * sizeof(PVOID)); } return static_cast<int>(_types.size()); } const std::vector<std::shared_ptr<ObjectType>>& ObjectManager::GetObjectTypes() const { return _types; } const std::vector<ObjectManager::Change>& ObjectManager::GetChanges() const { return _changes; } int64_t ObjectManager::GetTotalObjects() const { return _totalObjects; } int64_t ObjectManager::GetTotalHandles() const { return _totalHandles; }
36.020619
140
0.743274
[ "vector" ]
b57de223acefe0c955562767237b89d8df50b3b7
119,245
cpp
C++
src/RocketSim.cpp
RCrockford/ksp-launch-optimisation
cadd73b24c6e50e3981f904806efc280995b0f60
[ "MIT" ]
null
null
null
src/RocketSim.cpp
RCrockford/ksp-launch-optimisation
cadd73b24c6e50e3981f904806efc280995b0f60
[ "MIT" ]
null
null
null
src/RocketSim.cpp
RCrockford/ksp-launch-optimisation
cadd73b24c6e50e3981f904806efc280995b0f60
[ "MIT" ]
null
null
null
// RocketSim.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "RocketSim.h" #define MAX_LOADSTRING 100 // Global Variables: static wchar_t szTitle[MAX_LOADSTRING]; // The title bar text static wchar_t szWindowClass[MAX_LOADSTRING]; // the main window class name static RocketSim s_RocketSim; //------------------------------------------------------------------------------------------------ static constexpr float c_RadToDegree = 180.0f / 3.14159265f; static constexpr float c_DegreeToRad = 3.14159265f / 180.0f; static double earthRadius = 6371000; static double earthMu = 3.986004418e+14; static double earthg0 = earthMu / (earthRadius * earthRadius); static constexpr D3D12_RESOURCE_STATES D3D12_RESOURCE_STATE_SHADER_RESOURCE = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; //------------------------------------------------------------------------------------------------ template<typename T> T sqr( T x ) { return x * x; } template<typename T> T cube( T x ) { return x * x * x; } //------------------------------------------------------------------------------------------------ struct ProgressVertex { float x, y, z; uint32_t colour; }; static char barVertexShader[] = "struct PSInput\n" "{\n" " float4 position : SV_POSITION;\n" " float4 color : COLOR;\n" "};\n" "\n" "PSInput VSMain(float4 position : POSITION, float4 colour : COLOR)\n" "{\n" " PSInput result;\n" "\n" " result.position = position;\n" " result.color = colour;\n" "\n" " return result;\n" "}\n" ; static char barPixelShader[] = "struct PSInput\n" "{\n" " float4 position : SV_POSITION;\n" " float4 color : COLOR;\n" "};\n" "\n" "float4 PSMain(PSInput input) : SV_TARGET\n" "{\n" " return input.color;\n" "}\n" ; //------------------------------------------------------------------------------------------------ const D3D12_RENDER_TARGET_BLEND_DESC RocketSim::s_opaqueRenderTargetBlendDesc = { FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL, }; const D3D12_RENDER_TARGET_BLEND_DESC RocketSim::s_blendedRenderTargetBlendDesc = { TRUE, FALSE, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL, }; //------------------------------------------------------------------------------------------------ void DebugTrace( const wchar_t* fmt, ... ) { wchar_t message[2000]; va_list args; va_start( args, fmt ); if ( vswprintf_s( message, fmt, args ) > 0 ) { wcscat_s( message, L"\r\n" ); OutputDebugString( message ); } va_end( args ); } //------------------------------------------------------------------------------------------------ template <typename T> T RoundUpPow2( T x, T p ) { return (x + p - 1) & ~(p - 1); } //------------------------------------------------------------------------------------------------ class PixMarker { public: PixMarker( ID3D12GraphicsCommandList* cmdList, wchar_t const * name ) : m_cmdList( cmdList ) { PIXBeginEvent( m_cmdList, PIX_COLOR_INDEX( s_index++ ), name ); } ~PixMarker() { PIXEndEvent( m_cmdList ); } static void reset() { s_index = 0; } private: ID3D12GraphicsCommandList * m_cmdList; static uint8_t s_index; }; uint8_t PixMarker::s_index; //------------------------------------------------------------------------------------------------ void RocketSim::InitRenderer( HWND hwnd ) { m_hwnd = hwnd; #if defined(_DEBUG) // Enable the D3D12 debug layer. { ComPtr<ID3D12Debug> debugController; if ( SUCCEEDED( D3D12GetDebugInterface( IID_PPV_ARGS( &debugController ) ) ) ) { debugController->EnableDebugLayer(); } } #endif ComPtr<IDXGIFactory4> factory; if ( ErrorHandler( CreateDXGIFactory1( IID_PPV_ARGS( &factory ) ), L"CreateDXGIFactory" ) == ErrorResult::ABORT ) return; ComPtr<IDXGIAdapter1> hardwareAdapter; HRESULT createResult = DXGI_ERROR_NOT_FOUND; for ( UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != factory->EnumAdapters1( adapterIndex, &hardwareAdapter ); ++adapterIndex ) { DXGI_ADAPTER_DESC1 desc; hardwareAdapter->GetDesc1( &desc ); if ( desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE ) { // Don't select the Basic Render Driver adapter. hardwareAdapter = nullptr; continue; } createResult = D3D12CreateDevice( hardwareAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS( &m_device ) ); if ( SUCCEEDED( createResult ) ) { break; } } if ( ErrorHandler( createResult, L"D3D12CreateDevice" ) == ErrorResult::ABORT ) return; ComPtr<ID3D12InfoQueue> infoQueue; m_device.As( &infoQueue ); if ( infoQueue.Get() ) { // Just map/unmap null ranges enabled by default (these are mobile optimisation warnings). std::array<D3D12_MESSAGE_ID, 2> ids = { D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE, D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE }; D3D12_INFO_QUEUE_FILTER filter; memset( &filter, 0, sizeof(filter) ); filter.DenyList.NumIDs = UINT( ids.size() ); filter.DenyList.pIDList = ids.data(); infoQueue->AddStorageFilterEntries( &filter ); } // Describe and create the command queue. D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; if ( ErrorHandler( m_device->CreateCommandQueue( &queueDesc, IID_PPV_ARGS( &m_commandQueue ) ), L"CreateCommandQueue" ) == ErrorResult::ABORT ) return; RECT rc; GetClientRect( m_hwnd, &rc ); // Describe and create the swap chain. DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {}; swapChainDesc.BufferCount = ARRAY_SIZE( m_renderTargets ); swapChainDesc.Width = rc.right - rc.left; swapChainDesc.Height = rc.bottom - rc.top; swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapChainDesc.SampleDesc.Count = 1; ComPtr<IDXGISwapChain1> swapChain; if ( ErrorHandler( factory->CreateSwapChainForHwnd( m_commandQueue.Get(), m_hwnd, &swapChainDesc, nullptr, nullptr, &swapChain ), L"CreateSwapChain" ) == ErrorResult::ABORT ) return; // Default viewport and scissor regions m_viewport.Width = static_cast<float>(rc.right - rc.left); m_viewport.Height = static_cast<float>(rc.bottom - rc.top); m_viewport.MaxDepth = 1.0f; m_scissorRect.right = static_cast<LONG>(rc.right - rc.left); m_scissorRect.bottom = static_cast<LONG>(rc.bottom - rc.top); // Disable fullscreen transitions. if ( ErrorHandler( factory->MakeWindowAssociation( m_hwnd, DXGI_MWA_NO_ALT_ENTER ), L"MakeWindowAssociation" ) == ErrorResult::ABORT ) return; if ( ErrorHandler( swapChain.As( &m_swapChain ), L"GetSwapChain3" ) == ErrorResult::ABORT ) return; m_frameIndex = m_swapChain->GetCurrentBackBufferIndex(); // Create descriptor heaps. { // Describe and create a render target view (RTV) descriptor heap. D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {}; rtvHeapDesc.NumDescriptors = ARRAY_SIZE( m_renderTargets ); rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; if ( ErrorHandler( m_rtvHeap.Create( m_device.Get(), rtvHeapDesc ), L"CreateDescriptorHeap" ) == ErrorResult::ABORT ) return; // Describe and create a shader resource view (SRV) descriptor heap. D3D12_DESCRIPTOR_HEAP_DESC srvHeapDesc = {}; srvHeapDesc.NumDescriptors = ShaderShared::getDescriptorCount(); srvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; srvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; if ( ErrorHandler( m_shaderHeap.Create( m_device.Get(), srvHeapDesc ), L"CreateDescriptorHeap" ) == ErrorResult::ABORT ) return; } // Create frame resources. { // Create a RTV for each frame. for ( UINT n = 0; n < ARRAY_SIZE( m_renderTargets ); n++ ) { if ( ErrorHandler( m_swapChain->GetBuffer( n, IID_PPV_ARGS( &m_renderTargets[n] ) ), L"GetSwapChainBuffer" ) == ErrorResult::ABORT ) return; m_device->CreateRenderTargetView( m_renderTargets[n].Get(), nullptr, m_rtvHeap.GetCPUHandle( n ) ); if ( ErrorHandler( m_device->CreateCommandAllocator( D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS( &m_commandAllocators[n] ) ), L"CreateCommandAllocator" ) == ErrorResult::ABORT ) return; } } { D3D12_QUERY_HEAP_DESC queryDesc; queryDesc.Type = D3D12_QUERY_HEAP_TYPE_TIMESTAMP; queryDesc.Count = 2; queryDesc.NodeMask = 0; m_device->CreateQueryHeap( &queryDesc, IID_PPV_ARGS( &m_queryHeap ) ); m_queryRB = CreateReadbackBuffer( L"QueryRB", sizeof( uint64_t ) * queryDesc.Count ); } m_simStepsPerFrame = 50; } //------------------------------------------------------------------------------------------------ void RocketSim::LoadBaseResources() { // Create a root signature. { D3D12_FEATURE_DATA_ROOT_SIGNATURE featureData = {}; featureData.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_1; if ( FAILED( m_device->CheckFeatureSupport( D3D12_FEATURE_ROOT_SIGNATURE, &featureData, sizeof( featureData ) ) ) ) { featureData.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_0; } D3D12_DESCRIPTOR_RANGE1 ranges[] = { { D3D12_DESCRIPTOR_RANGE_TYPE_CBV, ShaderShared::getCbvCount(), 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, 0 }, { D3D12_DESCRIPTOR_RANGE_TYPE_SRV, ShaderShared::getSrvCount(), 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND }, { D3D12_DESCRIPTOR_RANGE_TYPE_UAV, ShaderShared::getUavCount(), 0, 0, D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND }, }; std::array<D3D12_ROOT_PARAMETER1, 3> rootParameters; uint32_t paramIdx = 0; rootParameters[paramIdx].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; rootParameters[paramIdx].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; rootParameters[paramIdx].Constants.ShaderRegister = 0; rootParameters[paramIdx].Constants.RegisterSpace = 1; rootParameters[paramIdx].Constants.Num32BitValues = sizeof( ShaderShared::DrawConstData ) / sizeof( uint32_t ); ++paramIdx; rootParameters[paramIdx].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; rootParameters[paramIdx].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; rootParameters[paramIdx].Descriptor.ShaderRegister = 1; rootParameters[paramIdx].Descriptor.RegisterSpace = 1; rootParameters[paramIdx].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC_WHILE_SET_AT_EXECUTE; ++paramIdx; rootParameters[paramIdx].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; rootParameters[paramIdx].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; rootParameters[paramIdx].DescriptorTable.NumDescriptorRanges = ARRAY_SIZE( ranges ); rootParameters[paramIdx].DescriptorTable.pDescriptorRanges = ranges; ++paramIdx; D3D12_STATIC_SAMPLER_DESC samplers[2] = {}; for ( D3D12_STATIC_SAMPLER_DESC& sampler : samplers ) { sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER; sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER; sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER; sampler.MipLODBias = 0; sampler.MaxAnisotropy = 0; sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; sampler.MinLOD = 0.0f; sampler.MaxLOD = D3D12_FLOAT32_MAX; sampler.ShaderRegister = UINT( &sampler - samplers ); sampler.RegisterSpace = 0; sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; } samplers[0].Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; samplers[1].Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; D3D12_VERSIONED_ROOT_SIGNATURE_DESC rootSignatureDesc; rootSignatureDesc.Version = featureData.HighestVersion; rootSignatureDesc.Desc_1_1.NumParameters = static_cast<UINT>(rootParameters.size()); rootSignatureDesc.Desc_1_1.pParameters = rootParameters.data(); rootSignatureDesc.Desc_1_1.NumStaticSamplers = ARRAY_SIZE( samplers ); rootSignatureDesc.Desc_1_1.pStaticSamplers = samplers; rootSignatureDesc.Desc_1_1.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; ComPtr<ID3DBlob> signature; ComPtr<ID3DBlob> error; if ( ErrorHandler( D3D12SerializeVersionedRootSignature( &rootSignatureDesc, &signature, &error ), L"SerializeRootSignature" ) == ErrorResult::ABORT ) return; if ( ErrorHandler( m_device->CreateRootSignature( 0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS( &m_rootSignature ) ), L"CreateRootSignature" ) == ErrorResult::ABORT ) return; } // Setup resources m_ascentParamsBuffer.desc = m_shaderHeap.GetCPUHandle( ShaderShared::srvAscentParams ); m_missionParamsBuffer.desc = m_shaderHeap.GetCPUHandle( ShaderShared::cbvMissionParams ); m_enviroParamsBuffer.desc = m_shaderHeap.GetCPUHandle( ShaderShared::cbvEnviroParams ); m_pressureHeightCurve.desc = m_shaderHeap.GetCPUHandle( ShaderShared::srvPressureHeightCurve ); m_temperatureHeightCurve.desc = m_shaderHeap.GetCPUHandle( ShaderShared::srvTemperatureHeightCurve ); m_graphColourBuffer.desc = m_shaderHeap.GetCPUHandle( ShaderShared::srvGraphColours ); for ( uint32_t i = 0; i < 4; ++i ) { m_liftMachCurve[i].desc = m_shaderHeap.GetCPUHandle( ShaderShared::srvLiftMachCurve, i ); m_dragMachCurve[i].desc = m_shaderHeap.GetCPUHandle( ShaderShared::srvDragMachCurve, i ); } SetCurrentDirectoryW( L"resources" ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_draw_pxl.hlsl", { 0 }, &RocketSim::ReloadAllGraphShaders, nullptr } ); m_trackedFiles.emplace_back( TrackedFile{ L"heatmap_draw_vtx.hlsl",{ 0 }, &RocketSim::ReloadAllHeatmapShaders, nullptr } ); m_trackedFiles.emplace_back( TrackedFile{ L"simulate_flight_cs.hlsl", { 0 }, &RocketSim::ReloadDispatchShader, &m_dispatchList[DispatchList_SimulateFlight] } ); m_trackedFiles.emplace_back( TrackedFile{ L"flight_data_extents_cs.hlsl",{ 0 }, &RocketSim::ReloadDispatchShader, &m_dispatchList[DispatchList_FlightDataExtents] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_height_vtx.hlsl", { 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_Height] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_position_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_Position] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_velocity_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_Velocity] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_Q_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_Q] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_pitch_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_Pitch] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_aoa_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_AoA] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_mass_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_Mass] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_apoapsis_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_Apoapsis] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_eccentricty_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_Eccentricity] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_guidance_pitch_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_GuidancePitch] } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_twr_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_graphList[GraphList_TWR] } ); m_trackedFiles.emplace_back( TrackedFile{ L"heatmap_maxQ_pxl.hlsl",{ 0 }, &RocketSim::ReloadHeatmapShader, &m_heatmapList[HeatmapList_MaxQ] } ); m_trackedFiles.emplace_back( TrackedFile{ L"heatmap_mass_pxl.hlsl",{ 0 }, &RocketSim::ReloadHeatmapShader, &m_heatmapList[HeatmapList_MaxMass] } ); m_trackedFiles.emplace_back( TrackedFile{ L"heatmap_orbit_variance_pxl.hlsl",{ 0 }, &RocketSim::ReloadHeatmapShader, &m_heatmapList[HeatmapList_OrbitVariance] } ); m_trackedFiles.emplace_back( TrackedFile{ L"heatmap_combined_pxl.hlsl",{ 0 }, &RocketSim::ReloadHeatmapShader, &m_heatmapList[HeatmapList_Combined] } ); m_trackedFiles.emplace_back( TrackedFile{ L"marker_draw_vtx.hlsl",{ 0 }, &RocketSim::ReloadGraphShader, &m_selectionMarker } ); m_trackedFiles.emplace_back( TrackedFile{ L"textbox_vtx.hlsl",{ 0 }, &RocketSim::ReloadDrawShader, &m_boxDraw } ); m_trackedFiles.emplace_back( TrackedFile{ L"textbox_pxl.hlsl",{ 0 }, &RocketSim::ReloadDrawShader, &m_boxDraw } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_background_vtx.hlsl",{ 0 }, &RocketSim::ReloadDrawShader, &m_graphBackground } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_background_pxl.hlsl",{ 0 }, &RocketSim::ReloadDrawShader, &m_graphBackground } ); m_trackedFiles.emplace_back( TrackedFile{ L"environmental_params.json",{ 0 }, &RocketSim::ReloadEnvironmentalParams, &m_enviroParamsBuffer } ); m_trackedFiles.emplace_back( TrackedFile{ L"ascent_params.json",{ 0 }, &RocketSim::ReloadAscentParams, &m_ascentParamsBuffer } ); m_trackedFiles.emplace_back( TrackedFile{ L"mission_params.json",{ 0 }, &RocketSim::ReloadMissionParams, &m_missionParamsBuffer } ); m_trackedFiles.emplace_back( TrackedFile{ L"machsweep_s1.csv",{ 0 }, &RocketSim::ReloadMachSweep, &m_liftMachCurve[0] } ); m_trackedFiles.emplace_back( TrackedFile{ L"machsweep_s1.csv",{ 0 }, &RocketSim::ReloadMachSweep, &m_dragMachCurve[0] } ); m_trackedFiles.emplace_back( TrackedFile{ L"machsweep_s2.csv",{ 0 }, &RocketSim::ReloadMachSweep, &m_liftMachCurve[1] } ); m_trackedFiles.emplace_back( TrackedFile{ L"machsweep_s2.csv",{ 0 }, &RocketSim::ReloadMachSweep, &m_dragMachCurve[1] } ); m_trackedFiles.emplace_back( TrackedFile{ L"pressure_height.json",{ 0 }, &RocketSim::ReloadHermiteCurve, &m_pressureHeightCurve } ); m_trackedFiles.emplace_back( TrackedFile{ L"temperature_height.json",{ 0 }, &RocketSim::ReloadHermiteCurve, &m_temperatureHeightCurve } ); m_trackedFiles.emplace_back( TrackedFile{ L"graph_colours.json",{ 0 }, &RocketSim::ReloadGraphColours, &m_graphColourBuffer } ); m_graphLayout.emplace_back( GraphList_Height ); m_graphLayout.emplace_back( GraphList_Velocity ); m_graphLayout.emplace_back( GraphList_Q ); m_graphLayout.emplace_back( GraphList_GuidancePitch ); m_graphLayout.emplace_back( GraphList_Pitch ); m_graphLayout.emplace_back( GraphList_Mass ); m_graphLayout.emplace_back( GraphList_Apoapsis ); m_graphLayout.emplace_back( GraphList_Eccentricity ); m_graphLayout.emplace_back( GraphList_TWR ); m_heatmapLayout.emplace_back( HeatmapList_MaxMass ); m_heatmapLayout.emplace_back( HeatmapList_MaxQ ); m_heatmapLayout.emplace_back( HeatmapList_OrbitVariance ); m_heatmapLayout.emplace_back( HeatmapList_Combined ); // Create the command list. if ( ErrorHandler( m_device->CreateCommandList( 0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_commandAllocators[m_frameIndex].Get(), nullptr, IID_PPV_ARGS( &m_commandList ) ), L"CreateCommandList" ) == ErrorResult::ABORT ) return; // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. m_commandList->Close(); // Create progress bar resources { std::array<ComPtr<ID3DBlob>, ShaderType_Count> shaderList; D3DCompile( barVertexShader, sizeof( barVertexShader ), "embedded", nullptr, nullptr, "VSMain", "vs_5_0", 0, 0, &shaderList[ShaderType_Vertex], nullptr ); D3DCompile( barPixelShader, sizeof( barPixelShader ), "embedded", nullptr, nullptr, "PSMain", "ps_5_0", 0, 0, &shaderList[ShaderType_Pixel], nullptr ); D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; m_progressBarPSO = CreateGraphicsPSO( L"ProgressBarPSO", inputElementDescs, ARRAY_SIZE( inputElementDescs ), shaderList ); for ( UINT i = 0; i < ARRAY_SIZE( m_progressBarVB ); ++i ) { m_progressBarVB[i] = CreateUploadBuffer( L"ProgressBarVB", nullptr, sizeof( ProgressVertex ) * 6 ); m_progressBarVBV[i].BufferLocation = m_progressBarVB[i]->GetGPUVirtualAddress(); m_progressBarVBV[i].StrideInBytes = sizeof( ProgressVertex ); m_progressBarVBV[i].SizeInBytes = sizeof( ProgressVertex ) * 6; } } // Create simulation resources { m_simulationStepSize = 1.0f / 50.0f; m_telemetryStepSize = 5; m_telemetryMaxSamples = uint32_t( 600.0f / (m_simulationStepSize * m_telemetryStepSize) + 0.5f ); m_simulationThreadWidth = 16; m_simulationThreadHeight = 32; m_simulationThreadCount = 16 * 32; CreateRWStructuredBuffer( L"TelemetryData", m_telemetryData, m_shaderHeap.GetCPUHandle( ShaderShared::srvTelemetryData ), m_shaderHeap.GetCPUHandle( ShaderShared::uavTelemetryData ), sizeof( ShaderShared::TelemetryData ), m_telemetryMaxSamples * m_simulationThreadCount ); CreateRWStructuredBuffer( L"FlightData", m_flightData, m_shaderHeap.GetCPUHandle( ShaderShared::srvFlightData ), m_shaderHeap.GetCPUHandle( ShaderShared::uavFlightData ), sizeof( ShaderShared::FlightData ), (m_simulationThreadCount + 2) ); m_flightDataRB[0] = CreateReadbackBuffer( L"FlightDataRB[0]", sizeof( ShaderShared::FlightData ) * (m_simulationThreadCount + 2) ); m_flightDataRB[1] = CreateReadbackBuffer( L"FlightDataRB[1]", sizeof( ShaderShared::FlightData ) * (m_simulationThreadCount + 2) ); m_dispatchList[DispatchList_SimulateFlight].name = L"SimulateFlight"; m_dispatchList[DispatchList_SimulateFlight].threadGroupCount[0] = 1; m_dispatchList[DispatchList_SimulateFlight].threadGroupCount[1] = 1; m_dispatchList[DispatchList_SimulateFlight].threadGroupCount[2] = 1; m_dispatchList[DispatchList_SimulateFlight].perStep = true; m_dispatchList[DispatchList_FlightDataExtents].name = L"FlightDataExtents"; m_dispatchList[DispatchList_FlightDataExtents].threadGroupCount[0] = 1; m_dispatchList[DispatchList_FlightDataExtents].threadGroupCount[1] = 1; m_dispatchList[DispatchList_FlightDataExtents].threadGroupCount[2] = 1; m_dispatchList[DispatchList_FlightDataExtents].perStep = false; m_simulationStep = 0; } m_frameConstantBuffer = CreateUploadBuffer( L"Frame Constant Buffer", nullptr, 2 * RoundUpPow2( sizeof( ShaderShared::FrameConstData ), 256llu ) ); D3D12_RANGE readRange = { 0, 0 }; m_frameConstantBuffer->Map( 0, &readRange, (void**)&m_frameConstData[0] ); m_frameConstData[1] = (ShaderShared::FrameConstData*)((uintptr_t)m_frameConstData[0] + RoundUpPow2( sizeof( ShaderShared::FrameConstData ), 256llu )); m_font.Create( m_hwnd, this, 48 ); // Create synchronization objects and wait until assets have been uploaded to the GPU. { if ( ErrorHandler( m_device->CreateFence( 0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS( &m_fence ) ), L"CreateFence" ) == ErrorResult::ABORT ) return; ++m_fenceValues[m_frameIndex]; // Create an event handle to use for frame synchronization. m_fenceEvent = CreateEvent( nullptr, FALSE, FALSE, nullptr ); if ( m_fenceEvent == nullptr ) { if ( ErrorHandler( HRESULT_FROM_WIN32( GetLastError() ), L"CreateEvent" ) == ErrorResult::ABORT ) return; } WaitForGPU(); } #if defined(_DEBUG) DXGIGetDebugInterface1( 0, IID_PPV_ARGS( &m_graphicsAnalysis ) ); #endif } //------------------------------------------------------------------------------------------------ bool RocketSim::CompileShader( const wchar_t* filename, std::array<ID3DBlob**, ShaderType_Count> shaderList, std::vector<std::wstring>& errorList ) { #if defined(_DEBUG) // Enable better shader debugging with the graphics debugging tools. UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; #else UINT compileFlags = 0; #endif ComPtr<ID3DBlob> errors; char target[] = "xs_5_1"; const wchar_t* targetTag = wcsrchr( filename, L'_' ); if ( targetTag && isalpha( targetTag[1] ) ) { target[0] = char( targetTag[1] ); } const char shaderTypes[ShaderType_Count] = { 'v', 'p', 'd', 'h', 'g', 'c' }; ptrdiff_t shader = std::find( shaderTypes, shaderTypes + ARRAY_SIZE( shaderTypes ), target[0] ) - shaderTypes; if ( shader == ARRAY_SIZE( shaderTypes ) ) { DebugTrace( L"Unable to deduce shader type for file: %s", filename ); return false; } if ( !shaderList[shader] ) { DebugTrace( L"Cannot load shader in this context: %s", filename ); return false; } if ( *shaderList[shader] ) { (*shaderList[shader])->Release(); *shaderList[shader] = nullptr; } errorList.clear(); char targetDefine[] = "SHADER_TYPE_XS"; targetDefine[12] = static_cast<char>(toupper(target[0])); D3D_SHADER_MACRO defines[2] = { 0 }; defines[0].Name = targetDefine; defines[0].Definition = ""; HRESULT hr; while ( FAILED( hr = D3DCompileFromFile( filename, defines, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", target, compileFlags, 0, shaderList[shader], &errors ) ) ) { // If it's a sharing violation just have another crack if ( hr == HRESULT_FROM_WIN32( ERROR_SHARING_VIOLATION ) ) { continue; } if ( errors && errors->GetBufferSize() ) { DebugTrace( L"Failed to compile shader: %S", errors->GetBufferPointer() ); char* context = nullptr; char* token = strtok_s( static_cast<char*>(errors->GetBufferPointer()), "\n", &context ); while ( token ) { size_t len; mbstowcs_s( &len, nullptr, 0, token, _TRUNCATE ); wchar_t* wtoken = static_cast<wchar_t*>(alloca( sizeof( wchar_t ) * len )); mbstowcs_s( nullptr, wtoken, len, token, _TRUNCATE ); errorList.emplace_back( wtoken ); token = strtok_s( nullptr, "\n", &context ); } } else { DebugTrace( L"Failed to load shader %s: %d", filename, hr ); } break; } // true even if compile failed - indicates one of the shaders changed, not that it was a valid compile return true; } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadAllGraphShaders( TrackedFile& trackedFile ) { std::array<ID3DBlob**, ShaderType_Count> shaderLoadList; for ( int i = 0; i < ShaderType_Count; ++i ) { shaderLoadList[i] = m_graphShaders[i].GetAddressOf(); } if ( CompileShader( trackedFile.filename, shaderLoadList, trackedFile.errorList ) ) { std::array<ComPtr<ID3DBlob>, ShaderType_Count> graphShaders( m_graphShaders ); for ( GraphData& graphData : m_graphList ) { if ( graphData.pso ) { m_pendingDeletes.emplace_back( PendingDeleteData{ graphData.pso, m_fenceValues[m_frameIndex] } ); graphData.pso = nullptr; } if ( graphData.vertexShader ) { graphShaders[ShaderType_Vertex] = graphData.vertexShader; graphData.pso = CreateGraphicsPSO( graphData.name, nullptr, 0, graphShaders, D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, D3D12_CULL_MODE_NONE, s_blendedRenderTargetBlendDesc ); } } } } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadGraphShader( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; GraphData* graphData = static_cast<GraphData*>(trackedFile.userData); std::array<ID3DBlob**, ShaderType_Count> shaderLoadList; shaderLoadList.fill( nullptr ); shaderLoadList[ShaderType_Vertex] = graphData->vertexShader.GetAddressOf(); if ( CompileShader( trackedFile.filename, shaderLoadList, trackedFile.errorList ) ) { if ( graphData->pso ) { m_pendingDeletes.emplace_back( PendingDeleteData{ graphData->pso, m_fenceValues[m_frameIndex] } ); graphData->pso = nullptr; } std::array<ComPtr<ID3DBlob>, ShaderType_Count> graphShaders( m_graphShaders ); graphShaders[ShaderType_Vertex] = graphData->vertexShader; graphData->name = trackedFile.filename; graphData->pso = CreateGraphicsPSO( graphData->name, nullptr, 0, graphShaders, D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, D3D12_CULL_MODE_NONE, s_blendedRenderTargetBlendDesc ); } } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadAllHeatmapShaders( TrackedFile& trackedFile ) { std::array<ID3DBlob**, ShaderType_Count> shaderLoadList; for ( int i = 0; i < ShaderType_Count; ++i ) { shaderLoadList[i] = m_heatmapShaders[i].GetAddressOf(); } if ( CompileShader( trackedFile.filename, shaderLoadList, trackedFile.errorList ) ) { std::array<ComPtr<ID3DBlob>, ShaderType_Count> heatmapShaders( m_heatmapShaders ); for ( HeatmapData& heatmapData : m_heatmapList ) { if ( heatmapData.pso ) { m_pendingDeletes.emplace_back( PendingDeleteData{ heatmapData.pso, m_fenceValues[m_frameIndex] } ); heatmapData.pso = nullptr; } if ( heatmapData.pixelShader ) { heatmapShaders[ShaderType_Pixel] = heatmapData.pixelShader; heatmapData.pso = CreateGraphicsPSO( heatmapData.name, nullptr, 0, heatmapShaders, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, D3D12_CULL_MODE_NONE, s_opaqueRenderTargetBlendDesc ); } } } } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadHeatmapShader( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; HeatmapData* heatmapData = static_cast<HeatmapData*>(trackedFile.userData); std::array<ID3DBlob**, ShaderType_Count> shaderLoadList; shaderLoadList.fill( nullptr ); shaderLoadList[ShaderType_Pixel] = heatmapData->pixelShader.GetAddressOf(); if ( CompileShader( trackedFile.filename, shaderLoadList, trackedFile.errorList ) ) { if ( heatmapData->pso ) { m_pendingDeletes.emplace_back( PendingDeleteData{ heatmapData->pso, m_fenceValues[m_frameIndex] } ); heatmapData->pso = nullptr; } std::array<ComPtr<ID3DBlob>, ShaderType_Count> heatmapShaders( m_heatmapShaders ); heatmapShaders[ShaderType_Pixel] = heatmapData->pixelShader; heatmapData->name = trackedFile.filename; heatmapData->pso = CreateGraphicsPSO( heatmapData->name, nullptr, 0, heatmapShaders, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, D3D12_CULL_MODE_NONE, s_opaqueRenderTargetBlendDesc ); } } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadDrawShader( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; DrawData* drawData = static_cast<DrawData*>(trackedFile.userData); std::array<ID3DBlob**, ShaderType_Count> shaderLoadList; shaderLoadList.fill( nullptr ); shaderLoadList[ShaderType_Vertex] = drawData->vertexShader.GetAddressOf(); shaderLoadList[ShaderType_Pixel] = drawData->pixelShader.GetAddressOf(); if ( CompileShader( trackedFile.filename, shaderLoadList, trackedFile.errorList ) ) { if ( drawData->pso ) { m_pendingDeletes.emplace_back( PendingDeleteData{ drawData->pso, m_fenceValues[m_frameIndex] } ); drawData->pso = nullptr; } std::array<ComPtr<ID3DBlob>, ShaderType_Count> drawShaders; drawShaders.fill( nullptr ); drawShaders[ShaderType_Vertex] = drawData->vertexShader; drawShaders[ShaderType_Pixel] = drawData->pixelShader; drawData->name = trackedFile.filename; drawData->pso = CreateGraphicsPSO( drawData->name, nullptr, 0, drawShaders, D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, D3D12_CULL_MODE_NONE, s_blendedRenderTargetBlendDesc ); } } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadDispatchShader( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; DispatchData* dispatchData = static_cast<DispatchData*>(trackedFile.userData); std::array<ID3DBlob**, ShaderType_Count> shaderLoadList; shaderLoadList.fill( nullptr ); shaderLoadList[ShaderType_Compute] = dispatchData->shader.GetAddressOf(); if ( CompileShader( trackedFile.filename, shaderLoadList, trackedFile.errorList ) ) { if ( dispatchData->pso ) { m_pendingDeletes.emplace_back( PendingDeleteData{ dispatchData->pso, m_fenceValues[m_frameIndex] } ); dispatchData->pso = nullptr; } dispatchData->pso = CreateComputePSO( dispatchData->name, dispatchData->shader.Get() ); } // Restart sim m_simulationStep = 0; } //------------------------------------------------------------------------------------------------ void RocketSim::CreateConstantBuffer( const wchar_t* name, ResourceData& resourceData, const void* data, uint32_t size ) { if ( resourceData.resource ) { m_pendingDeletes.emplace_back( PendingDeleteData{ resourceData.resource, m_fenceValues[m_frameIndex] } ); } resourceData.resource = CreateDefaultBuffer( name, data, RoundUpPow2( size, 256u ), D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, false ); if ( resourceData.resource ) { D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {}; cbvDesc.BufferLocation = resourceData.resource->GetGPUVirtualAddress(); cbvDesc.SizeInBytes = RoundUpPow2( size, 256u ); m_device->CreateConstantBufferView( &cbvDesc, resourceData.desc ); resourceData.size = size; } } //------------------------------------------------------------------------------------------------ void RocketSim::CreateFloat4Buffer( const wchar_t * name, ComPtr<ID3D12Resource>& resource, D3D12_CPU_DESCRIPTOR_HANDLE srvDescHandle, const ShaderShared::float4* data, uint32_t elements ) { if ( resource ) { m_pendingDeletes.emplace_back( PendingDeleteData{ resource, m_fenceValues[m_frameIndex] } ); } resource = CreateDefaultBuffer( name, data, sizeof( ShaderShared::float4 ) * size_t( elements ), D3D12_RESOURCE_STATE_SHADER_RESOURCE, false ); if ( resource ) { D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Buffer.NumElements = elements; m_device->CreateShaderResourceView( resource.Get(), &srvDesc, srvDescHandle ); } } //------------------------------------------------------------------------------------------------ void RocketSim::CreateStructuredBuffer( const wchar_t* name, ComPtr<ID3D12Resource>& resource, D3D12_CPU_DESCRIPTOR_HANDLE srvDescHandle, const void* data, uint32_t stride, uint32_t elements ) { if ( resource ) { m_pendingDeletes.emplace_back( PendingDeleteData{ resource, m_fenceValues[m_frameIndex] } ); } resource = CreateDefaultBuffer( name, data, size_t( stride ) * size_t( elements ), D3D12_RESOURCE_STATE_SHADER_RESOURCE, false ); if ( resource ) { D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; srvDesc.Format = DXGI_FORMAT_UNKNOWN; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Buffer.NumElements = elements; srvDesc.Buffer.StructureByteStride = stride; m_device->CreateShaderResourceView( resource.Get(), &srvDesc, srvDescHandle ); } } //------------------------------------------------------------------------------------------------ void RocketSim::CreateRWStructuredBuffer( const wchar_t* name, TrackedResource& resource, D3D12_CPU_DESCRIPTOR_HANDLE srvDescHandle, D3D12_CPU_DESCRIPTOR_HANDLE uavDescHandle, uint32_t stride, uint32_t elements ) { if ( resource.resource ) { m_pendingDeletes.emplace_back( PendingDeleteData{ resource.resource, m_fenceValues[m_frameIndex] } ); } resource.resource = CreateDefaultBuffer( name, nullptr, size_t(stride) * size_t(elements), D3D12_RESOURCE_STATE_COMMON, true ); if ( resource.resource ) { resource.state = D3D12_RESOURCE_STATE_COMMON; m_uavResources.push_back( &resource ); if ( srvDescHandle.ptr ) { D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; srvDesc.Format = DXGI_FORMAT_UNKNOWN; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Buffer.NumElements = elements; srvDesc.Buffer.StructureByteStride = stride; m_device->CreateShaderResourceView( resource.resource.Get(), &srvDesc, srvDescHandle ); } D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; uavDesc.Format = DXGI_FORMAT_UNKNOWN; uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uavDesc.Buffer.NumElements = elements; uavDesc.Buffer.StructureByteStride = stride; m_device->CreateUnorderedAccessView( resource.resource.Get(), nullptr, &uavDesc, uavDescHandle ); } } //------------------------------------------------------------------------------------------------ nlohmann::json RocketSim::LoadJsonFile( const wchar_t* filename ) { std::ifstream iStream( filename ); if ( iStream.fail() ) { throw nlohmann::json::other_error::create( 502, "Failed to open file." ); } nlohmann::json j; iStream >> j; return j; } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadAscentParams( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; trackedFile.errorList.clear(); try { nlohmann::json ascentJson = LoadJsonFile( trackedFile.filename ); float minSpeed = ascentJson.value( "minSpeed", 20.0f ); float maxSpeed = ascentJson.value( "maxSpeed", 100.0f ); float minAngle = ascentJson.value( "minAngle", 1.0f ); float maxAngle = ascentJson.value( "maxAngle", 5.0f ); float speedStep = (maxSpeed - minSpeed) / float( m_ascentParams.size() - 1 ); float angleStep = (maxAngle - minAngle) / float( m_ascentParams[0].size() - 1 ); for ( uint32_t angle = 0; angle < m_ascentParams[0].size(); ++angle ) { float a = (minAngle + angle * angleStep) * c_DegreeToRad; m_ascentParams[0][angle].pitchOverSpeed = minSpeed; m_ascentParams[0][angle].sinPitchOverAngle = sin( a ); m_ascentParams[0][angle].cosPitchOverAngle = cos( a ); m_ascentParams[0][angle].sinAimAngle = sin( a + c_DegreeToRad ); m_ascentParams[0][angle].cosAimAngle = cos( a + c_DegreeToRad ); } for ( uint32_t speed = 1; speed < m_ascentParams.size(); ++speed ) { float pitchOverSpeed = minSpeed + speed * speedStep; for ( uint32_t angle = 0; angle < m_ascentParams[0].size(); ++angle ) { m_ascentParams[speed][angle].pitchOverSpeed = pitchOverSpeed; m_ascentParams[speed][angle].sinPitchOverAngle = m_ascentParams[speed - 1][angle].sinPitchOverAngle; m_ascentParams[speed][angle].cosPitchOverAngle = m_ascentParams[speed - 1][angle].cosPitchOverAngle; m_ascentParams[speed][angle].sinAimAngle = m_ascentParams[speed - 1][angle].sinAimAngle; m_ascentParams[speed][angle].cosAimAngle = m_ascentParams[speed - 1][angle].cosAimAngle; } } ResourceData* resourceData = static_cast<ResourceData*>(trackedFile.userData); CreateStructuredBuffer( trackedFile.filename, resourceData->resource, resourceData->desc, m_ascentParams.data(), sizeof( ShaderShared::AscentParams ), static_cast<uint32_t>(m_ascentParams.size() * m_ascentParams[0].size()) ); // Restart sim m_simulationStep = 0; m_autoSelectData = true; } catch ( nlohmann::json::exception& e ) { ErrorTrace( trackedFile, L"%S", e.what() ); } } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadMissionParams( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; trackedFile.errorList.clear(); try { nlohmann::json missionParamsJson = LoadJsonFile( trackedFile.filename ); memset( &m_missionParams, 0, sizeof( m_missionParams ) ); m_missionParams.stageCount = 0; for ( const nlohmann::json& stageJson : missionParamsJson["stages"] ) { m_missionParams.stage[m_missionParams.stageCount].wetMass = stageJson.value( "wetmass", 0.0f ); m_missionParams.stage[m_missionParams.stageCount].dryMass = stageJson.value( "drymass", 0.0f ); m_missionParams.stage[m_missionParams.stageCount].IspSL = stageJson.value( "IspSL", 0.0f ); m_missionParams.stage[m_missionParams.stageCount].IspVac = stageJson.value( "IspVac", 0.0f ); m_missionParams.stage[m_missionParams.stageCount].rotationRate = c_DegreeToRad; float fuelMass = stageJson.value( "fuelmass", 0.0f ); if ( fuelMass > 0.0f ) m_missionParams.stage[m_missionParams.stageCount].dryMass = m_missionParams.stage[m_missionParams.stageCount].wetMass - fuelMass; if ( m_missionParams.stage[m_missionParams.stageCount].IspVac > 0.0f ) { // Convert thrust (in kN) to mass flow rate float thrust = stageJson.value( "thrustVac", 0.0f ); float thrustLimit = stageJson.value( "thrustLimit", 1.0f ); thrustLimit = std::min( std::max( thrustLimit, 0.0f ), 1.0f ); m_missionParams.stage[m_missionParams.stageCount].massFlow = thrust * 1000.0f * thrustLimit / (9.82025f * m_missionParams.stage[m_missionParams.stageCount].IspVac); } if ( m_missionParams.stage[m_missionParams.stageCount].dryMass > 0.0f ) { if ( ++m_missionParams.stageCount >= ARRAY_SIZE( m_missionParams.stage ) ) break; } } double Ap = missionParamsJson.value( "apoapsis", 200000.0 ) + earthRadius; double Pe = missionParamsJson.value( "periapsis", 200000.0 ) + earthRadius; double a = (Ap + Pe) / 2.0; double e = 1 - Pe / a; double L = a * (1 - e * e); m_missionParams.finalState.r = float(Pe); m_missionParams.finalState.rv = 0; m_missionParams.finalState.h = float( sqrt( earthMu * L ) ); m_missionParams.finalState.omega = m_missionParams.finalState.h / float( sqr(Pe) ); m_missionParams.finalOrbitalEnergy = float( -earthMu / (2 * a)); CreateConstantBuffer( trackedFile.filename, *static_cast<ResourceData*>(trackedFile.userData), &m_missionParams, sizeof( m_missionParams ) ); // Restart sim m_simulationStep = 0; m_autoSelectData = true; } catch ( nlohmann::json::exception& e ) { ErrorTrace( trackedFile, L"%S", e.what() ); } } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadEnvironmentalParams( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; trackedFile.errorList.clear(); try { nlohmann::json enviroParamsJson = LoadJsonFile( trackedFile.filename ); earthMu = enviroParamsJson.value("gravConstant", earthMu); earthRadius = enviroParamsJson.value("earthRadius", earthRadius); earthg0 = earthMu / (earthRadius * earthRadius); float data[] = { float( earthMu ), float( earthRadius ), float( earthg0 ), enviroParamsJson.value( "airMolarMass", 0.0289644f ), 8.3144598f, // universal gas constant enviroParamsJson.value( "adiabaticIndex", 1.4f ), enviroParamsJson.value( "launchLatitude", 28.608389f ), enviroParamsJson.value( "launchAltitude", 85.0f ), enviroParamsJson.value( "rotationPeriod", 86164.098903691f ), }; CreateConstantBuffer( trackedFile.filename, *static_cast<ResourceData*>(trackedFile.userData), data, sizeof( data ) ); // Reload mission params as they depend on earthRadius InvalidateTrackedFile( L"mission_params.json" ); // Restart sim m_simulationStep = 0; m_autoSelectData = true; } catch ( nlohmann::json::exception& e ) { ErrorTrace( trackedFile, L"%S", e.what() ); } } //------------------------------------------------------------------------------------------------ static void GenerateMonotonicInterpolants( std::vector<ShaderShared::float4>& curveData ) { std::vector<float> delta; for ( uint32_t i = 0; i < curveData.size() - 1; ++i ) { delta.emplace_back( (curveData[i + 1].y - curveData[i].y) / (curveData[i + 1].x - curveData[i].x) ); } std::vector<float> tangents; tangents.emplace_back( delta.front() ); for ( uint32_t i = 1; i < delta.size(); ++i ) { if ( (delta[i - 1] > 0.0f) == (delta[i] > 0.0f) ) tangents.emplace_back( (delta[i - 1] + delta[i]) / 2 ); else tangents.emplace_back( 0.0f ); } tangents.emplace_back( delta.back() ); for ( uint32_t i = 0; i < delta.size(); ++i ) { if ( fabs( delta[i] ) < FLT_EPSILON ) { tangents[i] = 0.f; tangents[i + 1] = 0.f; ++i; } else { float alpha = tangents[i] / delta[i]; float beta = tangents[i + 1] / delta[i]; if ( alpha < 0.0f || beta < 0.0f ) { tangents[i] = 0.f; } else { float s = alpha * alpha + beta * beta; if ( s > 9.0f ) { s = 3.0f / sqrt( s ); tangents[i] = s * alpha * delta[i]; tangents[i + 1] = s * beta * delta[i]; } } } } for ( uint32_t i = 0; i < curveData.size(); ++i ) { curveData[i].z = curveData[i].w = tangents[i]; } } //------------------------------------------------------------------------------------------------ static void FixupHermiteTangents( std::vector<ShaderShared::float4>& curveData ) { curveData[0].z = 0.0f; curveData[0].w *= (curveData[1].x - curveData[0].x); uint32_t i; for ( i = 1; i < curveData.size() - 1; ++i ) { curveData[i].z *= (curveData[i].x - curveData[i - 1].x); curveData[i].w *= (curveData[i + 1].x - curveData[i].x); } curveData[i].z *= (curveData[i].x - curveData[i - 1].x); curveData[i].w = 0.0f; } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadMachSweep( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; trackedFile.errorList.clear(); std::ifstream iStream( trackedFile.filename ); if ( iStream.fail() ) { ErrorTrace( trackedFile, L"Failed to open file." ); return; } char line[500]; iStream.getline( line, ARRAY_SIZE( line ) ); std::vector<std::string> headers; char* context; for ( const char* token = strtok_s( line, ",", &context ); token; token = strtok_s( nullptr, ",", &context ) ) { headers.emplace_back( token ); std::for_each(headers.back().begin(), headers.back().end(), [] (char& a) { a = static_cast<char>(tolower(a)); } ); } std::vector<std::vector<double>> data; data.emplace_back(); for (;;) { std::ifstream::int_type c; for (;;) { c = iStream.peek(); if ( c == std::ifstream::traits_type::eof() || isdigit( c ) || c == '-' ) break; iStream.get(); } float f; iStream >> f; if (!iStream.good()) break; if ( data.back().size() < headers.size() ) data.back().push_back( f ); else data.emplace_back( std::vector<double>( 1, f ) ); } if ( data.size() > 0 ) { ResourceData& resourceData = *static_cast<ResourceData*>(trackedFile.userData); for ( uint32_t i = 1; i < data.size(); ++i ) { data.erase( data.begin() + i ); } const char* columnNames[] = { "mach", "a", "cd" }; double scale = 1.0f; if ( resourceData.desc.ptr >= m_shaderHeap.GetCPUHandle( ShaderShared::srvLiftMachCurve ).ptr && resourceData.desc.ptr <= m_shaderHeap.GetCPUHandle( ShaderShared::srvLiftMachCurve, 3 ).ptr ) { columnNames[2] = "cl"; scale = 1000; } std::array<uint32_t, ARRAY_SIZE( columnNames )> columnIndex; for ( uint32_t i = 0; i < columnIndex.size(); ++i ) { std::vector<std::string>::const_iterator colIter = std::find( headers.cbegin(), headers.cend(), columnNames[i] ); if ( colIter == headers.cend() ) { ErrorTrace( trackedFile, L"Missing %c%s column.", toupper( *columnNames[i] ), columnNames[i] + 1 ); return; } columnIndex[i] = static_cast<uint32_t>(colIter - headers.cbegin()); } std::vector<ShaderShared::float4> curveData; curveData.reserve( data.size() ); for ( const std::vector<double>& src : data ) { float mach = float(src[columnIndex[0]]); float y = float(src[columnIndex[2]] * src[columnIndex[1]] * scale); curveData.emplace_back( mach, y, 0.0f, 0.0f ); } GenerateMonotonicInterpolants( curveData ); FixupHermiteTangents( curveData ); wchar_t name[200]; swprintf_s( name, L"%s:%SA", trackedFile.filename, columnNames[2] ); CreateFloat4Buffer( name, resourceData.resource, resourceData.desc, curveData.data(), static_cast<uint32_t>(curveData.size()) ); resourceData.size = static_cast<uint32_t>(curveData.size()); // Restart sim m_simulationStep = 0; } else { ErrorTrace( trackedFile, L"No valid data in file." ); } } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadHermiteCurve( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; trackedFile.errorList.clear(); try { nlohmann::json keyListJson = LoadJsonFile( trackedFile.filename ); std::vector<ShaderShared::float4> curveData; curveData.reserve( keyListJson.size() ); bool generateInterpolants = true; for ( const std::vector<float>& key : keyListJson["keys"] ) { if ( key.size() >= 4 ) { curveData.emplace_back( key[0], key[1], key[2], key[3] ); generateInterpolants = false; } else if ( key.size() >= 2 ) { curveData.emplace_back( key[0], key[1], 0.0f, 0.0f ); } } if ( curveData.size() > 0 ) { if ( curveData.size() > 1 ) { if ( generateInterpolants ) { GenerateMonotonicInterpolants( curveData ); } FixupHermiteTangents( curveData ); } ResourceData& resourceData = *static_cast<ResourceData*>(trackedFile.userData); CreateFloat4Buffer( trackedFile.filename, resourceData.resource, resourceData.desc, curveData.data(), static_cast<uint32_t>(curveData.size()) ); resourceData.size = static_cast<uint32_t>(curveData.size()); } else { ErrorTrace( trackedFile, L"No valid data in file." ); } // Restart sim m_simulationStep = 0; } catch ( nlohmann::json::exception& e ) { ErrorTrace( trackedFile, L"%S", e.what() ); } } //------------------------------------------------------------------------------------------------ void RocketSim::ReloadGraphColours( TrackedFile& trackedFile ) { if ( !trackedFile.userData ) return; trackedFile.errorList.clear(); try { nlohmann::json coloursJson = LoadJsonFile( trackedFile.filename ); std::vector<ShaderShared::float4> graphColours; graphColours.reserve( coloursJson.size() ); for ( const std::vector<int>& col : coloursJson["colours"] ) { if ( col.size() >= 3 ) { graphColours.emplace_back( col[0] / 255.0f, col[1] / 255.0f, col[2] / 255.0f, 1.0f ); } } if ( graphColours.size() > 0 ) { ResourceData& resourceData = *static_cast<ResourceData*>(trackedFile.userData); CreateFloat4Buffer( trackedFile.filename, resourceData.resource, resourceData.desc, graphColours.data(), static_cast<uint32_t>(graphColours.size()) ); resourceData.size = static_cast<uint32_t>(graphColours.size()); m_graphColours.clear(); m_graphColours.reserve( graphColours.size() ); std::for_each( graphColours.begin(), graphColours.end(), [this] ( const ShaderShared::float4& col ) { uint32_t ucol = (255 << 24) | (uint32_t( col.z * 255.0f ) << 16) | (uint32_t( col.y * 255.0f ) << 8) | uint32_t( col.x * 255.0f ); m_graphColours.emplace_back(ucol); } ); } else { ErrorTrace( trackedFile, L"No valid data in file." ); } } catch ( nlohmann::json::exception& e ) { ErrorTrace( trackedFile, L"%S", e.what() ); } } //------------------------------------------------------------------------------------------------ void RocketSim::ErrorTrace( TrackedFile& trackedFile, const wchar_t* fmt, ... ) { wchar_t message[2000]; wcscpy_s( message, trackedFile.filename ); wcscat_s( message, L": " ); size_t n = wcslen( message ); va_list args; va_start( args, fmt ); if ( vswprintf_s( message + n, ARRAY_SIZE( message ) - n, fmt, args ) > 0 ) { trackedFile.errorList.emplace_back( message ); wcscat_s( message, L"\r\n" ); OutputDebugString( message ); } va_end( args ); } //------------------------------------------------------------------------------------------------ RocketSim::ErrorResult RocketSim::ErrorHandler( HRESULT hr, const wchar_t* szOperation ) { if ( SUCCEEDED( hr ) ) { return ErrorResult::CONTINUE; } wchar_t szErrorMsg[500]; swprintf_s( szErrorMsg, L"Could not %s: %d", szOperation, hr ); MessageBox( m_hwnd, szErrorMsg, szTitle, MB_OK | MB_ICONERROR ); DestroyWindow( m_hwnd ); return ErrorResult::ABORT; } //------------------------------------------------------------------------------------------------ void RocketSim::UpdateTrackedFiles() { for ( TrackedFile& trackedFile : m_trackedFiles ) { WIN32_FIND_DATA findData; HANDLE hFind = FindFirstFile( trackedFile.filename, &findData ); if ( hFind != INVALID_HANDLE_VALUE ) { FindClose( hFind ); if ( CompareFileTime( &trackedFile.lastUpdate, &findData.ftLastWriteTime ) != 0 ) { trackedFile.lastUpdate = findData.ftLastWriteTime; (this->*trackedFile.updateCallback)(trackedFile); } } } } //------------------------------------------------------------------------------------------------ void RocketSim::InvalidateTrackedFile( const wchar_t* filename ) { for ( TrackedFile& trackedFile : m_trackedFiles ) { if ( !_wcsicmp( filename, trackedFile.filename ) ) { trackedFile.lastUpdate.dwLowDateTime = 0; trackedFile.lastUpdate.dwHighDateTime = 0; break; } } } //------------------------------------------------------------------------------------------------ void RocketSim::DrawTrackedFileErrors() { PixMarker marker( m_commandList.Get(), L"DrawTrackedFileErrors" ); float scale = 0.44f; float xpos = -0.98f; float ypos = 0.98f - m_font.GetTopAlign() * scale; ShaderShared::DrawConstData drawConsts = m_currentDrawConsts; for ( TrackedFile& trackedFile : m_trackedFiles ) { for ( const std::wstring& errorLine : trackedFile.errorList ) { if ( m_boxDraw.pso ) { drawConsts.invViewportSize.x = xpos; drawConsts.invViewportSize.y = ypos + m_font.GetTopAlign() * scale; drawConsts.viewportSize.x = m_font.CalcTextLength( errorLine.c_str() ) * scale; drawConsts.viewportSize.y = -m_font.GetLineSpacing() * scale; SetDrawConstants( drawConsts ); m_commandList->SetPipelineState( m_boxDraw.pso.Get() ); m_commandList->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); m_commandList->DrawInstanced( 4, 1, 0, 0 ); } m_font.DrawText( xpos, ypos, scale, 0.0f, 0xff0000df, errorLine.c_str() ); ypos -= m_font.GetLineSpacing() * scale; if ( ypos <= -1.0f ) return; } } } //------------------------------------------------------------------------------------------------ void RocketSim::WaitForGPU() { // Schedule a Signal command in the queue. m_commandQueue->Signal( m_fence.Get(), m_fenceValues[m_frameIndex] ); // Wait until the fence has been processed. m_fence->SetEventOnCompletion( m_fenceValues[m_frameIndex], m_fenceEvent ); WaitForSingleObjectEx( m_fenceEvent, INFINITE, FALSE ); // Increment the fence value for the current frame. ++m_fenceValues[m_frameIndex]; } //------------------------------------------------------------------------------------------------ void RocketSim::BarrierTransition( ID3D12Resource* resource, D3D12_RESOURCE_STATES stateBefore, D3D12_RESOURCE_STATES stateAfter ) { D3D12_RESOURCE_BARRIER barrier; memset( &barrier, 0, sizeof( barrier ) ); barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.pResource = resource; barrier.Transition.StateBefore = stateBefore; barrier.Transition.StateAfter = stateAfter; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; m_commandList->ResourceBarrier( 1, &barrier ); } //------------------------------------------------------------------------------------------------ void RocketSim::BarrierTransition( TrackedResource & resource, D3D12_RESOURCE_STATES newState ) { if ( resource.state != newState ) { D3D12_RESOURCE_BARRIER barrier; memset( &barrier, 0, sizeof( barrier ) ); barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barrier.Transition.pResource = resource.resource.Get(); barrier.Transition.StateBefore = resource.state; barrier.Transition.StateAfter = newState; barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; m_commandList->ResourceBarrier( 1, &barrier ); resource.state = newState; } } //------------------------------------------------------------------------------------------------ void RocketSim::BarrierTransition( std::vector<TrackedResource*> resourceList, D3D12_RESOURCE_STATES newState ) { if ( resourceList.empty() ) return; D3D12_RESOURCE_BARRIER* barriers = static_cast<D3D12_RESOURCE_BARRIER*>(alloca( sizeof( D3D12_RESOURCE_BARRIER ) * resourceList.size() )); memset( barriers, 0, sizeof( D3D12_RESOURCE_BARRIER ) * resourceList.size() ); uint32_t count = 0; for ( TrackedResource* resource : resourceList ) { if ( resource->state != newState ) { barriers[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; barriers[count].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barriers[count].Transition.pResource = resource->resource.Get(); barriers[count].Transition.StateBefore = resource->state; barriers[count].Transition.StateAfter = newState; barriers[count].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; ++count; resource->state = newState; } } if (count) { m_commandList->ResourceBarrier( count, barriers ); } } //------------------------------------------------------------------------------------------------ void RocketSim::BarrierUAV( std::vector<TrackedResource*> resourceList ) { if ( resourceList.empty() ) return; D3D12_RESOURCE_BARRIER* barriers = static_cast<D3D12_RESOURCE_BARRIER*>(alloca( sizeof( D3D12_RESOURCE_BARRIER ) * resourceList.size() )); memset( barriers, 0, sizeof( D3D12_RESOURCE_BARRIER ) * resourceList.size() ); for ( uint_fast32_t i = 0; i < resourceList.size(); ++i ) { barriers[i].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; barriers[i].Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; barriers[i].UAV.pResource = resourceList[i]->resource.Get(); } m_commandList->ResourceBarrier( static_cast<UINT>(resourceList.size()), barriers ); } //------------------------------------------------------------------------------------------------ ComPtr<ID3D12Resource> RocketSim::CreateUploadBuffer( const wchar_t* name, const void* data, size_t size ) { // Create upload buffer D3D12_HEAP_PROPERTIES heapProperties; heapProperties.Type = D3D12_HEAP_TYPE_UPLOAD; heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProperties.CreationNodeMask = 1; heapProperties.VisibleNodeMask = 1; D3D12_RESOURCE_DESC bufferDesc; bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; bufferDesc.Alignment = 0; bufferDesc.Width = size; bufferDesc.Height = 1; bufferDesc.DepthOrArraySize = 1; bufferDesc.MipLevels = 1; bufferDesc.Format = DXGI_FORMAT_UNKNOWN; bufferDesc.SampleDesc.Count = 1; bufferDesc.SampleDesc.Quality = 0; bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; bufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; ComPtr<ID3D12Resource> uploadBuffer; if ( ErrorHandler( m_device->CreateCommittedResource( &heapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &uploadBuffer ) ), L"CreateUploadBuffer" ) == ErrorResult::ABORT ) return nullptr; uploadBuffer->SetName( name ); if ( data ) { // Copy the data to the upload buffer. UINT8* dataBegin; D3D12_RANGE readRange = { 0 }; if ( ErrorHandler( uploadBuffer->Map( 0, &readRange, reinterpret_cast<void**>(&dataBegin) ), L"Map Buffer" ) == ErrorResult::ABORT ) return nullptr; memcpy( dataBegin, data, size ); uploadBuffer->Unmap( 0, nullptr ); } return uploadBuffer; } //------------------------------------------------------------------------------------------------ ComPtr<ID3D12Resource> RocketSim::CreateReadbackBuffer( const wchar_t* name, size_t size ) { // Create readback buffer D3D12_HEAP_PROPERTIES heapProperties; heapProperties.Type = D3D12_HEAP_TYPE_READBACK; heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProperties.CreationNodeMask = 1; heapProperties.VisibleNodeMask = 1; D3D12_RESOURCE_DESC bufferDesc; bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; bufferDesc.Alignment = 0; bufferDesc.Width = size; bufferDesc.Height = 1; bufferDesc.DepthOrArraySize = 1; bufferDesc.MipLevels = 1; bufferDesc.Format = DXGI_FORMAT_UNKNOWN; bufferDesc.SampleDesc.Count = 1; bufferDesc.SampleDesc.Quality = 0; bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; bufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; ComPtr<ID3D12Resource> readbackBuffer; if ( ErrorHandler( m_device->CreateCommittedResource( &heapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS( &readbackBuffer ) ), L"CreateReadbackBuffer" ) == ErrorResult::ABORT ) return nullptr; readbackBuffer->SetName( name ); return readbackBuffer; } //------------------------------------------------------------------------------------------------ ComPtr<ID3D12Resource> RocketSim::CreateDefaultBuffer( const wchar_t* name, const void* data, size_t size, D3D12_RESOURCE_STATES targetState, bool allowUAV ) { // Create default buffer D3D12_HEAP_PROPERTIES heapProperties; heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT; heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProperties.CreationNodeMask = 1; heapProperties.VisibleNodeMask = 1; D3D12_RESOURCE_DESC bufferDesc; bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; bufferDesc.Alignment = 0; bufferDesc.Width = size; bufferDesc.Height = 1; bufferDesc.DepthOrArraySize = 1; bufferDesc.MipLevels = 1; bufferDesc.Format = DXGI_FORMAT_UNKNOWN; bufferDesc.SampleDesc.Count = 1; bufferDesc.SampleDesc.Quality = 0; bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; bufferDesc.Flags = allowUAV ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE; ComPtr<ID3D12Resource> defaultBuffer; D3D12_RESOURCE_STATES state = data ? D3D12_RESOURCE_STATE_COPY_DEST : targetState; if ( ErrorHandler( m_device->CreateCommittedResource( &heapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc, state, nullptr, IID_PPV_ARGS( &defaultBuffer ) ), L"CreateBuffer" ) == ErrorResult::ABORT ) return nullptr; defaultBuffer->SetName( name ); if ( data ) { // Create upload buffer bufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; heapProperties.Type = D3D12_HEAP_TYPE_UPLOAD; ComPtr<ID3D12Resource> uploadBuffer; if ( ErrorHandler( m_device->CreateCommittedResource( &heapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &uploadBuffer ) ), L"CreateUploadBuffer" ) == ErrorResult::ABORT ) return nullptr; uploadBuffer->SetName( name ); // Copy the data to the upload buffer. UINT8* dataBegin; D3D12_RANGE readRange = { 0 }; if ( ErrorHandler( uploadBuffer->Map( 0, &readRange, reinterpret_cast<void**>(&dataBegin) ), L"Map Buffer" ) == ErrorResult::ABORT ) return nullptr; memcpy( dataBegin, data, size ); uploadBuffer->Unmap( 0, nullptr ); m_pendingUploads.emplace_back( PendingUploadData{ uploadBuffer, defaultBuffer, D3D12_PLACED_SUBRESOURCE_FOOTPRINT{}, targetState } ); } return defaultBuffer; } //------------------------------------------------------------------------------------------------ ComPtr<ID3D12Resource> RocketSim::CreateTexture( const wchar_t* name, const void* data, size_t width, size_t height, DXGI_FORMAT format, size_t texelSize, D3D12_RESOURCE_STATES targetState, bool allowUAV ) { // Create default buffer D3D12_HEAP_PROPERTIES heapProperties; heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT; heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProperties.CreationNodeMask = 1; heapProperties.VisibleNodeMask = 1; // Describe and create a Texture2D. D3D12_RESOURCE_DESC textureDesc = {}; textureDesc.MipLevels = 1; textureDesc.Format = format; textureDesc.Width = UINT( width ); textureDesc.Height = UINT( height ); textureDesc.Flags = allowUAV ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE; textureDesc.DepthOrArraySize = 1; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; ComPtr<ID3D12Resource> texture; D3D12_RESOURCE_STATES state = data ? D3D12_RESOURCE_STATE_COPY_DEST : targetState; if ( ErrorHandler( m_device->CreateCommittedResource( &heapProperties, D3D12_HEAP_FLAG_NONE, &textureDesc, state, nullptr, IID_PPV_ARGS( &texture ) ), L"CreateTexture" ) == ErrorResult::ABORT ) return nullptr; texture->SetName( name ); if ( data ) { // Create upload buffer UINT64 bufferSize = 0; D3D12_PLACED_SUBRESOURCE_FOOTPRINT layout; UINT numRows; UINT64 rowSize; m_device->GetCopyableFootprints( &textureDesc, 0, 1, 0, &layout, &numRows, &rowSize, &bufferSize ); D3D12_RESOURCE_DESC bufferDesc; bufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; bufferDesc.Alignment = 0; bufferDesc.Width = bufferSize; bufferDesc.Height = 1; bufferDesc.DepthOrArraySize = 1; bufferDesc.MipLevels = 1; bufferDesc.Format = DXGI_FORMAT_UNKNOWN; bufferDesc.SampleDesc.Count = 1; bufferDesc.SampleDesc.Quality = 0; bufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; bufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; heapProperties.Type = D3D12_HEAP_TYPE_UPLOAD; ComPtr<ID3D12Resource> uploadBuffer; if ( ErrorHandler( m_device->CreateCommittedResource( &heapProperties, D3D12_HEAP_FLAG_NONE, &bufferDesc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS( &uploadBuffer ) ), L"CreateUploadBuffer" ) == ErrorResult::ABORT ) return nullptr; uploadBuffer->SetName( name ); // Copy the data to the upload buffer. BYTE* dataBegin; D3D12_RANGE readRange = { 0 }; if ( ErrorHandler( uploadBuffer->Map( 0, &readRange, reinterpret_cast<void**>(&dataBegin) ), L"Map Buffer" ) == ErrorResult::ABORT ) return nullptr; dataBegin += layout.Offset; UINT srcRowPitch = UINT( width * texelSize ); UINT srcSlicePitch = UINT( srcRowPitch * height ); UINT dstRowPitch = layout.Footprint.RowPitch; UINT dstSlicePitch = dstRowPitch * numRows; for ( UINT z = 0; z < layout.Footprint.Depth; ++z ) { BYTE* pDestSlice = dataBegin + dstSlicePitch * z; const BYTE* pSrcSlice = reinterpret_cast<const BYTE*>(data) + srcSlicePitch * z; for ( UINT y = 0; y < numRows; ++y ) { memcpy( pDestSlice + dstRowPitch * y, pSrcSlice + srcRowPitch * y, size_t( rowSize ) ); } } uploadBuffer->Unmap( 0, nullptr ); m_pendingUploads.emplace_back( PendingUploadData{ uploadBuffer, texture, layout, targetState } ); } return texture; } //------------------------------------------------------------------------------------------------ ID3D12PipelineState* RocketSim::CreateGraphicsPSO( const wchar_t* name, const D3D12_INPUT_ELEMENT_DESC* inputElements, UINT numInputElements, const std::array<ComPtr<ID3DBlob>, ShaderType_Count>& shaderList, D3D12_PRIMITIVE_TOPOLOGY_TYPE topology, D3D12_CULL_MODE cullMode, const D3D12_RENDER_TARGET_BLEND_DESC& blendDesc ) { // Describe and create the graphics pipeline state object (PSO). D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.InputLayout = { inputElements, numInputElements }; psoDesc.pRootSignature = m_rootSignature.Get(); psoDesc.DepthStencilState.DepthEnable = FALSE; psoDesc.DepthStencilState.StencilEnable = FALSE; psoDesc.SampleMask = UINT_MAX; psoDesc.PrimitiveTopologyType = topology; psoDesc.NumRenderTargets = 1; psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; psoDesc.SampleDesc.Count = 1; D3D12_SHADER_BYTECODE* byteCode[] = { &psoDesc.VS, &psoDesc.PS, &psoDesc.DS, &psoDesc.HS, &psoDesc.GS }; for ( uint_fast32_t i = 0; i < ARRAY_SIZE( byteCode ); ++i ) { if ( shaderList[i] ) { byteCode[i]->pShaderBytecode = shaderList[i]->GetBufferPointer(); byteCode[i]->BytecodeLength = shaderList[i]->GetBufferSize(); } } psoDesc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; psoDesc.RasterizerState.CullMode = cullMode; psoDesc.RasterizerState.FrontCounterClockwise = FALSE; psoDesc.RasterizerState.DepthBias = D3D12_DEFAULT_DEPTH_BIAS; psoDesc.RasterizerState.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP; psoDesc.RasterizerState.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; psoDesc.RasterizerState.DepthClipEnable = TRUE; psoDesc.RasterizerState.MultisampleEnable = FALSE; psoDesc.RasterizerState.AntialiasedLineEnable = FALSE; psoDesc.RasterizerState.ForcedSampleCount = 0; psoDesc.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; psoDesc.BlendState.AlphaToCoverageEnable = FALSE; psoDesc.BlendState.IndependentBlendEnable = FALSE; for ( UINT i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i ) psoDesc.BlendState.RenderTarget[i] = blendDesc; ID3D12PipelineState* pso = nullptr; m_device->CreateGraphicsPipelineState( &psoDesc, IID_PPV_ARGS( &pso ) ); if ( pso && name ) { pso->SetName( name ); } return pso; } //------------------------------------------------------------------------------------------------ ID3D12PipelineState* RocketSim::CreateComputePSO( const wchar_t * name, ID3DBlob* shader ) { if ( !shader ) { return nullptr; } D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {}; psoDesc.pRootSignature = m_rootSignature.Get(); psoDesc.CS.pShaderBytecode = shader->GetBufferPointer(); psoDesc.CS.BytecodeLength = shader->GetBufferSize(); ID3D12PipelineState* pso = nullptr; m_device->CreateComputePipelineState( &psoDesc, IID_PPV_ARGS( &pso ) ); if ( pso ) { pso->SetName( name ); } return pso; } //------------------------------------------------------------------------------------------------ static void UpdateDirtyConstants( uint32_t* dst, const uint32_t* src, std::vector<std::pair<uint32_t, uint32_t>>& ranges, uint32_t count ) { for ( uint32_t i = 0; i < count; ++i ) { if ( src[i] != dst[i] ) { dst[i] = src[i]; if ( ranges.empty() || ranges.back().second != i ) { ranges.emplace_back( i, i + 1 ); } else { ranges.back().second = i + 1; } } } } //------------------------------------------------------------------------------------------------ void RocketSim::SetDrawConstants( const ShaderShared::DrawConstData& drawConsts ) { constexpr uint32_t count = sizeof( ShaderShared::DrawConstData ) / sizeof( uint32_t ); const uint32_t* src = reinterpret_cast<const uint32_t*>(&drawConsts); uint32_t* dst = reinterpret_cast<uint32_t*>(&m_currentDrawConsts); std::vector<std::pair<uint32_t, uint32_t>> ranges; UpdateDirtyConstants(dst, src, ranges, count); for ( const std::pair<uint32_t, uint32_t>& r : ranges ) { if ( r.first == r.second ) m_commandList->SetGraphicsRoot32BitConstant( 0, dst[r.first], r.first ); else m_commandList->SetGraphicsRoot32BitConstants( 0, r.second - r.first, dst + r.first, r.first ); } } //------------------------------------------------------------------------------------------------ void RocketSim::SetDispatchConstants( const ShaderShared::DispatchConstData& dispatchConsts ) { constexpr uint32_t count = sizeof( ShaderShared::DispatchConstData ) / sizeof( uint32_t ); const uint32_t* src = reinterpret_cast<const uint32_t*>(&dispatchConsts); uint32_t* dst = reinterpret_cast<uint32_t*>(&m_currentDispatchConsts); std::vector<std::pair<uint32_t, uint32_t>> ranges; UpdateDirtyConstants( dst, src, ranges, count ); for ( const std::pair<uint32_t, uint32_t>& r : ranges ) { if ( r.first == r.second ) m_commandList->SetComputeRoot32BitConstant( 0, dst[r.first], r.first ); else m_commandList->SetComputeRoot32BitConstants( 0, r.second - r.first, dst + r.first, r.first ); } } //------------------------------------------------------------------------------------------------ void RocketSim::RenderFrame() { m_commandAllocators[m_frameIndex]->Reset(); m_commandList->Reset( m_commandAllocators[m_frameIndex].Get(), nullptr ); PixMarker::reset(); const UINT64 currentFenceValue = m_fenceValues[m_frameIndex]; UpdateTrackedFiles(); if ( !m_pendingDeletes.empty() ) { for ( std::vector<TrackedResource*>::iterator resource = m_uavResources.begin(); resource != m_uavResources.end(); ) { if ( std::find( m_pendingDeletes.begin(), m_pendingDeletes.end(), (*resource)->resource.Get() ) != m_pendingDeletes.end() ) { resource = m_uavResources.erase( resource ); } else { ++resource; } } UINT64 completedFence = m_fence->GetCompletedValue(); m_pendingDeletes.erase( std::remove_if( m_pendingDeletes.begin(), m_pendingDeletes.end(), [completedFence] ( const PendingDeleteData& data ) { return data.fence <= completedFence; } ), m_pendingDeletes.end() ); } if ( !m_pendingUploads.empty() ) { PixMarker marker( m_commandList.Get(), L"Upload" ); for ( PendingUploadData& upload : m_pendingUploads ) { if ( upload.layout.Footprint.Format != DXGI_FORMAT_UNKNOWN ) { D3D12_TEXTURE_COPY_LOCATION dst{ upload.dest.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, 0 }; D3D12_TEXTURE_COPY_LOCATION src{ upload.source.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, upload.layout }; m_commandList->CopyTextureRegion( &dst, 0, 0, 0, &src, nullptr ); } else { m_commandList->CopyResource( upload.dest.Get(), upload.source.Get() ); } BarrierTransition( upload.dest.Get(), D3D12_RESOURCE_STATE_COPY_DEST, upload.targetState ); m_pendingDeletes.emplace_back( PendingDeleteData{ upload.source, currentFenceValue } ); } m_pendingUploads.clear(); } #ifdef _DEBUG if ( m_graphicsAnalysis && m_simulationStep == 0 && m_dispatchList[0].pso ) { m_graphicsAnalysis->BeginCapture(); } #endif // Update main constants m_frameConstData[m_frameIndex]->timeStep = m_simulationStepSize; m_frameConstData[m_frameIndex]->simDataStep = m_simulationThreadCount; m_frameConstData[m_frameIndex]->selectedData = m_selectedData; m_frameConstData[m_frameIndex]->selectionFlash = int( GetTimestampMilliSec() / 500.0f ) & 1; // Set necessary state. ID3D12DescriptorHeap* ppHeaps[] = { m_shaderHeap.GetHeap() }; m_commandList->SetDescriptorHeaps( _countof( ppHeaps ), ppHeaps ); { PixMarker marker( m_commandList.Get(), L"Simulation" ); m_commandList->SetComputeRootSignature( m_rootSignature.Get() ); m_commandList->SetComputeRootConstantBufferView( 1, m_frameConstantBuffer->GetGPUVirtualAddress() + m_frameIndex * RoundUpPow2( sizeof( ShaderShared::FrameConstData ), 256llu ) ); m_commandList->SetComputeRootDescriptorTable( 2, m_shaderHeap.GetHeap()->GetGPUDescriptorHandleForHeapStart() ); BarrierTransition( m_uavResources, D3D12_RESOURCE_STATE_UNORDERED_ACCESS ); if ( m_queryHeap && m_frameIndex == 0 ) m_commandList->EndQuery( m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0 ); // Mark current consts invalid memset( &m_currentDispatchConsts, 0xde, sizeof( m_currentDispatchConsts ) ); ShaderShared::DispatchConstData dispatchConsts; // Run N sim steps for ( uint32_t i = 0; i < m_simStepsPerFrame && m_simulationStep < (m_telemetryMaxSamples * m_telemetryStepSize); ++i ) { dispatchConsts.srcDataOffset = ((m_simulationStep - 1) / m_telemetryStepSize) * m_simulationThreadCount; dispatchConsts.dstDataOffset = (m_simulationStep / m_telemetryStepSize) * m_simulationThreadCount; if ( m_simulationStep == 0 ) dispatchConsts.srcDataOffset = ~0u; SetDispatchConstants( dispatchConsts ); bool simRunning = true; for ( const DispatchData& dispatchData : m_dispatchList ) { if ( dispatchData.perStep ) { if ( dispatchData.pso && dispatchData.threadGroupCount[0] > 0 ) { m_commandList->SetPipelineState( dispatchData.pso.Get() ); m_commandList->Dispatch( dispatchData.threadGroupCount[0], dispatchData.threadGroupCount[1], dispatchData.threadGroupCount[2] ); BarrierUAV( m_uavResources ); } else { simRunning = false; } } } if ( simRunning ) { ++m_simulationStep; } else { break; } } } { PixMarker marker( m_commandList.Get(), L"Sim Per Frame" ); BarrierTransition( m_uavResources, D3D12_RESOURCE_STATE_UNORDERED_ACCESS ); // Do per frame dispatches for ( const DispatchData& dispatchData : m_dispatchList ) { if ( !dispatchData.perStep && dispatchData.pso && dispatchData.threadGroupCount[0] > 0 ) { m_commandList->SetPipelineState( dispatchData.pso.Get() ); m_commandList->Dispatch( dispatchData.threadGroupCount[0], dispatchData.threadGroupCount[1], dispatchData.threadGroupCount[2] ); BarrierUAV( m_uavResources ); } } if ( m_simulationStep > 0 ) { BarrierTransition( m_flightData, D3D12_RESOURCE_STATE_COPY_SOURCE ); m_commandList->CopyResource( m_flightDataRB[m_frameIndex].Get(), m_flightData.resource.Get() ); } BarrierTransition( m_uavResources, D3D12_RESOURCE_STATE_SHADER_RESOURCE ); if ( m_queryHeap && m_frameIndex == 0 ) { m_commandList->EndQuery( m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 1 ); m_commandList->ResolveQueryData( m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, m_queryRB.Get(), 0 ); } } { PixMarker marker( m_commandList.Get(), L"GFX Setup" ); m_commandList->SetGraphicsRootSignature( m_rootSignature.Get() ); m_commandList->SetGraphicsRootConstantBufferView( 1, m_frameConstantBuffer->GetGPUVirtualAddress() + m_frameIndex * RoundUpPow2( sizeof( ShaderShared::FrameConstData ), 256llu ) ); m_commandList->SetGraphicsRootDescriptorTable( 2, m_shaderHeap.GetHeap()->GetGPUDescriptorHandleForHeapStart() ); m_graphViewport = m_viewport; m_graphViewport.Width = m_viewport.Width * 8 / 10; m_graphViewport.TopLeftX = m_viewport.Width - m_graphViewport.Width; m_heatmapViewport = m_viewport; m_heatmapViewport.Width = m_graphViewport.TopLeftX * 0.5f - 1; m_heatmapViewport.Height = m_graphViewport.TopLeftX; // Mark current consts invalid memset( &m_currentDrawConsts, 0xde, sizeof(m_currentDrawConsts) ); // Set default draw constants ShaderShared::DrawConstData drawConsts; drawConsts.graphDataOffset = 0; drawConsts.graphDiscontinuity = static_cast<float>(m_simulationStep / m_telemetryStepSize); drawConsts.graphViewportScale = 5.0f / m_viewport.Width; // NumPoints = 2 / graphViewportScale drawConsts.graphSampleXScale = m_telemetryMaxSamples * drawConsts.graphViewportScale / 2.0f; drawConsts.viewportSize.x = m_graphViewport.Width; drawConsts.viewportSize.y = m_graphViewport.Height; drawConsts.invViewportSize.x = 1.0f / drawConsts.viewportSize.x; drawConsts.invViewportSize.y = 1.0f / drawConsts.viewportSize.y; SetDrawConstants( drawConsts ); SetViewport( m_viewport ); m_commandList->RSSetScissorRects( 1, &m_scissorRect ); // Indicate that the back buffer will be used as a render target. BarrierTransition( m_renderTargets[m_frameIndex].Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET ); D3D12_CPU_DESCRIPTOR_HANDLE rtv = m_rtvHeap.GetCPUHandle( m_frameIndex ); m_commandList->OMSetRenderTargets( 1, &rtv, FALSE, nullptr ); // Record commands. const float clearColor[] = { 0.2f, 0.2f, 0.2f, 1.0f }; m_commandList->ClearRenderTargetView( m_rtvHeap.GetCPUHandle( m_frameIndex ), clearColor, 0, nullptr ); m_font.UpdateLoading(); } { PixMarker marker( m_commandList.Get(), L"Graph Draw" ); SetViewport( m_graphViewport ); ShaderShared::DrawConstData drawConsts = m_currentDrawConsts; if ( m_graphBackground.pso ) { drawConsts.graphSampleXScale = float(m_telemetryMaxSamples - 1); SetDrawConstants( drawConsts ); m_commandList->SetPipelineState( m_graphBackground.pso.Get() ); m_commandList->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); m_commandList->DrawInstanced( 4, 1, 0, 0 ); } float scale = 0.35f; float xpos = -0.99f; float ypos = 0.98f - m_font.GetTopAlign() * scale; for ( GraphList graphIdx : m_graphLayout ) { if (graphIdx != GraphList_Count) { GraphData& graphData = m_graphList[graphIdx]; if ( graphData.pso ) { drawConsts.graphDiscontinuity = static_cast<float>(m_simulationStep / m_telemetryStepSize); drawConsts.graphSampleXScale = m_telemetryMaxSamples * m_currentDrawConsts.graphViewportScale / 2.0f; SetDrawConstants( drawConsts ); m_commandList->SetPipelineState( graphData.pso.Get() ); m_commandList->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_LINESTRIP ); uint32_t vertexCount = static_cast<uint32_t>(ceilf( 2.0f / drawConsts.graphViewportScale )); m_commandList->DrawInstanced( vertexCount, 1, 0, 0 ); wchar_t legend[100]; wcscpy_s( legend, wcschr( graphData.name, '_' ) + 1); *wcsstr( legend, L"_vtx" ) = 0; m_font.DrawText( xpos, ypos, scale, 0.0f, m_graphColours[graphIdx], legend ); ypos -= m_font.GetLineSpacing() * scale; } } } } { PixMarker marker(m_commandList.Get(), L"Heatmap Draw"); D3D12_VIEWPORT hmViewport = m_heatmapViewport; ShaderShared::DrawConstData drawConsts = m_currentDrawConsts; for ( HeatmapList heatmapIdx : m_heatmapLayout ) { if (heatmapIdx != HeatmapList_Count) { HeatmapData& heatmapData = m_heatmapList[heatmapIdx]; if ( heatmapData.pso) { SetViewport( hmViewport ); if ( hmViewport.TopLeftX == m_viewport.TopLeftX ) { hmViewport.TopLeftX += hmViewport.Width + c_xHeatmapSpacing; } else { hmViewport.TopLeftX = m_viewport.TopLeftX; hmViewport.TopLeftY += hmViewport.Height + c_yHeatmapSpacing; } m_commandList->SetPipelineState( heatmapData.pso.Get()); m_commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_commandList->DrawInstanced(3, 1, 0, 0); } if ( m_selectionMarker.pso ) { m_commandList->SetPipelineState( m_selectionMarker.pso.Get() ); m_commandList->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_LINELIST ); m_commandList->DrawInstanced( 16, 1, 0, 0 ); } } } SetViewport( m_viewport ); if ( m_mouseCapture && m_boxDraw.pso ) { drawConsts.invViewportSize.x = 2.0f * m_mouseDragStart.x / m_viewport.Width - 1.0f; drawConsts.invViewportSize.y = 1.0f - 2.0f * m_mouseDragStart.y / m_viewport.Height; drawConsts.viewportSize.x = 2.0f * (m_mouseDragEnd.x - m_mouseDragStart.x) / m_viewport.Width; drawConsts.viewportSize.y = 2.0f * (m_mouseDragStart.y - m_mouseDragEnd.y) / m_viewport.Height; SetDrawConstants( drawConsts ); m_commandList->SetPipelineState( m_boxDraw.pso.Get() ); m_commandList->IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); m_commandList->DrawInstanced( 4, 1, 0, 0 ); } } { PixMarker marker( m_commandList.Get(), L"Heatmap Legend" ); float scale = 0.3f; float xpos = -0.99f; float ypos = 1.0f - 2.0f * ((m_heatmapViewport.Height + 1) / m_viewport.Height) - m_font.GetTopAlign() * scale; for ( HeatmapList heatmapIdx : m_heatmapLayout ) { if ( heatmapIdx != HeatmapList_Count ) { wchar_t legend[100]; wcscpy_s( legend, wcschr( m_heatmapList[heatmapIdx].name, '_' ) + 1 ); *wcsstr( legend, L"_pxl" ) = 0; m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, legend ); if ( xpos <= -0.98f ) { xpos += 2.0f * ((m_heatmapViewport.Width + c_xHeatmapSpacing) / m_viewport.Width); } else { xpos = -0.99f; ypos -= 2.0f * (m_heatmapViewport.Height + c_yHeatmapSpacing) / m_viewport.Height; } } } scale = 0.4f; ypos += 2.0f * m_heatmapViewport.Height / m_viewport.Height; const ShaderShared::AscentParams& ascentParams = m_ascentParams[m_selectedData / m_ascentParams[0].size()][m_selectedData % m_ascentParams[0].size()]; wchar_t statusText[100]; swprintf_s( statusText, L"Pitch Over Angle: %.2f\xb0", acos( ascentParams.cosPitchOverAngle) * c_RadToDegree ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); float spacing = m_font.GetLineSpacing() * scale * 1.1f; ypos -= spacing; swprintf_s( statusText, L"Pitch Over Speed: %.1f m/s", ascentParams.pitchOverSpeed ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); if ( m_simulationStep > 0 ) { std::vector<ShaderShared::FlightData> flightData; flightData.resize( m_simulationThreadCount + 2, ShaderShared::FlightData{} ); UINT8* dataBegin; D3D12_RANGE readRange = { 0 }; if ( ErrorHandler( m_flightDataRB[1 - m_frameIndex]->Map( 0, &readRange, reinterpret_cast<void**>(&dataBegin) ), L"Map Buffer" ) == ErrorResult::CONTINUE ) { memcpy( flightData.data(), dataBegin, flightData.size() * sizeof( ShaderShared::FlightData ) ); m_flightDataRB[1 - m_frameIndex]->Unmap( 0, nullptr ); } if ( m_autoSelectData && m_simulationStep == (m_telemetryMaxSamples * m_telemetryStepSize)) { float bestDelta = FLT_MAX; uint32_t selected = ~0u; for ( uint32_t i = 0; i < m_simulationThreadCount; ++i ) { if ( flightData[i].flightPhase == ShaderShared::c_PhaseMECO && flightData[i].maxQ < 60000.0f ) { float massDelta = flightData[m_simulationThreadCount + 1].minMass - flightData[i].minMass; massDelta = std::max( massDelta, 0.0f ); float targetPe = float(m_missionParams.finalState.r - earthRadius); float targetAp = float(-earthMu / (2 * m_missionParams.finalOrbitalEnergy) - earthRadius) * 2 - targetPe; float Ap = (1 + flightData[i].e) * flightData[i].a - float(earthRadius); float Pe = (1 - flightData[i].e) * flightData[i].a - float(earthRadius); float orbDelta = sqrtf(sqr( Ap - targetAp ) + sqr( Pe - targetPe )); float delta = massDelta + sqr(orbDelta * 0.001f) * 10.0f; if ( delta < bestDelta ) { bestDelta = delta; selected = i; } } } if ( selected < m_simulationThreadCount ) m_selectedData = selected; } ypos -= spacing; swprintf_s( statusText, L"Max Altitude: %.2f km", flightData[m_selectedData].maxAltitude / 1000.0f ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); ypos -= spacing; swprintf_s( statusText, L"Max Surface Speed: %.1f m/s", flightData[m_selectedData].maxSurfSpeed ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); ypos -= spacing; swprintf_s( statusText, L"Max Q: %.2f kPa", flightData[m_selectedData].maxQ / 1000.0f ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); ypos -= spacing; swprintf_s( statusText, L"Max g: %.2f", flightData[m_selectedData].maxAccel / earthg0 ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); ypos -= spacing; swprintf_s( statusText, L"Min Mass: %.3f tonnes", flightData[m_selectedData].minMass / 1000.0f ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); // Calc delta v for current stage uint32_t stage = flightData[m_selectedData].stage; float deltaV = (float(earthg0) * m_missionParams.stage[stage].IspVac) * logf( flightData[m_selectedData].minMass / m_missionParams.stage[stage].dryMass ); // Add on delta v for remaining stages for ( uint32_t s = stage + 1; s < m_missionParams.stageCount; ++s ) { deltaV += (float(earthg0) * m_missionParams.stage[s].IspVac) * logf( m_missionParams.stage[s].wetMass / m_missionParams.stage[s].dryMass ); } // Calc original delta V float padDeltaV = 0.0f; for ( uint32_t s = 0; s < m_missionParams.stageCount; ++s ) { padDeltaV += (float( earthg0 ) * m_missionParams.stage[s].IspVac) * logf( m_missionParams.stage[s].wetMass / m_missionParams.stage[s].dryMass ); } ypos -= spacing; swprintf_s( statusText, L"Delta V: %.1f / %.1f m/s", deltaV, padDeltaV ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); const wchar_t* flightPhases[] = { L"Liftoff", L"Pitch Over", L"Aero Flight", L"Guidance Ready", L"Guidance Active", L"MECO" }; ypos -= spacing; swprintf_s( statusText, L"Final Flight Phase: %s", flightPhases[flightData[m_selectedData].flightPhase] ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); ypos -= spacing; swprintf_s( statusText, L"Apoapsis: %.3f km", ((1.0f + flightData[m_selectedData].e) * flightData[m_selectedData].a - 6371000.0f) / 1000.0f); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); ypos -= spacing; swprintf_s( statusText, L"Periapsis: %.3f km", ((1.0f - flightData[m_selectedData].e) * flightData[m_selectedData].a - 6371000.0f) / 1000.0f ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); for ( uint32_t s = 0; s < m_missionParams.stageCount; ++s ) { ypos -= spacing; swprintf_s( statusText, L"Stage %d Burn: %.1f s", s, flightData[m_selectedData].stageBurnTime[s] ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); } } } { PixMarker marker( m_commandList.Get(), L"Status Text" ); float scale = 0.44f; wchar_t statusText[100]; swprintf_s( statusText, L"Simulation Time: %.2fs (steps=%u, sim=%.2f ms)", m_simulationStep * m_simulationStepSize, m_simStepsPerFrame, m_simGpuTime.getAverage() ); float xpos = 0.98f - m_font.CalcTextLength( statusText ) * scale; float ypos = 0.98f - m_font.GetTopAlign() * scale; m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); float time = GetTimestampMilliSec(); if ( m_lastFrame > 0.0f ) { m_frameTime = m_frameTime * 0.9f + (time - m_lastFrame) * 0.1f; } m_lastFrame = time; ypos -= m_font.GetLineSpacing() * scale; swprintf_s( statusText, L"Frame Rate: %.1f", 1000.0f / m_frameTime ); m_font.DrawText( xpos, ypos, scale, 0.0f, 0xffcfcfcf, statusText ); } DrawTrackedFileErrors(); // Indicate that the back buffer will now be used to present. BarrierTransition( m_renderTargets[m_frameIndex].Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT ); m_commandList->Close(); // Execute the command list. ID3D12CommandList* ppCommandLists[] = { m_commandList.Get() }; m_commandQueue->ExecuteCommandLists( _countof( ppCommandLists ), ppCommandLists ); // Present the frame. m_swapChain->Present( 1, 0 ); #ifdef _DEBUG if ( m_graphicsAnalysis && m_simulationStep == (m_telemetryMaxSamples * m_telemetryStepSize) && m_dispatchList[0].pso ) { m_graphicsAnalysis->EndCapture(); } #endif // Schedule a Signal command in the queue. m_commandQueue->Signal( m_fence.Get(), currentFenceValue ); // Update the frame index. m_frameIndex = m_swapChain->GetCurrentBackBufferIndex(); // If the next frame is not ready to be rendered yet, wait until it is ready. if ( m_fence->GetCompletedValue() < m_fenceValues[m_frameIndex] ) { m_fence->SetEventOnCompletion( m_fenceValues[m_frameIndex], m_fenceEvent ); WaitForSingleObjectEx( m_fenceEvent, INFINITE, FALSE ); } // Set the fence value for the next frame. m_fenceValues[m_frameIndex] = currentFenceValue + 1; // Update frame step speed if ( m_simulationStep > 0 && m_simulationStep < (m_telemetryMaxSamples * m_telemetryStepSize) && m_queryHeap && m_frameIndex == 1 ) { int64_t simulationTime = -1; void* dataBegin; if ( ErrorHandler( m_queryRB->Map( 0, nullptr, &dataBegin ), L"Map Buffer" ) == ErrorResult::CONTINUE ) { const int64_t* timestamp = static_cast<const int64_t*>(dataBegin); simulationTime = timestamp[1] - timestamp[0]; D3D12_RANGE writeRange = { 0 }; m_queryRB->Unmap( 0, &writeRange ); } uint64_t gpuFreq = 0; if ( simulationTime > 0 && m_commandQueue->GetTimestampFrequency( &gpuFreq ) == S_OK ) { double simTimeMS = 1000.0 * simulationTime / gpuFreq; if ( m_simGpuTime.getAverage() == 0.0f ) m_simGpuTime.reset( static_cast<float>(simTimeMS) ); else m_simGpuTime.addData( static_cast<float>(simTimeMS) ); if ( m_tweakTimer > 0 ) --m_tweakTimer; // Only update when the timings are fairly stable. if ( m_simGpuTime.getAverage() > m_simGpuTime.getStdDeviation() ) { float maxTime = m_simGpuTime.getAverage() + m_simGpuTime.getStdDeviation(); uint32_t newSteps = 0; if ( maxTime < 2.0f ) { // Less than 5 ms, increase rapidly newSteps = m_simStepsPerFrame * 5 / 4; newSteps = std::max(newSteps, m_simStepsPerFrame + 1); } else if ( !m_tweakTimer && maxTime < 8.0f ) { // Less than 10 ms, increase slowly newSteps = m_simStepsPerFrame * 16 / 15; newSteps = std::max(newSteps, m_simStepsPerFrame + 1); } else if ( maxTime > 16.0f ) { // Over 20 ms, reduce rapidly newSteps = m_simStepsPerFrame * 3 / 4; newSteps = std::min(newSteps, m_simStepsPerFrame - 1); } else if ( !m_tweakTimer && maxTime > 12.0f ) { // Over 15 ms, reduce slowly newSteps = m_simStepsPerFrame * 15 / 16; newSteps = std::min(newSteps, m_simStepsPerFrame - 1); } if (newSteps) { m_simStepsPerFrame = newSteps; m_tweakTimer = 10; } } if ( m_simStepsPerFrame > 1000 ) { m_simStepsPerFrame = ((m_simStepsPerFrame + 50) / 100) * 100; } else if ( m_simStepsPerFrame > 500 ) { m_simStepsPerFrame = ((m_simStepsPerFrame + 25) / 50) * 50; } else if ( m_simStepsPerFrame > 100 ) { m_simStepsPerFrame = ((m_simStepsPerFrame + 5) / 10) * 10; } else if ( m_simStepsPerFrame > 50 ) { m_simStepsPerFrame = ((m_simStepsPerFrame + 2) / 5) * 5; } m_simStepsPerFrame = std::min( m_simStepsPerFrame, m_telemetryMaxSamples / 10 ); m_simStepsPerFrame = std::max( m_simStepsPerFrame, 10u ); } } } //------------------------------------------------------------------------------------------------ void RocketSim::Shutdown() { // Ensure that the GPU is no longer referencing resources that are about to be // cleaned up by the destructor. WaitForGPU(); CloseHandle( m_fenceEvent ); } //------------------------------------------------------------------------------------------------ float RocketSim::xPositionToDataIndex(int x) { x -= int(m_heatmapViewport.TopLeftX + 0.5); if ( x < 0 || x >= int( m_heatmapViewport.Width + c_xHeatmapSpacing ) * 2 ) return -1.0f; x %= int( m_heatmapViewport.Width + c_xHeatmapSpacing ); return x * (m_simulationThreadWidth - 1) / (m_heatmapViewport.Width - 1); } float RocketSim::yPositionToDataIndex(int y) { y -= int( m_heatmapViewport.TopLeftY + 0.5 ); if ( y < 0 || y >= int( m_heatmapViewport.Height + c_yHeatmapSpacing ) * 2 ) return -1.0f; y %= int( m_heatmapViewport.Height + c_yHeatmapSpacing ); return y * (m_simulationThreadHeight - 1) / (m_heatmapViewport.Height - 1); } //------------------------------------------------------------------------------------------------ void RocketSim::MouseClicked( int x, int y, bool shiftPressed, bool ) { if ( shiftPressed || m_mouseCapture ) { if ( !m_mouseCapture && DragDetect( m_hwnd, POINT{ x,y } ) ) { m_mouseDragStart.x = x; m_mouseDragStart.y = y; SetCapture( m_hwnd ); m_mouseCapture = true; } if ( m_mouseCapture ) { m_mouseDragEnd.x = x; m_mouseDragEnd.y = y; } return; } x = int( xPositionToDataIndex( x ) + 0.5f ); y = int( yPositionToDataIndex( y ) + 0.5f ); if ( x >= 0 && x < int( m_simulationThreadWidth ) && y >= 0 && y < int( m_simulationThreadHeight ) ) { m_selectedData = x + (m_simulationThreadHeight - y - 1) * m_simulationThreadWidth; m_autoSelectData = false; } } void RocketSim::MouseReleased( int x, int y, bool captureLost ) { if ( m_mouseCapture && !captureLost ) { ReleaseCapture(); m_mouseDragEnd.x = x; m_mouseDragEnd.y = y; float xStart = xPositionToDataIndex( m_mouseDragStart.x ); float yStart = yPositionToDataIndex( m_mouseDragStart.y ); if ( xStart > -1.0f && xStart <= m_simulationThreadWidth && yStart > -1.0f && yStart <= m_simulationThreadHeight ) { int xMax = m_simulationThreadWidth - 1; int yMax = m_simulationThreadHeight - 1; xStart = std::min( std::max( xStart, 0.0f ), float(xMax) ); yStart = std::min( std::max( yStart, 0.0f ), float(yMax) ); float f = xStart - floorf( xStart ); float minAngle = asin( m_ascentParams[0][int(xStart)].sinPitchOverAngle * (1 - f) + m_ascentParams[0][std::min(int(xStart) + 1, xMax)].sinPitchOverAngle * f ); f = yStart - floorf( yStart ); float minSpeed = m_ascentParams[m_simulationThreadHeight - 1 - int(yStart)][0].pitchOverSpeed * (1 - f) + m_ascentParams[std::max( int( m_simulationThreadHeight ) - 1 - (int(yStart) + 1), 0)][0].pitchOverSpeed * f; float xEnd = xPositionToDataIndex( m_mouseDragEnd.x ); xEnd = std::min( std::max( xEnd, 0.0f ), m_simulationThreadWidth - 1.0f ); float yEnd = yPositionToDataIndex( m_mouseDragEnd.y ); yEnd = std::min( std::max( yEnd, 0.0f ), m_simulationThreadHeight - 1.0f ); f = xEnd - floorf( xEnd ); float maxAngle = asin( m_ascentParams[0][int(xEnd)].sinPitchOverAngle * (1 - f) + m_ascentParams[0][std::min(int(xEnd) + 1, xMax)].sinPitchOverAngle * f ); f = yEnd - floorf( yEnd ); float maxSpeed = m_ascentParams[m_simulationThreadHeight - 1 - int(yEnd)][0].pitchOverSpeed * (1 - f) + m_ascentParams[std::max( int(m_simulationThreadHeight) - 1 - (int(yEnd) + 1), 0)][0].pitchOverSpeed * f; if ( maxAngle < minAngle ) std::swap( minAngle, maxAngle ); if ( maxSpeed < minSpeed ) std::swap( minSpeed, maxSpeed ); float angleStep = (maxAngle - minAngle) / float( m_ascentParams[0].size() - 1 ); float speedStep = (maxSpeed - minSpeed) / float( m_ascentParams.size() - 1 ); for ( uint32_t angle = 0; angle < m_ascentParams[0].size(); ++angle ) { float a = minAngle + angle * angleStep; m_ascentParams[0][angle].pitchOverSpeed = minSpeed; m_ascentParams[0][angle].sinPitchOverAngle = sin( a ); m_ascentParams[0][angle].cosPitchOverAngle = cos( a ); m_ascentParams[0][angle].sinAimAngle = sin( a + c_DegreeToRad ); m_ascentParams[0][angle].cosAimAngle = cos( a + c_DegreeToRad ); } for ( uint32_t speed = 1; speed < m_ascentParams.size(); ++speed ) { float pitchOverSpeed = minSpeed + speed * speedStep; for ( uint32_t angle = 0; angle < m_ascentParams[0].size(); ++angle ) { m_ascentParams[speed][angle].pitchOverSpeed = pitchOverSpeed; m_ascentParams[speed][angle].sinPitchOverAngle = m_ascentParams[speed - 1][angle].sinPitchOverAngle; m_ascentParams[speed][angle].cosPitchOverAngle = m_ascentParams[speed - 1][angle].cosPitchOverAngle; m_ascentParams[speed][angle].sinAimAngle = m_ascentParams[speed - 1][angle].sinAimAngle; m_ascentParams[speed][angle].cosAimAngle = m_ascentParams[speed - 1][angle].cosAimAngle; } } ResourceData* resourceData = &m_ascentParamsBuffer; CreateStructuredBuffer( L"Zoomed ascent params", resourceData->resource, resourceData->desc, m_ascentParams.data(), sizeof( ShaderShared::AscentParams ), static_cast<uint32_t>(m_ascentParams.size() * m_ascentParams[0].size()) ); // Restart sim m_simulationStep = 0; m_autoSelectData = true; } } m_mouseCapture = false; } //------------------------------------------------------------------------------------------------ void RocketSim::RMouseClicked( int x, int y, bool, bool ) { x = int( xPositionToDataIndex( x ) + 0.5f ); y = int( yPositionToDataIndex( y ) + 0.5f ); if ( x >= 0 && x < int( m_simulationThreadWidth ) && y >= 0 && y < int( m_simulationThreadHeight ) ) { for ( TrackedFile& tf : m_trackedFiles ) { if ( tf.updateCallback == &RocketSim::ReloadAscentParams ) { (this->*tf.updateCallback)(tf); } } } } //------------------------------------------------------------------------------------------------ // Forward declarations of functions included in this code module: ATOM MyRegisterClass( HINSTANCE hInstance ); BOOL InitInstance( HINSTANCE, int ); LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ); INT_PTR CALLBACK About( HWND, UINT, WPARAM, LPARAM ); //------------------------------------------------------------------------------------------------ int APIENTRY wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow ) { UNREFERENCED_PARAMETER( hPrevInstance ); UNREFERENCED_PARAMETER( lpCmdLine ); // Initialize global strings LoadStringW( hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING ); LoadStringW( hInstance, IDC_ROCKETSIM, szWindowClass, MAX_LOADSTRING ); MyRegisterClass( hInstance ); // Perform application initialization: if ( !InitInstance( hInstance, nCmdShow ) ) { return FALSE; } MSG msg = {}; while ( msg.message != WM_QUIT ) { // Process any messages in the queue. if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } s_RocketSim.Shutdown(); return (int)msg.wParam; } //------------------------------------------------------------------------------------------------ // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass( HINSTANCE hInstance ) { WNDCLASSEXW wcex; wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon( hInstance, MAKEINTRESOURCE( IDI_ROCKETSIM ) ); wcex.hCursor = LoadCursor( nullptr, IDC_ARROW ); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCEW( IDC_ROCKETSIM ); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon( wcex.hInstance, MAKEINTRESOURCE( IDI_SMALL ) ); return RegisterClassExW( &wcex ); } //------------------------------------------------------------------------------------------------ // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance( HINSTANCE hInstance, int nCmdShow ) { RECT workArea; SystemParametersInfo( SPI_GETWORKAREA, 0, &workArea, 0 ); RECT windowRect; UINT width = (workArea.right - workArea.left) & ~3; UINT height = 0; do { width -= 4; while ( width > 0 ) { height = width * 9 / 16; if ( (height & 3) == 0 ) { break; } width -= 4; } windowRect.left = 0; windowRect.top = 0; windowRect.right = width; windowRect.bottom = height; AdjustWindowRect( &windowRect, WS_OVERLAPPEDWINDOW, FALSE ); } while ( (windowRect.right - windowRect.left) > (workArea.right - workArea.left) || (windowRect.bottom - windowRect.top) > (workArea.bottom - workArea.top) ); width = windowRect.right - windowRect.left; height = windowRect.bottom - windowRect.top; UINT left = ((workArea.right - workArea.left) - width) / 2; UINT top = ((workArea.bottom - workArea.top) - height) / 2; HWND hWnd = CreateWindowW( szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, left, top, width, height, nullptr, nullptr, hInstance, nullptr ); if ( !hWnd ) { return FALSE; } s_RocketSim.InitRenderer( hWnd ); s_RocketSim.LoadBaseResources(); ShowWindow( hWnd, nCmdShow ); return TRUE; } //------------------------------------------------------------------------------------------------ // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { switch ( message ) { case WM_COMMAND: { int wmId = LOWORD( wParam ); // Parse the menu selections: switch ( wmId ) { case IDM_ABOUT: DialogBox( GetModuleHandle( nullptr ), MAKEINTRESOURCE( IDD_ABOUTBOX ), hWnd, About ); break; case IDM_EXIT: DestroyWindow( hWnd ); break; default: return DefWindowProc( hWnd, message, wParam, lParam ); } } break; case WM_PAINT: s_RocketSim.RenderFrame(); return 0; case WM_LBUTTONDOWN: s_RocketSim.MouseClicked( GET_X_LPARAM( lParam ), GET_Y_LPARAM( lParam ), (wParam & MK_SHIFT) != 0, (wParam & MK_CONTROL) != 0 ); return 0; case WM_LBUTTONUP: s_RocketSim.MouseReleased( GET_X_LPARAM( lParam ), GET_Y_LPARAM( lParam ), false ); return 0; case WM_RBUTTONUP: s_RocketSim.RMouseClicked( GET_X_LPARAM( lParam ), GET_Y_LPARAM( lParam ), (wParam & MK_SHIFT) != 0, (wParam & MK_CONTROL) != 0 ); return 0; case WM_MOUSEMOVE: if ( wParam & MK_LBUTTON ) s_RocketSim.MouseClicked( GET_X_LPARAM( lParam ), GET_Y_LPARAM( lParam ), (wParam & MK_SHIFT) != 0, (wParam & MK_CONTROL) != 0 ); return 0; case WM_CAPTURECHANGED: s_RocketSim.MouseReleased( GET_X_LPARAM( lParam ), GET_Y_LPARAM( lParam ), true ); break; case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, message, wParam, lParam ); } return 0; } //------------------------------------------------------------------------------------------------ // Message handler for about box. INT_PTR CALLBACK About( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam ) { UNREFERENCED_PARAMETER( lParam ); switch ( message ) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if ( LOWORD( wParam ) == IDOK || LOWORD( wParam ) == IDCANCEL ) { EndDialog( hDlg, LOWORD( wParam ) ); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
38.994441
238
0.610525
[ "render", "object", "vector" ]
b5800dda2ad8569714d5bca617eaa7fde7657a28
5,183
cpp
C++
src/ui_text.cpp
Tizzio/EngineT
b9975634bbfa4ac0d5729928bb50a71e977344e0
[ "MIT" ]
1
2020-09-25T12:38:03.000Z
2020-09-25T12:38:03.000Z
src/ui_text.cpp
Tizzio/EngineT
b9975634bbfa4ac0d5729928bb50a71e977344e0
[ "MIT" ]
null
null
null
src/ui_text.cpp
Tizzio/EngineT
b9975634bbfa4ac0d5729928bb50a71e977344e0
[ "MIT" ]
null
null
null
#include "ui_text.h" #include "style.h" #include "font.h" #include "texture.h" #include "utils.h" namespace EngineT { Text::Text(wstring text, Style* style) { this->name = "text"; this->style = style; if(text.length() <= 0) return; GenerateBuffers(); Texture* tex = style->font->texture; SetText(text); UpdateBuffers(); } void Text::SetText(wstring text) { int count = 0; for(char32_t c : text) { //if character exists if(c > 0 && c < style->font->chars.size()) if(style->font->chars[c] != nullptr) { count++; } } vertices.reserve(count * 4); indices.reserve(count * 6); //style properties int xoffset = style->xoffset; int yoffset = style->yoffset; int spacing = style->spacing; int spaceWidth = style->spaceWidth; int lineHeight = style->lineHeight; int xpos = 0; int ypos = 0; uint idx = 0; vec4 color = style->color; bool openCommand = false; string command; for(char32_t c : text) { //check newline if(openCommand) { if(c == ']') { openCommand = false; //execute command if(command[0] == '#') { if(command.length() == 7) { color = Utils::HexColorToVec4(command); } else { color = style->color; } } command = ""; } else { command.push_back((char)c); } continue; } else { if(c == '[') { openCommand = true; continue; } } //check newline character if(c == 10 || c == 13) { xpos = 0; ypos += style->font->maxHeight + lineHeight; } //check space else if(c == ' ') xpos += spaceWidth; Font::Char* fc = nullptr; if(c > 0 && c < style->font->chars.size()) fc = style->font->chars[c]; //if character exists if(fc != nullptr) { vertices.insert(vertices.end(), { Vertex(vec2(xpos + fc->xoffset, ypos + fc->yoffset), vec2(fc->uvX1, fc->uvY1), color), Vertex(vec2(xpos + fc->width + fc->xoffset, ypos + fc->yoffset), vec2(fc->uvX2, fc->uvY1), color), Vertex(vec2(xpos + fc->xoffset, ypos + fc->height + fc->yoffset), vec2(fc->uvX1, fc->uvY2), color), Vertex(vec2(xpos + fc->width + fc->xoffset, ypos + fc->height + fc->yoffset), vec2(fc->uvX2, fc->uvY2), color) }); indices.insert(indices.end(), { idx + 0, idx + 1, idx + 2, idx + 2, idx + 3, idx + 1 }); idx += 4; xpos += (int)fc->width + spacing; } } } void Text::Draw() { glBindVertexArray(vao); if(style->font->texture != nullptr) style->font->texture->Bind(GL_TEXTURE0); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); } void Text::GenerateBuffers() { //Vertex array object glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo_v); glGenBuffers(1, &vbo_i); glBindVertexArray(vao); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_i); glBindBuffer(GL_ARRAY_BUFFER, vbo_v); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(class Vertex, pos)); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(class Vertex, uv)); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(class Vertex, col)); glBindVertexArray(0); } void Text::UpdateBuffers() { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_i); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint)* indices.size(), &indices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, vbo_v); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)* vertices.size(), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } }
28.955307
131
0.450897
[ "object" ]
b58238a1a258e85911a78274f96d33d3774a7609
1,256
cpp
C++
aws-cpp-sdk-gamelift/source/model/UpdateAliasRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-gamelift/source/model/UpdateAliasRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-gamelift/source/model/UpdateAliasRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/gamelift/model/UpdateAliasRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::GameLift::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateAliasRequest::UpdateAliasRequest() : m_aliasIdHasBeenSet(false), m_nameHasBeenSet(false), m_descriptionHasBeenSet(false), m_routingStrategyHasBeenSet(false) { } Aws::String UpdateAliasRequest::SerializePayload() const { JsonValue payload; if(m_aliasIdHasBeenSet) { payload.WithString("AliasId", m_aliasId); } if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } if(m_descriptionHasBeenSet) { payload.WithString("Description", m_description); } if(m_routingStrategyHasBeenSet) { payload.WithObject("RoutingStrategy", m_routingStrategy.Jsonize()); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateAliasRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "GameLift.UpdateAlias")); return headers; }
19.323077
86
0.738057
[ "model" ]
b5932fee10111d1abaad10089c47e919d11664d0
2,551
hpp
C++
source/cppx-core-language/x-propagation/x-unwrapping.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
3
2020-05-24T16:29:42.000Z
2021-09-10T13:33:15.000Z
source/cppx-core-language/x-propagation/x-unwrapping.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
source/cppx-core-language/x-propagation/x-unwrapping.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
#pragma once // Source encoding: UTF-8 with BOM (π is a lowercase Greek "pi"). #include <cppx-core-language/syntax/string-expressions/basic-string-assembly.hpp> #include <cppx-core-language/syntax/collection-util.hpp> // cppx::is_empty #include <cppx-core-language/syntax/declarations.hpp> // CPPX_USE_STD #include <cppx-core-language/text/C_str_.hpp> // cppx::C_str #include <exception> // std::(exception, rethrow_exception) #include <functional> // std::function #include <utility> // std::move #include <vector> // std::vector namespace cppx::definitions_ { CPPX_USE_STD( exception, function, move, rethrow_if_nested, string, vector ); inline void for_each_description_line_from( const exception& x, const function<void( const C_str )>& f ) { f( x.what() ); try { rethrow_if_nested( x ); } catch( const exception& rx ) { for_each_description_line_from( rx, f ); } catch( const C_str sz ) { f( sz ); } catch( const int code ) { const auto s = "<integer value "s << code << ">"; f( s.c_str() ); } catch( ... ) { f( "<a non-standard exception>" ); } } inline auto to_string( const exception& x ) -> string { string result; const auto add_it = [&]( const C_str s ) -> void { const bool is_first = is_empty( result ); result << (is_first? "• " : "\n• because ") << s; }; for_each_description_line_from( x, add_it ); return result; } inline auto description_lines_from( const exception& x ) -> vector<string> { vector<string> result; const auto add_it = [&]( const C_str s ) -> void { result.push_back( s ); }; for_each_description_line_from( x, add_it ); return result; } namespace x_propagation_exports { CPPX_USE_FROM_NAMESPACE( definitions_, for_each_description_line_from, to_string, description_lines_from ); } // namespace x_propagation_exports } // namespace cppx::definitions_ namespace cppx::x_propagation { using namespace cppx::definitions_::x_propagation_exports; } namespace cppx { using namespace cppx::definitions_::x_propagation_exports; }
32.705128
98
0.558996
[ "vector" ]
b59693b630f1ecb43f6ca1afb0c8eaae9ae9ff12
9,004
cpp
C++
src/Services/StatusReportService.cpp
loonwerks/case-ta6-experimental-platform-OpenUxAS
2db8b04b12f34d4c43119740cd665be554e85b95
[ "NASA-1.3" ]
88
2017-08-24T07:02:01.000Z
2022-03-18T04:34:17.000Z
src/Services/StatusReportService.cpp
loonwerks/case-ta6-experimental-platform-OpenUxAS
2db8b04b12f34d4c43119740cd665be554e85b95
[ "NASA-1.3" ]
46
2017-06-08T18:18:08.000Z
2022-03-15T18:24:43.000Z
src/Services/StatusReportService.cpp
loonwerks/case-ta6-experimental-platform-OpenUxAS
2db8b04b12f34d4c43119740cd665be554e85b95
[ "NASA-1.3" ]
53
2017-06-22T14:48:05.000Z
2022-02-15T16:59:38.000Z
// =============================================================================== // Authors: AFRL/RQQA // Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division // // Copyright (c) 2017 Government of the United State of America, as represented by // the Secretary of the Air Force. No copyright is claimed in the United States under // Title 17, U.S. Code. All Other Rights Reserved. // =============================================================================== /* * File: StatusReportService.cpp * Author: derek * * Created on Jan 30, 2018 * * <Service Type="StatusReportService" VehicleID="100" * ReportPeriod_ms="5000" * StaleStateTime_ms="5000" * KeepAliveExpiration_ms="7000" /> * */ #include "StatusReportService.h" #include "UxAS_TimerManager.h" #include "uxas/messages/uxnative/EntityJoin.h" #include "uxas/messages/uxnative/EntityExit.h" #include "uxas/messages/uxnative/AutopilotKeepAlive.h" #include "afrl/cmasi/EntityState.h" #include "afrl/cmasi/EntityStateDescendants.h" namespace uxas // uxas:: { namespace service // uxas::service:: { // this entry registers the service in the service creation registry StatusReportService::ServiceBase::CreationRegistrar<StatusReportService> StatusReportService::s_registrar(StatusReportService::s_registryServiceTypeNames()); // service constructor StatusReportService::StatusReportService() : ServiceBase(StatusReportService::s_typeName(), StatusReportService::s_directoryName()) { m_report.setValidState(false); m_report.setValidAuthorization(false); m_report.setSpeedAuthorization(false); m_report.setGimbalAuthorization(false); }; // service destructor StatusReportService::~StatusReportService() { // destroy report timer uint64_t delayTime_ms{10}; if (m_reportTimerId && !uxas::common::TimerManager::getInstance().destroyTimer(m_reportTimerId, delayTime_ms)) { UXAS_LOG_WARN("StatusReportService::~StatusReportService failed to destroy report timer " "(m_reportTimerId) with timer ID ", m_reportTimerId, " within ", delayTime_ms, " millisecond timeout"); } // destroy keep alive timer if (m_keepAliveTimerId && !uxas::common::TimerManager::getInstance().destroyTimer(m_keepAliveTimerId, delayTime_ms)) { UXAS_LOG_WARN("StatusReportService::~StatusReportService failed to destroy keep alive gap timer " "(m_keepAliveTimerId) with timer ID ", m_keepAliveTimerId, " within ", delayTime_ms, " millisecond timeout"); } // destroy stale state timer if (m_staleStateTimerId && !uxas::common::TimerManager::getInstance().destroyTimer(m_staleStateTimerId, delayTime_ms)) { UXAS_LOG_WARN("StatusReportService::~StatusReportService failed to destroy keep alive gap timer " "(m_staleStateTimerId) with timer ID ", m_staleStateTimerId, " within ", delayTime_ms, " millisecond timeout"); } }; bool StatusReportService::configure(const pugi::xml_node& ndComponent) { // default to entity identified in top-level configuration m_vehicleId = ndComponent.attribute("VehicleID").as_int64(m_entityId); m_report.setVehicleID(m_vehicleId); // make sure report period is something sane (e.g. at most 10Hz) m_reportPeriod_ms = ndComponent.attribute("ReportPeriod_ms").as_uint(m_reportPeriod_ms); if(m_reportPeriod_ms < 100) m_reportPeriod_ms = 100; // make sure state timeout is something sane (e.g. at most 100Hz) m_staleStateTime_ms = ndComponent.attribute("StaleStateTime_ms").as_uint(m_staleStateTime_ms); if(m_staleStateTime_ms < 10) m_staleStateTime_ms = 10; // make sure keep-alive timeout is something sane (e.g. at least 1 sec) m_keepAliveExpirationTime_ms = ndComponent.attribute("KeepAliveExpiration_ms").as_uint(m_keepAliveExpirationTime_ms); if(m_keepAliveExpirationTime_ms < 1000) m_keepAliveExpirationTime_ms = 1000; // subscribe to join, exit, and keep-alive messages addSubscriptionAddress(uxas::messages::uxnative::EntityJoin::Subscription); addSubscriptionAddress(uxas::messages::uxnative::EntityExit::Subscription); addSubscriptionAddress(uxas::messages::uxnative::AutopilotKeepAlive::Subscription); // track all entity states addSubscriptionAddress(afrl::cmasi::EntityState::Subscription); std::vector< std::string > childstates = afrl::cmasi::EntityStateDescendants(); for(auto child : childstates) addSubscriptionAddress(child); return (true); } bool StatusReportService::initialize() { // create report timer m_reportTimerId = uxas::common::TimerManager::getInstance().createTimer( std::bind(&StatusReportService::OnReportTimeout, this), "StatusReportService::OnReportTimeout"); // create keep alive timer m_keepAliveTimerId = uxas::common::TimerManager::getInstance().createTimer( std::bind(&StatusReportService::OnKeepAliveTimeout, this), "StatusReportService::OnKeepAliveTimeout"); // create stale state timer m_staleStateTimerId = uxas::common::TimerManager::getInstance().createTimer( std::bind(&StatusReportService::OnStaleStateTimeout, this), "StatusReportService::OnStaleStateTimeout"); return (true); } bool StatusReportService::start() { // start periodic reporting timer uxas::common::TimerManager::getInstance().startPeriodicTimer(m_reportTimerId, m_reportPeriod_ms, m_reportPeriod_ms); return (true); } bool StatusReportService::processReceivedLmcpMessage(std::unique_ptr<uxas::communications::data::LmcpMessage> receivedLmcpMessage) { // lock during report update std::unique_lock<std::mutex> lock(m_mutex); auto entityState = std::dynamic_pointer_cast<afrl::cmasi::EntityState> (receivedLmcpMessage->m_object); if(entityState && m_vehicleId == entityState->getID()) { m_report.setVehicleTime(entityState->getTime()); m_report.getCurrentTaskList() = entityState->getAssociatedTasks(); m_report.setValidState(true); // reset timer to detect stale state (fresh now, timeout indicates stale) uxas::common::TimerManager::getInstance().startSingleShotTimer(m_staleStateTimerId, m_staleStateTime_ms); if(!uxas::common::TimerManager::getInstance().isTimerActive(m_reportTimerId)) { // start periodic reporting timer uxas::common::TimerManager::getInstance().startPeriodicTimer(m_reportTimerId, m_reportPeriod_ms, m_reportPeriod_ms); } } else if(uxas::messages::uxnative::isEntityJoin(receivedLmcpMessage->m_object)) { auto joinmsg = std::static_pointer_cast<uxas::messages::uxnative::EntityJoin>(receivedLmcpMessage->m_object); m_connections.insert(joinmsg->getEntityID()); m_report.getConnectedEntities().clear(); m_report.getConnectedEntities().insert(m_report.getConnectedEntities().end(), m_connections.begin(), m_connections.end()); } else if(uxas::messages::uxnative::isEntityExit(receivedLmcpMessage->m_object)) { auto exitmsg = std::static_pointer_cast<uxas::messages::uxnative::EntityExit>(receivedLmcpMessage->m_object); m_connections.erase(exitmsg->getEntityID()); m_report.getConnectedEntities().clear(); m_report.getConnectedEntities().insert(m_report.getConnectedEntities().end(), m_connections.begin(), m_connections.end()); } else if (uxas::messages::uxnative::isAutopilotKeepAlive(receivedLmcpMessage->m_object.get())) { auto keepAlive = std::static_pointer_cast<uxas::messages::uxnative::AutopilotKeepAlive>(receivedLmcpMessage->m_object); m_report.setValidAuthorization(keepAlive->getAutopilotEnabled()); m_report.setSpeedAuthorization(keepAlive->getSpeedAuthorized()); m_report.setGimbalAuthorization(keepAlive->getGimbalEnabled()); // reset timer to determine loss of keep-alive stream uxas::common::TimerManager::getInstance().startSingleShotTimer(m_keepAliveTimerId, m_keepAliveExpirationTime_ms); } return (false); // always return false unless terminating } void StatusReportService::OnReportTimeout() { std::unique_lock<std::mutex> lock(m_mutex); std::shared_ptr<uxas::messages::uxnative::OnboardStatusReport> sendReport(m_report.clone()); lock.unlock(); sendSharedLmcpObjectBroadcastMessage(sendReport); } void StatusReportService::OnKeepAliveTimeout() { std::unique_lock<std::mutex> lock(m_mutex); m_report.setValidAuthorization(false); m_report.setSpeedAuthorization(false); m_report.setGimbalAuthorization(false); } void StatusReportService::OnStaleStateTimeout() { std::unique_lock<std::mutex> lock(m_mutex); m_report.setValidState(false); } }; //namespace service }; //namespace uxas
43.288462
130
0.712017
[ "vector" ]
b59ec8ff78e4187b96eb9be10d34ce545cd6a42b
15,460
cpp
C++
structured/StorageSummaryInformation.cpp
djp952/storage-legacy
0aa77be62e4fd84feab4781d2e849692d80ccf99
[ "MIT" ]
null
null
null
structured/StorageSummaryInformation.cpp
djp952/storage-legacy
0aa77be62e4fd84feab4781d2e849692d80ccf99
[ "MIT" ]
null
null
null
structured/StorageSummaryInformation.cpp
djp952/storage-legacy
0aa77be62e4fd84feab4781d2e849692d80ccf99
[ "MIT" ]
1
2020-03-07T17:41:52.000Z
2020-03-07T17:41:52.000Z
//--------------------------------------------------------------------------- // Copyright (c) 2016 Michael G. Brehm // // 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 "stdafx.h" // Include project pre-compiled headers #include "StorageSummaryInformation.h" // Include StorageSummaryInformation decls #include <initguid.h> // Include DEFINE_GUID support #pragma warning(push, 4) // Enable maximum compiler warnings BEGIN_ROOT_NAMESPACE(zuki::storage) //--------------------------------------------------------------------------- // Macros //--------------------------------------------------------------------------- // FMTID_SUMMARYINFORMATION {F29F85E0-4FF9-1068-AB91-08002B27B3D9} // // Replaces the real FMTID_SummaryInformation GUID so that this code can // be compiled in /clr:pure mode without unresolved external errors DEFINE_GUID(FMTID_SUMMARYINFORMATION, 0xf29f85e0L, 0x4ff9, 0x1068, 0xab, 0x91, 0x08, 0x00, 0x2b, 0x27, 0xb3, 0xd9); //--------------------------------------------------------------------------- // StorageSummaryInformation Constructor (internal) // // Arguments: // // storage - Pointer to the root IComPropertySetStorage instance StorageSummaryInformation::StorageSummaryInformation(IComPropertySetStorage^ storage) : m_pPropertyStorage(NULL) { IPropertyStorage* pPropStorage; // Local IPropertyStg interface HRESULT hResult; // Result from function call if(storage == nullptr) throw gcnew ArgumentNullException(); m_readOnly = StorageUtil::IsStorageReadOnly(safe_cast<IComStorage^>(storage)); // First try to open an existing property set with the FMTID from // the current IStorage object ... hResult = storage->Open(FMTID_SUMMARYINFORMATION, ((m_readOnly) ? STGM_READ : STGM_READWRITE) | STGM_SHARE_EXCLUSIVE, &pPropStorage); // OK, that didn't work, so let's try to create it instead ... if((hResult == STG_E_FILENOTFOUND) && (!m_readOnly)) { hResult = storage->Create(FMTID_SUMMARYINFORMATION, NULL, PROPSETFLAG_DEFAULT, STGM_READWRITE | STGM_SHARE_EXCLUSIVE, &pPropStorage); } // Failure to open or create the summary information set is fatal if(FAILED(hResult)) throw gcnew StorageException(hResult); m_pPropertyStorage = pPropStorage; // Copy into the __gc mvar } //--------------------------------------------------------------------------- // StorageSummaryInformation Finalizer StorageSummaryInformation::!StorageSummaryInformation(void) { // Release local COM interface pointers and reset them all to NULL if(m_pPropertyStorage) m_pPropertyStorage->Release(); m_pPropertyStorage = NULL; } //--------------------------------------------------------------------------- // StorageSummaryInformation::GetFileTimeValue (private) // // Retrieves a FILETIME from the contained property set (if available) // // Arguments: // // propid - The special PROPID value for this item DateTime StorageSummaryInformation::GetFileTimeValue(PROPID propid) { HRESULT hResult; // Result from function call PROPSPEC propspec; // PROPSPEC structure PULARGE_INTEGER puli; // Pointer to a ULARGE_INTEGER PROPVARIANT varValue; // PROPVARIANT value CHECK_DISPOSED(m_disposed); if(!m_pPropertyStorage) return DateTime(0); // <--- PROPSET NOT AVAILABLE propspec.ulKind = PRSPEC_PROPID; // Using the PROPID propspec.propid = propid; // Set up the PROPID // Attempt to read the value from the property set, and just return // a default value if it cannot be retrieved hResult = m_pPropertyStorage->ReadMultiple(1, &propspec, &varValue); if(FAILED(hResult)) return DateTime(0); // Convert the FILETIME into an unsigned 64 bit integer and then // convert it into a DateTime structure for the caller puli = reinterpret_cast<PULARGE_INTEGER>(&varValue.filetime); return DateTime::FromFileTimeUtc(puli->QuadPart); } //--------------------------------------------------------------------------- // StorageSummaryInformation::GetIntegerValue (private) // // Retrieves a 32bit integer from the contained property set (if available) // // Arguments: // // propid - The special PROPID value for this item int StorageSummaryInformation::GetIntegerValue(PROPID propid) { HRESULT hResult; // Result from function call PROPSPEC propspec; // PROPSPEC structure PROPVARIANT varValue; // PROPVARIANT value CHECK_DISPOSED(m_disposed); if(!m_pPropertyStorage) return 0; // <--- PROPSET NOT AVAILABLE propspec.ulKind = PRSPEC_PROPID; // Using the PROPID propspec.propid = propid; // Set up the PROPID // Attempt to read the value from the property set, and just return // a default value if it cannot be retrieved hResult = m_pPropertyStorage->ReadMultiple(1, &propspec, &varValue); if(FAILED(hResult)) return 0; return varValue.lVal; // Return the integer value } //--------------------------------------------------------------------------- // StorageSummaryInformation::GetStringValue (private) // // Retrieves a string from the contained property set (if available) // // Arguments: // // propid - The special PROPID value for this item String^ StorageSummaryInformation::GetStringValue(PROPID propid) { HRESULT hResult; // Result from function call PROPSPEC propspec; // PROPSPEC structure PROPVARIANT varValue; // PROPVARIANT value CHECK_DISPOSED(m_disposed); if(!m_pPropertyStorage) return String::Empty; // <--- PROPSET NOT AVAILABLE propspec.ulKind = PRSPEC_PROPID; // Using the PROPID propspec.propid = propid; // Set up the PROPID // Attempt to read the value from the property set, and just return // a default value if it cannot be retrieved hResult = m_pPropertyStorage->ReadMultiple(1, &propspec, &varValue); if(FAILED(hResult)) return String::Empty; // Convert the ANSI property string into a managed String object, // and make sure to release the PROPVARIANT no matter what happens try { return gcnew String(varValue.pszVal); } finally { PropVariantClear(&varValue); } } //--------------------------------------------------------------------------- // StorageSummaryInformation::GetTimeSpanValue (private) // // Retrieves a FILETIME (timespan) from the contained property set (if available) // // Arguments: // // propid - The special PROPID value for this item TimeSpan StorageSummaryInformation::GetTimeSpanValue(PROPID propid) { HRESULT hResult; // Result from function call PROPSPEC propspec; // PROPSPEC structure PULARGE_INTEGER puli; // Pointer to a ULARGE_INTEGER PROPVARIANT varValue; // PROPVARIANT value CHECK_DISPOSED(m_disposed); if(!m_pPropertyStorage) return TimeSpan(0); // <--- PROPSET NOT AVAILABLE propspec.ulKind = PRSPEC_PROPID; // Using the PROPID propspec.propid = propid; // Set up the PROPID // Attempt to read the value from the property set, and just return // a default value if it cannot be retrieved hResult = m_pPropertyStorage->ReadMultiple(1, &propspec, &varValue); if(FAILED(hResult)) return TimeSpan(0); // Convert the FILETIME into an unsigned 64 bit integer and then // convert it into a DateTime structure for the caller puli = reinterpret_cast<PULARGE_INTEGER>(&varValue.filetime); return TimeSpan(puli->QuadPart); } //--------------------------------------------------------------------------- // StorageSummaryInformation::InternalDispose (internal) // // Behaves as a pseudo-destructor for the class so we can implement a // finalizer without having to expose a .Dispose() method publically // // Arguments: // // NONE void StorageSummaryInformation::InternalDispose(void) { if(m_disposed) return; // Class has already been disposed of this->!StorageSummaryInformation(); // Invoke the finalizer GC::SuppressFinalize(this); // Suppress finalization m_disposed = true; // Object is now disposed } //--------------------------------------------------------------------------- // StorageSummaryInformation::SetFileTimeValue (private) // // Changes the value of a FILETIME in the property set // // Arguments: // // propid - PROPID of the property to be changed // value - DateTime value to set the property to void StorageSummaryInformation::SetFileTimeValue(PROPID propid, DateTime value) { HRESULT hResult; // Result from function call PROPSPEC propspec; // PROPSPEC structure PULARGE_INTEGER puli; // Pointer to a ULARGE_INTEGER PROPVARIANT varValue; // PROPVARIANT value CHECK_DISPOSED(m_disposed); if(m_readOnly) throw gcnew InvalidOperationException("StorageSummaryInfo is read-only"); if(!m_pPropertyStorage) return; // <--- PROPERTY SET NOT AVAILABLE propspec.ulKind = PRSPEC_PROPID; // Using the PROPID propspec.propid = propid; // Set up the PROPID // Initialize the PROPVARIANT with the FILETIME information varValue.vt = VT_FILETIME; puli = reinterpret_cast<PULARGE_INTEGER>(&varValue.filetime); puli->QuadPart = value.ToFileTime(); // Attempt to write the new value into the property set. Unlike the // GetValue() method, we actually throw an exception if this fails hResult = m_pPropertyStorage->WriteMultiple(1, &propspec, &varValue, 0); if(FAILED(hResult)) throw gcnew StorageException(hResult); m_pPropertyStorage->Commit(STGC_DEFAULT); // Commit the changes to disk // NOTE: DO NOT CALL PropVariantClear } //--------------------------------------------------------------------------- // StorageSummaryInformation::SetIntegerValue (private) // // Changes the value of a 32bit integer in the property set // // Arguments: // // propid - PROPID of the property to be changed // value - TimeSpan value to set the property to void StorageSummaryInformation::SetIntegerValue(PROPID propid, int value) { HRESULT hResult; // Result from function call PROPSPEC propspec; // PROPSPEC structure PROPVARIANT varValue; // PROPVARIANT value CHECK_DISPOSED(m_disposed); if(m_readOnly) throw gcnew InvalidOperationException("StorageSummaryInfo is read-only"); if(!m_pPropertyStorage) return; // <--- PROPERTY SET NOT AVAILABLE propspec.ulKind = PRSPEC_PROPID; // Using the PROPID propspec.propid = propid; // Set up the PROPID varValue.vt = VT_I4; // Passing in a VT_I4 varValue.lVal = value; // Set the VT_I4 value // Attempt to write the new value into the property set. Unlike the // GetValue() method, we actually throw an exception if this fails hResult = m_pPropertyStorage->WriteMultiple(1, &propspec, &varValue, 0); if(FAILED(hResult)) throw gcnew StorageException(hResult); m_pPropertyStorage->Commit(STGC_DEFAULT); // Commit the changes to disk // NOTE: DO NOT CALL PropVariantClear } //--------------------------------------------------------------------------- // StorageSummaryInformation::SetStringValue (private) // // Changes the value of a string in the property set // // Arguments: // // propid - PROPID of the property to be changed // value - Value to set the property to void StorageSummaryInformation::SetStringValue(PROPID propid, String^ value) { HRESULT hResult; // Result from function call PROPSPEC propspec; // PROPSPEC structure PROPVARIANT varValue; // PROPVARIANT value IntPtr ptValue; // Unmanaged string buffer CHECK_DISPOSED(m_disposed); if(m_readOnly) throw gcnew InvalidOperationException("StorageSummaryInfo is read-only"); if(!m_pPropertyStorage) return; // <--- PROPERTY SET NOT AVAILABLE propspec.ulKind = PRSPEC_PROPID; // Using the PROPID propspec.propid = propid; // Set up the PROPID ptValue = Marshal::StringToHGlobalAnsi(value); // Convert the string // Initialize the PROPVARIANT with the pointer to the ANSI string varValue.vt = VT_LPSTR; varValue.pszVal = reinterpret_cast<LPSTR>(ptValue.ToPointer()); try { // Attempt to write the new value into the property set. Unlike the // GetValue() method, we actually throw an exception if this fails hResult = m_pPropertyStorage->WriteMultiple(1, &propspec, &varValue, 0); if(FAILED(hResult)) throw gcnew StorageException(hResult); m_pPropertyStorage->Commit(STGC_DEFAULT); // Commit the changes to disk } // NOTE: DO NOT CALL PropVariantClear! It might try to release the // unmanaged string buffer that we allocated with Marshal::StringToHGlobal finally { Marshal::FreeHGlobal(ptValue); } } //--------------------------------------------------------------------------- // StorageSummaryInformation::SetTimeSpanValue (private) // // Changes the value of a FILETIME (timespan) in the property set // // Arguments: // // propid - PROPID of the property to be changed // value - TimeSpan value to set the property to void StorageSummaryInformation::SetTimeSpanValue(PROPID propid, TimeSpan value) { HRESULT hResult; // Result from function call PROPSPEC propspec; // PROPSPEC structure PULARGE_INTEGER puli; // Pointer to a ULARGE_INTEGER PROPVARIANT varValue; // PROPVARIANT value CHECK_DISPOSED(m_disposed); if(m_readOnly) throw gcnew InvalidOperationException("StorageSummaryInfo is read-only"); if(!m_pPropertyStorage) return; // <--- PROPERTY SET NOT AVAILABLE propspec.ulKind = PRSPEC_PROPID; // Using the PROPID propspec.propid = propid; // Set up the PROPID // Initialize the PROPVARIANT with the FILETIME information varValue.vt = VT_FILETIME; puli = reinterpret_cast<PULARGE_INTEGER>(&varValue.filetime); puli->QuadPart = value.Ticks; // Attempt to write the new value into the property set. Unlike the // GetValue() method, we actually throw an exception if this fails hResult = m_pPropertyStorage->WriteMultiple(1, &propspec, &varValue, 0); if(FAILED(hResult)) throw gcnew StorageException(hResult); m_pPropertyStorage->Commit(STGC_DEFAULT); // Commit the changes to disk // NOTE: DO NOT CALL PropVariantClear } //--------------------------------------------------------------------------- END_ROOT_NAMESPACE(zuki::storage) #pragma warning(pop)
36.462264
90
0.667853
[ "object" ]
b26df1a0b3f8fee8d2cd7ac74ac7174e46188180
7,911
cpp
C++
SimSpark/rcssserver3d/plugin/soccer/kickeffector/kickeffector.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/kickeffector/kickeffector.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/kickeffector/kickeffector.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri May 9 2003 Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group $Id$ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "kickaction.h" #include "kickeffector.h" #include <salt/random.h> #include <zeitgeist/logserver/logserver.h> #include <oxygen/sceneserver/transform.h> #include <oxygen/physicsserver/spherecollider.h> #include <soccerbase/soccerbase.h> using namespace boost; using namespace oxygen; using namespace salt; using namespace std; KickEffector::KickEffector() : oxygen::Effector(), mKickMargin(0.04),mPlayerRadius(0.0),mBallRadius(0.0), mForceFactor(4.0),mTorqueFactor(0.1), mMaxPower(100.0), mMinAngle(0.0),mMaxAngle(50.0), mSteps(10), mSigmaPhiEnd(0.9), mSigmaPhiMid(4.5) { } KickEffector::~KickEffector() { } void KickEffector::PrePhysicsUpdateInternal(float /*deltaTime*/) { // this should also include the case when there is no ball // (because then there will be no body, neither). if (mAction.get() == 0 || mBallBody.get() == 0) { return; } if (mAgent.get() == 0) { GetLog()->Error() << "ERROR: (KickEffector) parent node is not derived from BaseNode\n"; return; } boost::shared_ptr<KickAction> kickAction = dynamic_pointer_cast<KickAction>(mAction); mAction.reset(); if (kickAction.get() == 0) { GetLog()->Error() << "ERROR: (KickEffector) cannot realize an unknown ActionObject\n"; return; } // if the agent doesn't have a body, we're done (this should never happen) if (mBall.get() == 0) return; Vector3f force = mBallBody->GetWorldTransform().Pos() - mAgent->GetWorldTransform().Pos(); // the ball can be kicked if the distance is // less then Ball-Radius + Player-Radius + KickMargin AND // the player is close to the ground if (mAgent->GetWorldTransform().Pos().z() > mPlayerRadius + 0.01 || force.Length() > mPlayerRadius + mBallRadius + mKickMargin) { // ball is out of reach, or player is in the air: // kick has no effect return; } // get the kick angle in the horizontal plane double theta = salt::gArcTan2(force[1], force[0]); if (mThetaErrorRNG.get() != 0) { theta += (*(mThetaErrorRNG.get()))(); } float phi = salt::gMin(salt::gMax(kickAction->GetAngle(), mMinAngle), mMaxAngle); if (mSigmaPhiEnd > 0.0 || mSigmaPhiMid > 0.0) { // f will be close to 0.0 if the angle is near the minimum or the maximum. // f will be close to 1.0 if the angle is somewhere in the middle of the range. float f = 1.0 - 2.0 * salt::gAbs((phi - mMinAngle) / (mMaxAngle - mMinAngle) - 0.5); // f is set to a number between mSigmaPhiEnd and mSigmaPhiMid f = salt::gMax(mSigmaPhiEnd + f * (mSigmaPhiMid-mSigmaPhiEnd), 0.0); phi = salt::NormalRNG<>(phi,f)(); } phi = salt::gDegToRad(90.0-phi); // x = r * cos(theta) * sin(90 - phi), with r = 1.0 force[0] = salt::gCos(theta) * salt::gSin(phi); // y = r * sin(theta) * sin(90 - phi), with r = 1.0 force[1] = salt::gSin(theta) * salt::gSin(phi); // z = r * cos(90 - phi), with r = 1.0 force[2] = salt::gCos(phi); float kick_power = salt::gMin(salt::gMax(kickAction->GetPower(), 1.0f), mMaxPower); if (mForceErrorRNG.get() != 0) { kick_power += (*(mForceErrorRNG.get()))(); } force *= (mForceFactor * kick_power); const Vector3f torque(-mTorqueFactor*force[1]/salt::g2PI, mTorqueFactor*force[0]/salt::g2PI, 0.0); mBall->SetAcceleration(mSteps,force,torque,mAgent); mBallStateAspect->UpdateLastKickingAgent(mAgent); } boost::shared_ptr<ActionObject> KickEffector::GetActionObject(const Predicate& predicate) { do { if (predicate.name != GetPredicate()) { GetLog()->Error() << "ERROR: (KickEffector) invalid predicate" << predicate.name << "\n"; break; } Predicate::Iterator iter = predicate.begin(); float angle; if (! predicate.AdvanceValue(iter, angle)) { GetLog()->Error() << "ERROR: (KickEffector) kick angle parameter expected\n"; break; } float power; if (! predicate.AdvanceValue(iter, power)) { GetLog()->Error() << "ERROR: (KickEffector) kick power expected\n"; break; } // construct the KickAction object return boost::shared_ptr<KickAction>(new KickAction(GetPredicate(),angle,power)); } while (0); // some error happened return boost::shared_ptr<ActionObject>(); } void KickEffector::OnLink() { SoccerBase::GetBall(*this,mBall); SoccerBase::GetBallBody(*this,mBallBody); mAgent = dynamic_pointer_cast<AgentAspect>(GetParent().lock()); if (mAgent.get() == 0) { GetLog()->Error() << "ERROR: (KickEffector) parent node is not derived from AgentAspect\n"; return; } boost::shared_ptr<SphereCollider> geom = dynamic_pointer_cast<SphereCollider>(mAgent->GetChild("geometry")); if (geom.get() == 0) { GetLog()->Error() << "ERROR: (KickEffector) parent node has no SphereCollider child\n"; } else { mPlayerRadius = geom->GetRadius(); } if (! SoccerBase::GetBallCollider(*this,geom)) { GetLog()->Error() << "ERROR: (KickEffector) ball node has no SphereCollider child\n"; } else { mBallRadius = geom->GetRadius(); } if (mBallStateAspect.get() == 0) { mBallStateAspect = dynamic_pointer_cast<BallStateAspect> (GetCore()->Get("/sys/server/gamecontrol/BallStateAspect")); if (mBallStateAspect.get() == 0) return; } } void KickEffector::OnUnlink() { mForceErrorRNG.reset(); mThetaErrorRNG.reset(); mBallBody.reset(); mAgent.reset(); } void KickEffector::SetKickMargin(float margin) { mKickMargin = margin; } void KickEffector::SetNoiseParams(double sigma_force, double sigma_theta, double sigma_phi_end, double sigma_phi_mid) { NormalRngPtr rng(new salt::NormalRNG<>(0.0,sigma_force)); mForceErrorRNG = rng; NormalRngPtr rng2(new salt::NormalRNG<>(0.0,sigma_theta)); mThetaErrorRNG = rng2; mSigmaPhiEnd = sigma_phi_end; mSigmaPhiMid = sigma_phi_mid; } void KickEffector::SetForceFactor(float force_factor) { mForceFactor = force_factor; } void KickEffector::SetTorqueFactor(float torque_factor) { mTorqueFactor = torque_factor; } void KickEffector::SetSteps(int steps) { mSteps = steps; } void KickEffector::SetMaxPower(float max_power) { mMaxPower = max_power; } void KickEffector::SetAngleRange(float min, float max) { if (max <= min) { GetLog()->Error() << "ERROR: (KickEffector) min. kick angle should be < max kick angle\n"; return; } mMinAngle = min; mMaxAngle = max; }
27.855634
92
0.621034
[ "geometry", "object", "transform", "3d" ]
b2734ba9ce3ed00bde2c47be601a8766d7360c08
938
cpp
C++
PROX/FOUNDATION/SPARSE/unit_tests/sparse_element_prod/sparse_element_prod.cpp
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
[ "MIT" ]
2
2019-11-27T09:44:45.000Z
2020-01-13T00:24:21.000Z
PROX/FOUNDATION/SPARSE/unit_tests/sparse_element_prod/sparse_element_prod.cpp
erleben/matchstick
1cfdc32b95437bbb0063ded391c34c9ee9b9583b
[ "MIT" ]
null
null
null
PROX/FOUNDATION/SPARSE/unit_tests/sparse_element_prod/sparse_element_prod.cpp
erleben/matchstick
1cfdc32b95437bbb0063ded391c34c9ee9b9583b
[ "MIT" ]
null
null
null
#include <sparse.h> #define BOOST_AUTO_TEST_MAIN #include <boost/test/auto_unit_test.hpp> #include <boost/test/unit_test_suite.hpp> #include <boost/test/floating_point_comparison.hpp> #include <boost/test/test_tools.hpp> BOOST_AUTO_TEST_SUITE(SPARSE); BOOST_AUTO_TEST_CASE(element_prod_test) { typedef sparse::Block<2,1,float> block_type; typedef sparse::Vector<block_type> vector_type; vector_type a; vector_type b; vector_type c; a.resize(2); b.resize(2); c.resize(2); a(0)(0) = 1.0f; a(0)(1) = 2.0f; a(1)(0) = 3.0f; a(1)(1) = 4.0f; b(0)(0) = 4.0f; b(0)(1) = 3.0f; b(1)(0) = 2.0f; b(1)(1) = 1.0f; c(0)(0) = 1.0f; c(0)(1) = 1.0f; c(1)(0) = 1.0f; c(1)(1) = 1.0f; sparse::element_prod( a, b, c); BOOST_CHECK( c(0)(0) == 4.0f ); BOOST_CHECK( c(0)(1) == 6.0f ); BOOST_CHECK( c(1)(0) == 6.0f ); BOOST_CHECK( c(1)(1) == 4.0f ); } BOOST_AUTO_TEST_SUITE_END();
19.142857
51
0.602345
[ "vector" ]
b27a64b4a087c6d62f0812431f310e1cf4f96e3a
2,412
cpp
C++
Algorithms/1801.Number_of_Orders_in_the_Backlog.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/1801.Number_of_Orders_in_the_Backlog.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/1801.Number_of_Orders_in_the_Backlog.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
typedef long long LL; class Solution { public: const int mod = (int) 1e9+7; int getNumberOfBacklogOrders(vector<vector<int>>& orders) { map<int,LL> mpbuy,mpsell; map<int,LL>::iterator it; int n = orders.size(); for( int i = 0 ; i < n ; i++ ) { if(orders[i][2] == 0) { mpbuy[orders[i][0]] += orders[i][1]; while(!mpsell.empty()) { it = mpsell.begin(); if((*it).first <= orders[i][0]) { int psell = (*it).first; LL asell = (*it).second; int pbuy = orders[i][0]; LL abuy = mpbuy[pbuy]; mpbuy.erase(pbuy); mpsell.erase(psell); LL mn = min(asell,abuy); asell -= mn; abuy -= mn; if(asell) mpsell[psell] = asell; if(abuy) mpbuy[pbuy] = abuy; else break; } else break; } } else { mpsell[orders[i][0]] += orders[i][1]; while(!mpbuy.empty()) { it = mpbuy.end(); it--; if((*it).first >= orders[i][0]) { int pbuy = (*it).first; LL abuy = (*it).second; int psell = orders[i][0]; LL asell = mpsell[psell]; mpbuy.erase(pbuy); mpsell.erase(psell); LL mn = min(asell,abuy); asell -= mn; abuy -= mn; if(abuy) mpbuy[pbuy] = abuy; if(asell) mpsell[psell] = asell; else break; } else break; } } } LL ans = 0; for(auto it : mpbuy) ans += it.second; for(auto it : mpsell) ans += it.second; return ans%mod; } };
34.457143
63
0.307214
[ "vector" ]
b27bb6379dfb02d2799c0c597a9a14d8269ec1dd
6,677
cpp
C++
src/main/cpp/linux/desktopicons.cpp
ghedlund/desktopicons
ddcf892e1ca267ac36d3dd646441a534451372ee
[ "Apache-2.0" ]
null
null
null
src/main/cpp/linux/desktopicons.cpp
ghedlund/desktopicons
ddcf892e1ca267ac36d3dd646441a534451372ee
[ "Apache-2.0" ]
null
null
null
src/main/cpp/linux/desktopicons.cpp
ghedlund/desktopicons
ddcf892e1ca267ac36d3dd646441a534451372ee
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012-2018 Gregory Hedlund * * 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 <X11/Xlib.h> #include <gtk/gtk.h> #include <gio/gio.h> #include <jni.h> #include "../../../../target/generated-sources/cpp/include/desktopicons.h" #include "../jniload.h" #include "../common.h" #include <stdio.h> #include <iostream> /* * Get icon from current gtk theme. Object should be * released using g_object_unref * * @param name * @param size */ static GdkPixbuf* load_icon(const gchar* name, gint size) { GError *error = NULL; GtkIconLookupFlags flags = GTK_ICON_LOOKUP_FORCE_SIZE | GTK_ICON_LOOKUP_GENERIC_FALLBACK; auto icon_theme = gtk_icon_theme_get_default(); auto pixbuf = gtk_icon_theme_load_icon( icon_theme, name, size, flags, &error); if(!pixbuf) { std::cerr << error->message << "\n"; g_error_free(error); return NULL; } return pixbuf; } static GdkPixbuf* load_icon_choice(const gchar* choices[], gint size) { GError *error = NULL; GtkIconLookupFlags flags = GTK_ICON_LOOKUP_FORCE_SIZE | GTK_ICON_LOOKUP_GENERIC_FALLBACK; auto icon_theme = gtk_icon_theme_get_default(); auto icon_info = gtk_icon_theme_choose_icon(icon_theme, choices, size, flags); if(icon_info) { auto retVal = gtk_icon_info_load_icon(icon_info, &error); gtk_icon_info_free(icon_info); if(!retVal) { std::cerr << error->message << std::endl; g_error_free(error); } return retVal; } else { return NULL; } } static void draw_icon(JNIEnv *env, jobject bufferedImage, GdkPixbuf *pixbuf, int px, int py) { auto width = gdk_pixbuf_get_width(pixbuf); auto height = gdk_pixbuf_get_height(pixbuf); auto rowstride = gdk_pixbuf_get_rowstride(pixbuf); auto n_channels = gdk_pixbuf_get_n_channels(pixbuf); auto pixels = gdk_pixbuf_get_pixels(pixbuf); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { auto p = pixels + (y * rowstride) + (x * n_channels); int argb = 0; for(int i = 0; i < 3; i++) { argb |= p[i] << (8 * i); } if(gdk_pixbuf_get_has_alpha(pixbuf)) { argb |= p[n_channels-1] << 24; } drawPixel(env, bufferedImage, px+x, py+y, argb); } } } static GtkIconInfo* findIconForType(const gchar* type, gint size) { GtkIconInfo *retVal = NULL; GtkIconLookupFlags flags = GTK_ICON_LOOKUP_FORCE_SIZE | GTK_ICON_LOOKUP_GENERIC_FALLBACK; auto icon_theme = gtk_icon_theme_get_default(); return retVal; } /* * Class: ca_hedlund_desktopicons_DesktopIcons * Method: _drawIconForPath * Signature: (Ljava/lang/String;Ljava/awt/image/BufferedImage;IIII)I */ JNIEXPORT jint JNICALL Java_ca_hedlund_desktopicons_DesktopIcons__1drawIconForPath (JNIEnv *env, jclass DesktopIcons, jstring path, jobject bufferedImage, jint x, jint y, jint w, jint h) { jint retVal = 0; jboolean isCopy = false; GFileQueryInfoFlags queryFlags = G_FILE_QUERY_INFO_NONE; GError *error = NULL; //XInitThreads(); if(!gtk_init_check(0, NULL)) return -1; auto szPath = env->GetStringUTFChars(path, &isCopy); auto gFile = g_file_new_for_path(szPath); auto gFileInfo = g_file_query_info(gFile, "standard::icon", queryFlags, NULL, &error); if(gFileInfo) { auto gIcon = g_file_info_get_icon(gFileInfo); if(gIcon) { auto gThemedIcon = (GThemedIcon*)(gIcon); auto iconNames = g_themed_icon_get_names(gThemedIcon); auto icon = load_icon_choice(iconNames, w); if(icon) { draw_icon(env, bufferedImage, icon, x, y); g_object_unref(icon); } else { retVal = ca_hedlund_desktopicons_DesktopIcons_ICON_NOT_FOUND; } } else { retVal = ca_hedlund_desktopicons_DesktopIcons_ICON_NOT_FOUND; } //g_object_unref(gFileInfo); } else { std::cerr << error->message << "\n"; g_error_free(error); retVal = ca_hedlund_desktopicons_DesktopIcons_FILE_NOT_FOUND; } //g_object_unref(gFile); env->ReleaseStringUTFChars(path, szPath); return retVal; } /* * Class: ca_hedlund_desktopicons_DesktopIcons * Method: _drawIconForFileType * Signature: (Ljava/lang/String;Ljava/awt/image/BufferedImage;IIII)I */ JNIEXPORT jint JNICALL Java_ca_hedlund_desktopicons_DesktopIcons__1drawIconForFileType (JNIEnv *env, jclass DesktopIcons, jstring type, jobject bufferedImage, jint x , jint y, jint w, jint h) { jboolean isCopy = false; jint retVal = 0; //XInitThreads(); if(!gtk_init_check(0, NULL)) return -1; auto szType = env->GetStringUTFChars(type, &isCopy); auto icon = load_icon(szType, w); if(!icon) { retVal = ca_hedlund_desktopicons_DesktopIcons_ICON_NOT_FOUND; } else { draw_icon(env, bufferedImage, icon, x, y); g_object_unref(icon); } env->ReleaseStringUTFChars(type, szType); return retVal; } /* * Class: ca_hedlund_desktopicons_DesktopIcons * Method: _drawStockIcon * Signature: (ILjava/awt/image/BufferedImage;IIII)I */ JNIEXPORT jint JNICALL Java_ca_hedlund_desktopicons_DesktopIcons__1drawStockIcon (JNIEnv *env, jclass DesktopIcons, jint iconId, jobject bufferedImage, jint x, jint y, jint w, jint h) { const char* szEnumClazz = "ca/hedlund/desktopicons/GtkStockIcon"; const char* szGetStockIconName = "getStockIcon"; const char* szGetStockIconSig = "(I)Lca/hedlund/desktopicons/GtkStockIcon;"; const char* szIconName = "getIconName"; const char* szIconSig = "()Ljava/lang/String;"; jboolean isCopy = false; jint retVal = 0; //XInitThreads(); if(!gtk_init_check(0, NULL)) return -1; auto GtkStockIcon = env->FindClass(szEnumClazz); auto szGetStockIconID = env->GetStaticMethodID(GtkStockIcon, szGetStockIconName, szGetStockIconSig); auto iconNameId = env->GetMethodID(GtkStockIcon, szIconName, szIconSig); auto stockIcon = env->CallStaticObjectMethod(GtkStockIcon, szGetStockIconID, iconId); if(stockIcon != NULL) { jstring jIconName = static_cast<jstring>(env->CallObjectMethod(stockIcon, iconNameId)); auto iconName = env->GetStringUTFChars(jIconName, &isCopy); if(!iconName) { return 0; } auto icon = load_icon(iconName, w); if(icon) { draw_icon(env, bufferedImage, icon, x, y); g_object_unref(icon); } else { retVal = ca_hedlund_desktopicons_DesktopIcons_ICON_NOT_FOUND; } env->ReleaseStringUTFChars(jIconName, iconName); } return retVal; }
29.675556
109
0.731616
[ "object" ]
b28196f28313df289cea6f2c2151059ef94b5479
4,940
cpp
C++
src/FileReader.cpp
Spoock01/The-Capacitated-Vehicle-Routing-Problem
0f05acbf02020a2f7761f2ebe4afdd6bef609304
[ "MIT" ]
1
2019-09-25T18:20:57.000Z
2019-09-25T18:20:57.000Z
src/FileReader.cpp
Spoock01/The-Capacitated-Vehicle-Routing-Problem
0f05acbf02020a2f7761f2ebe4afdd6bef609304
[ "MIT" ]
null
null
null
src/FileReader.cpp
Spoock01/The-Capacitated-Vehicle-Routing-Problem
0f05acbf02020a2f7761f2ebe4afdd6bef609304
[ "MIT" ]
2
2019-09-10T03:58:03.000Z
2020-02-20T17:32:56.000Z
#include "../include/FileReader.h" #include <time.h> #include <cmath> #include "../include/ConstructiveHeuristic.h" #include "../include/Graph.h" #include "../include/Grasp.h" #include "../include/Helper.h" #include "../include/MovementHeuristic.h" int DIMENSION; int VEHICLE; int CAPACITY; int g_distance = 0; std::ifstream instanceFile; std::vector<Demand> demands; std::vector<std::vector<int>> g_weightMatrix; int getDimension() { return DIMENSION; } int getVEHICLE() { return VEHICLE; } int getCapacity() { return CAPACITY; } void splitInteger() { std::string line; for (int i = 0; i < 3; i++) { getline(instanceFile, line); char *token = strtok((char *)line.c_str(), " "); token = strtok(NULL, " "); switch (i) { case 0: DIMENSION = std::stoi(token); break; case 1: VEHICLE = std::stoi(token); break; case 2: CAPACITY = std::stoi(token); break; default: return; } } std::vector<std::vector<int>> aux(DIMENSION, std::vector<int>(DIMENSION, -1)); g_weightMatrix = aux; } void readDemands() { int client, client_demand; for (int i = 0; i < DIMENSION; i++) { instanceFile >> client; instanceFile >> client_demand; demands.push_back(Demand(client, client_demand)); } } void readMatrix(int type) { std::string line; auto aux = -1; if (type) { for (int i = 0; i < DIMENSION; i++) { for (int j = 0; j < i + 1; j++) { if (i != j) { instanceFile >> aux; g_weightMatrix[i][j] = aux; g_weightMatrix[j][i] = aux; } else { getline(instanceFile, line); g_weightMatrix[i][j] = 0; break; } } } } else { int vertex, x, y; std::vector<std::pair<int, int>> node; for (int i = 0; i < DIMENSION; i++) { instanceFile >> vertex >> x >> y; node.push_back(std::make_pair(x, y)); } for (auto i = 0; i < DIMENSION; i++) { for (auto j = 0; j < DIMENSION - 1; j++) { auto distancia = (int)std::round( hypot(node[i].first - node[j].first, node[i].second - node[j].second)); if (i != j) { g_weightMatrix[i][j] = distancia; g_weightMatrix[j][i] = distancia; } else g_weightMatrix[i][j] = 0; } } } } void skip(int times) { std::string line; for (int i = 0; i < times; i++) { getline(instanceFile, line); } } void readFile(std::string file) { std::string line; instanceFile.open(file.c_str()); if (instanceFile.is_open()) { skip(1); // Skipping NAME splitInteger(); // Dimension, VEHICLE, CAPACITY skip(1); // Skipping DEMAND_SECTION line readDemands(); // Reading DEMAND_SECTION skip(3); // Skipping DEMAND_SECTION, empty and EDGE_WEIGHT_SECTION /* CVRP (path + filename) size == 28 */ readMatrix(file.size() == 28 ? 0 : 1); auto graph = Graph<int>(); graph.setAdjMatrix(g_weightMatrix); graph.setDemands(demands); auto ch = ConstructiveHeuristic(graph); float time1 = 0.0; auto sum1 = 0; std::cout << "Greedy\n\n"; clock_t t1; t1 = clock(); //for (auto i = 0; i < 10; i++) { auto routess = ch.nearestNeighbor(CAPACITY, DIMENSION, VEHICLE); auto mh = MovementHeuristic(graph); auto route = mh.buildRoutesByMethod(splitRoutes(routess)); auto dis = getDistance(route, graph, false); printRouteAndDistance(route, dis); sum1 += dis; //} t1 = clock() - t1; time1 = ((float)t1) / CLOCKS_PER_SEC; printf("It took me (%f ms).\n", (time1) * 1000); // printf("Media de distancia: %d\n", sum1 / 10); /* =================================================================== */ float time = 0.0; auto sum = 0; auto grasp = Grasp(graph, CAPACITY); std::cout << "\n\n\nGRASP\n\n"; clock_t t; t = clock(); //for (auto i = 0; i < 10; i++) sum += grasp.buildGrasp(DIMENSION); t = clock() - t; time = ((float)t) / CLOCKS_PER_SEC; printf("It took me (%f ms).\n", (time) * 1000); // printf("Media de distancia: %d\n", sum / 10); // Nunca apagar demands.clear(); instanceFile.close(); } else { std::cout << "Error opening file." << std::endl; } }
27.597765
91
0.484615
[ "vector" ]
b282742f05d0c4ce39434fb9224d0cb68a0f8021
7,656
cpp
C++
Dalton/Filters.cpp
DaltonLens/DaltonLens
65f8655d5fe0166d41ae91d145a219f4796acc45
[ "BSD-2-Clause" ]
7
2018-02-05T23:29:13.000Z
2021-11-23T08:53:12.000Z
Dalton/Filters.cpp
DaltonLens/DaltonLens
65f8655d5fe0166d41ae91d145a219f4796acc45
[ "BSD-2-Clause" ]
9
2018-05-01T18:27:52.000Z
2022-03-19T00:32:33.000Z
Dalton/Filters.cpp
DaltonLens/DaltonLens
65f8655d5fe0166d41ae91d145a219f4796acc45
[ "BSD-2-Clause" ]
1
2020-04-04T17:02:17.000Z
2020-04-04T17:02:17.000Z
// // Copyright (c) 2017, Nicolas Burrus // This software may be modified and distributed under the terms // of the BSD license. See the LICENSE file for details. // #include "Filters.h" #include <Dalton/OpenGL.h> #include <Dalton/OpenGL_Shaders.h> #include <Dalton/Utils.h> #include <Dalton/ColorConversion.h> #include <gl3w/GL/gl3w.h> namespace dl { struct GLFilter::Impl { GLShader shader; }; GLFilter::GLFilter() : impl (new Impl) { } GLFilter::~GLFilter() = default; void GLFilter::initializeGL(const char *glslVersionString, const char *vertexShader, const char *fragmentShader) { impl->shader.initialize (glslVersionString, vertexShader, fragmentShader); } GLShader* GLFilter::glShader () const { return &impl->shader; } void GLFilter::enableGLShader() { impl->shader.enable (); } void GLFilter::disableGLShader() { impl->shader.disable (); } const GLShaderHandles& GLFilter::glHandles () const { return impl->shader.glHandles(); } void GLFilter::applyCPU (const ImageSRGBA& input, ImageSRGBA& output) const { dl_assert (false, "unimplemented"); } } // dl // -------------------------------------------------------------------------------- // GLFilterProcessor // -------------------------------------------------------------------------------- namespace dl { struct GLFilterProcessor::Impl { GLFrameBuffer frameBuffer; GLImageRenderer renderer; }; GLFilterProcessor::GLFilterProcessor() : impl (new Impl()) {} GLFilterProcessor::~GLFilterProcessor() = default; void GLFilterProcessor::initializeGL () { impl->renderer.initializeGL(); } void GLFilterProcessor::render (GLFilter& filter, uint32_t inputTextureId, int width, int height, ImageSRGBA* output) { impl->frameBuffer.enable(width, height); glBindTexture(GL_TEXTURE_2D, inputTextureId); filter.enableGLShader (); impl->renderer.render (); filter.disableGLShader (); if (output) { impl->frameBuffer.downloadBuffer (*output); } impl->frameBuffer.disable(); } GLTexture& GLFilterProcessor::filteredTexture() { return impl->frameBuffer.outputColorTexture(); } } // dl // -------------------------------------------------------------------------------- // Simple filters // -------------------------------------------------------------------------------- namespace dl { void Filter_FlipRedBlue::initializeGL () { GLFilter::initializeGL (glslVersion(), nullptr, fragmentShader_FlipRedBlue_glsl_130); } void Filter_FlipRedBlueAndInvertRed::initializeGL () { GLFilter::initializeGL (glslVersion(), nullptr, fragmentShader_FlipRedBlue_InvertRed_glsl_130); } } // dl // -------------------------------------------------------------------------------- // Highlight Similar Colors // -------------------------------------------------------------------------------- namespace dl { void Filter_HighlightSimilarColors::initializeGL () { GLFilter::initializeGL (glslVersion(), nullptr, fragmentShader_highlightSameColor); GLuint shaderHandle = glHandles().shaderHandle; _attribLocationRefColor_linearRGB = (GLuint)glGetUniformLocation(shaderHandle, "u_refColor_linearRGB"); _attribLocationDeltaH = (GLuint)glGetUniformLocation(shaderHandle, "u_deltaH_360"); _attribLocationDeltaS = (GLuint)glGetUniformLocation(shaderHandle, "u_deltaS_100"); _attribLocationDeltaV = (GLuint)glGetUniformLocation(shaderHandle, "u_deltaV_255"); _attribLocationFrameCount = (GLuint)glGetUniformLocation(shaderHandle, "u_frameCount"); } void Filter_HighlightSimilarColors::enableGLShader () { GLFilter::enableGLShader (); glUniform3f(_attribLocationRefColor_linearRGB, _currentParams.activeColorRGB01.x, _currentParams.activeColorRGB01.y, _currentParams.activeColorRGB01.z); glUniform1f(_attribLocationDeltaH, _currentParams.deltaH_360); glUniform1f(_attribLocationDeltaS, _currentParams.deltaS_100); glUniform1f(_attribLocationDeltaV, _currentParams.deltaV_255); glUniform1i(_attribLocationFrameCount, _currentParams.frameCount / 2); } } // dl // -------------------------------------------------------------------------------- // Daltonize // -------------------------------------------------------------------------------- namespace dl { void Filter_Daltonize::initializeGL () { GLFilter::initializeGL(glslVersion(), nullptr, fragmentShader_DaltonizeV1_glsl_130); GLuint shaderHandle = glHandles().shaderHandle; _attribLocationKind = (GLuint)glGetUniformLocation(shaderHandle, "u_kind"); _attribLocationSimulateOnly = (GLuint)glGetUniformLocation(shaderHandle, "u_simulateOnly"); _attribLocationSeverity = (GLuint)glGetUniformLocation(shaderHandle, "u_severity"); } void Filter_Daltonize::enableGLShader () { GLFilter::enableGLShader (); glUniform1i(_attribLocationKind, static_cast<int>(_currentParams.kind)); glUniform1i(_attribLocationSimulateOnly, _currentParams.simulateOnly); glUniform1f(_attribLocationSeverity, _currentParams.severity); } void applyDaltonizeSimulation (ImageLMS& lmsImage, Filter_Daltonize::Params::Kind blindness, float severity) { // See DaltonLens-Python and libDaltonLens to understand where the hardcoded // values come from. auto protanope = [severity](int c, int r, PixelLMS& p) { // Viénot 1999. p.l = (1.f-severity)*p.l + severity*(2.0205f*p.m - 2.4337f*p.s); }; auto deuteranope = [severity](int c, int r, PixelLMS& p) { // Viénot 1999. p.m = (1.f-severity)*p.m + severity*(0.4949f*p.l + + 1.2045f*p.s); }; auto tritanope = [severity](int c, int r, PixelLMS& p) { // Brettel 1997. // Check which plane. if ((p.l*0.34516 - p.m*0.65480) >= 0) { // Plane 1 for tritanopia p.s = (1.f-severity)*p.s + severity*(-0.00213*p.l + 0.05477*p.m); } else { // Plane 2 for tritanopia p.s = (1.f-severity)*p.s + severity*(-0.06195*p.l + 0.16826*p.m); } }; switch (blindness) { case Filter_Daltonize::Params::Protanope: lmsImage.apply (protanope); break; case Filter_Daltonize::Params::Deuteranope: lmsImage.apply (deuteranope); break; case Filter_Daltonize::Params::Tritanope: lmsImage.apply (tritanope); break; default: assert (false); } } void Filter_Daltonize::applyCPU (const ImageSRGBA& inputSRGBA, ImageSRGBA& output) const { ImageLinearRGB inputRGB = convertToLinearRGB(inputSRGBA); RGBAToLMSConverter converter; ImageLMS lmsImage; converter.convertToLms (inputRGB, lmsImage); applyDaltonizeSimulation (lmsImage, _currentParams.kind, _currentParams.severity); ImageLinearRGB simulatedRGB; converter.convertToLinearRGB (lmsImage, simulatedRGB); if (_currentParams.simulateOnly) { output = convertToSRGBA(simulatedRGB); return; } ImageLinearRGB outputRGB = inputRGB; outputRGB.apply ([&](int c, int r, PixelLinearRGB& rgb) { // [0, 0, 0], // [0.7, 1, 0], // [0.7, 0, 1] const auto& simRgb = simulatedRGB (c, r); float rError = rgb.r - simRgb.r; float gError = rgb.g - simRgb.g; float bError = rgb.b - simRgb.b; float updatedG = rgb.g + 0.7 * rError + 1.0 * gError + 0.0 * bError; float updatedB = rgb.b + 0.7 * rError + 0.0 * gError + 1.0 * bError; rgb.g = updatedG; rgb.b = updatedB; }); output = convertToSRGBA(outputRGB); } } // dl
28.567164
156
0.624869
[ "render" ]
b287238d61774ff0fea09dc779d7f0b7a4959688
769
cpp
C++
test/container/tree/equal.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/container/tree/equal.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/container/tree/equal.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // 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 <fcppt/container/tree/comparison.hpp> #include <fcppt/container/tree/object_impl.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <fcppt/config/external_end.hpp> TEST_CASE( "container::tree equal", "[container],[tree]" ) { typedef fcppt::container::tree::object< unsigned > ui_tree; ui_tree tree1{ 42 }; tree1.push_back( 100 ); ui_tree tree2{ 42 }; tree2.push_back( 100 ); CHECK( tree1 == tree2 ); tree2.push_back( 200 ); CHECK( tree1 != tree2 ); }
13.491228
61
0.663199
[ "object" ]
b287810bd8d521baf6de3ce096fc61fd37de6e47
14,212
cxx
C++
private/inet/xml/core/util/hashtable.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/xml/core/util/hashtable.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/xml/core/util/hashtable.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/* * * Copyright (c) 1998,1999 Microsoft Corporation. All rights reserved. * EXEMPT: copyright change only, no build required * */ #include "core.hxx" #pragma hdrstop #include "core/util/hashtable.hxx" Enumeration * HashtableEnumerator::newHashtableEnumerator( Hashtable *table, EnumType enumType) { HashtableEnumerator * he = new HashtableEnumerator(); he->_table = table; he->_position = 0; he->_enumType = enumType; return he; } /////////////////////////////////////////////////////////////////////////////// ////////////////// Hashtable //////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// DEFINE_CLASS_MEMBERS_CLONING(Hashtable, _T("Hashtable"), Base); const float atticRatio = 0.85f; ////////////// Java constructors ////////////////////////////////////////// Hashtable * Hashtable::newHashtable(int initialCapacity, Mutex * pMutex, bool fAddRef) { return new Hashtable(initialCapacity, pMutex, fAddRef); } Hashtable::Hashtable(int initialCapacity, Mutex * pMutex, bool fAddRef) { if (initialCapacity < HT_DEFAULT_INITIAL_CAPACITY) initialCapacity = HT_DEFAULT_INITIAL_CAPACITY; float loadFactor = HT_DEFAULT_LOAD_FACTOR; _addref = fAddRef; _loadFactor = loadFactor; _threshold = (int)(initialCapacity * loadFactor); _attic = (int)(initialCapacity * atticRatio); _emptyIndex = initialCapacity; _table = new (initialCapacity) HashArray; _pMutex = pMutex; } void Hashtable::finalize() { clear(); _table = null; _pMutex = null; super::finalize(); } ////////////////////// Java methods ///////////////////////////////////// // Clears this hashtable so that it contains no keys. void Hashtable::clear() { #ifdef _ALPHA_ Assert(!_fResizing); #endif if (_size > 0) { for (int i=0; i<_table->length(); ++i) { HashEntry& entry = (*_table)[i]; if (entry.isOccupied()) { entry.clear(this); } } _size = 0; } } // Creates a shallow copy of this hashtable. Object * Hashtable::clone() { #ifdef _ALPHA_ Assert(!_fResizing); #endif Hashtable *result = CAST_TO(Hashtable*, super::clone()); HashArray *newTable = new (_table->length()) HashArray; result->_addref = _addref; result->_size = _size; result->_loadFactor = _loadFactor; result->_threshold = _threshold; result->_attic = _attic; result->_emptyIndex = _emptyIndex; result->_table = newTable; for (int i=0; i<_table->length(); ++i) { HashEntry& myEntry = (*_table)[i]; HashEntry& newEntry = (*newTable)[i]; if (myEntry.isOccupied()) { newEntry.assign(this, myEntry); } } return result; } // Returns the value to which the specified key is mapped in this hashtable. IUnknown * Hashtable::_get(Object *key) { IUnknown *result; HashEntry *pEntry; MutexReadLock lock(_pMutex); TRY { result = (find(key, key->hashCode(), &pEntry) == Present) ? pEntry->value() : null; } CATCH { lock.Release(); Exception::throwAgain(); } ENDTRY return result; } // Maps the specified key to the specified value in this hashtable. IUnknown * Hashtable::_put(Object *key, IUnknown *value) { IUnknown * previousValue; MutexLock lock(_pMutex); TRY { previousValue = _set(key, value, false); } CATCH { lock.Release(); Exception::throwAgain(); } ENDTRY return previousValue; } // Add the value if not there, returns existing value if there IUnknown * Hashtable::_add(Object *key, IUnknown *value) { IUnknown * previousValue; MutexLock lock(_pMutex); TRY { previousValue = _set(key, value, true); } CATCH { lock.Release(); Exception::throwAgain(); } ENDTRY return previousValue; } // Maps the specified key to the specified value in this hashtable. IUnknown * Hashtable::_set(Object *key, IUnknown *value, bool add) { IUnknown *previousValue = null; if (key != null && value != null) { int hashcode = key->hashCode(); HashEntry *pEntry; switch (find(key, hashcode, &pEntry)) { case Present: previousValue = pEntry->value(); if (!add) pEntry->setValue(this, value); break; case EndOfList: findEmptySlot(); pEntry->appendToChain(_emptyIndex); pEntry = &(*_table)[_emptyIndex]; // fall through! case Empty: // case EndOfList falls through to here!! pEntry->set(this, key, value, hashcode); ++_size; if (add) previousValue = value; break; default: AssertSz(0, "Hashtable::Find() returns unknown code"); break; } if (size() > _threshold) { rehash(); } } else { Exception::throwE(E_POINTER); // Exception::NullPointerException); } return previousValue; } // Rehashes the contents of the hashtable into a hashtable with a larger capacity. // Note: caller must take lock. void Hashtable::rehash() { // BUGBUG: there is an intermittent bug under NT5 on one specific alpha machine // in the NT build lab, whereby we end up with a recursive rehash. That is bad. // this is here to stop the problem before it gets out-of-hand. #ifdef _ALPHA_ if(_fResizing) DebugBreak(); _fResizing = true; #endif HashArray *oldTable = _table; int oldCapacity = oldTable->length(); int newCapacity = 2*oldCapacity; HashArray * newTable = new (newCapacity) HashArray; // prepare a larger clear table _size = 0; _threshold = (int)(newCapacity * _loadFactor); _attic = (int)(newCapacity * atticRatio); _emptyIndex = newCapacity; _table = newTable; // rehash the old entries into the new table for (int i=0; i<oldCapacity; ++i) { HashEntry& entry = (*oldTable)[i]; if (entry.isOccupied()) { _set(entry.key(), entry.value(), false); entry.clear(this); } } #ifdef _ALPHA_ _fResizing = false; #endif } // Removes the key (and its corresponding value) from this hashtable. IUnknown * Hashtable::_remove(Object *key) { // this implementation is (relatively) simple, but has a bad worst case. // It re-inserts everything in the chain after the deleted element, so if // it's a long chain we do a lot of work. Because coalesced chaining tends // to yield short chains (length<=5 at loadFactor=0.92), I think it's an // acceptable risk. - SWB IUnknown *oldValue; MutexLock lock(_pMutex); TRY { int index, prevIndex; HashEntry *pEntry; int chainFirst; if (find(key, key->hashCode(), &pEntry, &index, &prevIndex) == Present) { // remember where we are, so we can start re-inserting the chain chainFirst = pEntry->nextIndex(); oldValue = pEntry->value(); // delete the target entry and cut the chain before it pEntry->clear(this); --_size; if (prevIndex != -1) { (*_table)[prevIndex].markEndOfList(); } // make the new empty entry available for chaining if (_emptyIndex <= index) _emptyIndex = index+1; // re-insert the remaining elements on the chain HashEntry temp; temp._value = null; TRY { while (chainFirst != -1) { // get the first element on the chain HashEntry & entry = (*_table)[chainFirst]; temp._key = entry.key(); temp.setValue(this, entry.value()); // remove it (temporarily) if (_emptyIndex <= chainFirst) _emptyIndex = chainFirst+1; chainFirst = entry.nextIndex(); entry.clear(this); --_size; // re-insert it // Cannot use _put() here because it will deadlock since // it also tries to grab the lock. // _put(temp._key, temp.value()); _set(temp._key, temp.value(), false); } } CATCH { temp.clear(this); Exception::throwAgain(); } ENDTRY temp.clear(this); } else // key not found { oldValue = null; } } CATCH { lock.Release(); Exception::throwAgain(); } ENDTRY return oldValue; } // Tests if some key maps into the specified value in this hashtable. bool Hashtable::contains(Object *value) { for (int i=0; i<_table->length(); ++i) { HashEntry & entry = (*_table)[i]; if (entry.isOccupied() && equalValue((Object *)entry.value(), (Object *)value)) { return true; } } return false; } bool Hashtable::equalValue(Object * pDst, Object * pSrc) { return pDst->equals(pSrc); } Hashtable::FindResult Hashtable::find(Object *key, int hashcode, HashEntry **ppEntry, int *pIndex, int *pPrevIndex) { Assert(hashcode == key->hashCode()); Assert(ppEntry); int index = (hashcode & 0x7fffffff) % _attic; int prevIndex = -1; FindResult result = Unknown; HashEntry *pEntry = null; while (result == Unknown) { pEntry = &(*_table)[index]; if (pEntry->isEmpty()) { result = Empty; } else if (pEntry->holdsKey(key, hashcode)) { result = Present; } else if (pEntry->isEndOfList()) { result = EndOfList; } else { prevIndex = index; index = pEntry->nextIndex(); } } *ppEntry = pEntry; if (pIndex) *pIndex = index; if (pPrevIndex) *pPrevIndex = prevIndex; return result; } // special-purpose implementation of find for use by StringHashtable. // this enables looking up a key without creating a String object Hashtable::FindResult Hashtable::find(const TCHAR *s, int len, int hashcode, HashEntry **ppEntry) { Assert(ppEntry); int index = (hashcode & 0x7fffffff) % _attic; FindResult result = Unknown; HashEntry *pEntry = null; while (result == Unknown) { pEntry = &(*_table)[index]; if (pEntry->isEmpty()) { result = Empty; } else if (pEntry->holdsKey(s, len, hashcode)) { result = Present; } else if (pEntry->isEndOfList()) { result = EndOfList; } else { index = pEntry->nextIndex(); } } *ppEntry = pEntry; return result; } void Hashtable::findEmptySlot() { do { --_emptyIndex; } while ((*_table)[_emptyIndex].isOccupied()); AssertSz(_emptyIndex > 0, "Can't find empty slot"); } /////////////////////////////////////////////////////////////////////////////// ////////////////// HashtableEnumerator ////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // use ABSTRACT because of no default constructor DEFINE_ABSTRACT_CLASS_MEMBERS(HashtableEnumerator, _T("HashtableEnumerator"), Base); // Tests if this enumeration contains more elements. bool HashtableEnumerator::hasMoreElements() { for (int i=_position; i<_table->_table->length(); ++i) { HashEntry& entry = (*_table->_table)[i]; if (entry.isOccupied()) return true; } return false; } // Returns the next element of this enumeration && position Object * HashtableEnumerator::_peekElement(int *position) { for (int i=_position; i<_table->_table->length(); ++i) { HashEntry& entry = (*_table->_table)[i]; if (entry.isOccupied()) { *position = i; switch (_enumType) { case Keys: return entry.key(); break; case Values: return (Object *)entry.value(); break; } } } return null; } // Returns the next element of this enumeration. Object * HashtableEnumerator::peekElement() { int i; Object * o = _peekElement(&i); if (o) { return o; } Exception::throwE(E_UNEXPECTED); // Exception::NoSuchElementException); return null; } // Returns the next element of this enumeration. Object * HashtableEnumerator::nextElement() { Object * o = _peekElement(&_position); _position++; return o; } // resets the enumeration void HashtableEnumerator::reset() { _position = 0; } // Called by the garbage collector on an object when garbage collection // determines that there are no more references to the object. void HashtableEnumerator::finalize() { _table = null; super::finalize(); }
24.933333
88
0.517943
[ "object" ]
b2888d4645c486ed5031ad0c96141317c05c5a7d
12,193
cpp
C++
src/physics/rigid_body_problem.cpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
71
2021-09-08T13:16:43.000Z
2022-03-27T10:23:33.000Z
src/physics/rigid_body_problem.cpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
4
2021-09-08T00:16:20.000Z
2022-01-05T17:44:08.000Z
src/physics/rigid_body_problem.cpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
2
2021-09-18T15:15:38.000Z
2021-09-21T15:15:38.000Z
#include "rigid_body_problem.hpp" #include <iostream> #include <tbb/parallel_for_each.h> #include <finitediff.hpp> #include <igl/PI.h> #include <igl/predicates/segment_segment_intersect.h> #include <ipc/utils/intersection.hpp> #include <ccd/rigid/broad_phase.hpp> #include <ccd/rigid/rigid_body_hash_grid.hpp> #include <io/read_rb_scene.hpp> #include <io/serialize_json.hpp> #include <logger.hpp> #include <profiler.hpp> #include <utils/eigen_ext.hpp> namespace ipc::rigid { RigidBodyProblem::RigidBodyProblem() : coefficient_restitution(0) , coefficient_friction(0) , collision_eps(2) , m_timestep(0.01) , do_intersection_check(false) { gravity.setZero(3); } bool RigidBodyProblem::settings(const nlohmann::json& params) { collision_eps = params["collision_eps"]; coefficient_restitution = params["coefficient_restitution"]; coefficient_friction = params["coefficient_friction"]; if (coefficient_friction < 0 || coefficient_friction > 1) { spdlog::warn( "Coefficient of friction (μ={:g}) is outside the standard " "[0, 1]", coefficient_friction); } else if (coefficient_friction == 0) { spdlog::info( "Disabling friction because coefficient of friction is zero"); } std::vector<RigidBody> rbs; bool success = read_rb_scene(params, rbs); if (!success) { spdlog::error("Unable to read rigid body scene!"); return false; } init(rbs); from_json(params["gravity"], gravity); assert(gravity.size() >= dim()); gravity.conservativeResize(dim()); do_intersection_check = params["do_intersection_check"]; return true; } nlohmann::json RigidBodyProblem::settings() const { nlohmann::json json; json["collision_eps"] = collision_eps; json["coefficient_restitution"] = coefficient_restitution; json["coefficient_friction"] = coefficient_friction; json["gravity"] = to_json(gravity); json["do_intersection_check"] = do_intersection_check; return json; } void RigidBodyProblem::init(const std::vector<RigidBody>& rbs) { m_assembler.init(rbs); update_constraints(); for (size_t i = 0; i < num_bodies(); ++i) { auto& rb = m_assembler[i]; spdlog::info( "rb={:d} group_id={:d} mass={:g} inertia={}", i, rb.group_id, rb.mass, fmt_eigen(rb.moment_of_inertia)); } spdlog::info("average_mass={:g}", m_assembler.average_mass); // Compute world diagonal Eigen::MatrixXd V = vertices(); init_bbox_diagonal = (V.colwise().maxCoeff() - V.colwise().minCoeff()).norm(); spdlog::info("init_bbox_diagonal={:g}", init_bbox_diagonal); // Ensure the dimension of gravity matches the dimension of the problem. gravity = gravity.head(dim()); if (detect_intersections(m_assembler.rb_poses_t1())) { spdlog::error("The initial state contains intersections!"); } else { spdlog::info("no intersections found in initial state"); } } nlohmann::json RigidBodyProblem::state() const { nlohmann::json json; std::vector<nlohmann::json> rbs; Eigen::VectorXd p = Eigen::VectorXd::Zero(PoseD::dim_to_pos_ndof(dim())); // Linear momentum Eigen::VectorXd L = Eigen::VectorXd::Zero( PoseD::dim_to_rot_ndof(dim())); // Angular momentum double T = 0.0; // Kinetic energy double G = 0.0; // Potential energy for (auto& rb : m_assembler.m_rbs) { nlohmann::json jrb; jrb["position"] = to_json(Eigen::VectorXd(rb.pose.position)); jrb["rotation"] = to_json(Eigen::VectorXd(rb.pose.rotation)); jrb["linear_velocity"] = to_json(Eigen::VectorXd(rb.velocity.position)); jrb["angular_velocity"] = to_json(Eigen::VectorXd(rb.velocity.rotation)); if (dim() == 3) { jrb["Qdot"] = to_json(rb.Qdot); jrb["Qddot"] = to_json(rb.Qddot); } rbs.push_back(jrb); // momentum p += rb.mass * rb.velocity.position; L += rb.moment_of_inertia.asDiagonal() * rb.velocity.rotation; T += 0.5 * rb.mass * rb.velocity.position.squaredNorm(); T += 0.5 * rb.velocity.rotation.transpose() * rb.moment_of_inertia.asDiagonal() * rb.velocity.rotation; if (!rb.is_dof_fixed[0] && !rb.is_dof_fixed[1]) { G -= rb.mass * gravity.dot(rb.pose.position); } } json["rigid_bodies"] = rbs; json["linear_momentum"] = to_json(p); json["angular_momentum"] = to_json(L); json["kinetic_energy"] = T; json["potential_energy"] = G; return json; } void RigidBodyProblem::state(const nlohmann::json& args) { nlohmann::json json; auto& rbs = args["rigid_bodies"]; assert(rbs.size() == num_bodies()); size_t i = 0; for (auto& jrb : args["rigid_bodies"]) { from_json(jrb["position"], m_assembler[i].pose.position); from_json(jrb["rotation"], m_assembler[i].pose.rotation); from_json(jrb["linear_velocity"], m_assembler[i].velocity.position); from_json(jrb["angular_velocity"], m_assembler[i].velocity.rotation); if (dim() == 3) { if (jrb.contains("Qdot")) { from_json(jrb["Qdot"], m_assembler[i].Qdot); } else { spdlog::warn("Missing field \"Qdot\" in rigid body state!"); m_assembler[i].Qdot.setZero(); } if (jrb.contains("Qddot")) { from_json(jrb["Qddot"], m_assembler[i].Qddot); } else { spdlog::warn("Missing field \"Qddot\" in rigid body state!"); m_assembler[i].Qddot.setZero(); } } i++; } } void RigidBodyProblem::update_dof() { poses_t0 = m_assembler.rb_poses_t0(); x0 = this->poses_to_dofs(poses_t0); num_vars_ = x0.size(); } void RigidBodyProblem::update_constraints() { update_dof(); constraint().initialize(); } void RigidBodyProblem::init_solve() { return solver().init_solve(starting_point()); } OptimizationResults RigidBodyProblem::solve_constraints() { return solver().solve(starting_point()); } OptimizationResults RigidBodyProblem::step_solve() { return solver().step_solve(); } bool RigidBodyProblem::take_step(const Eigen::VectorXd& dof) { //////////////////////////////////////////////////////////////////////// // WARNING: This only assumes an implicit euler velocity update. For // more updates look at the overridden version in // distance_barrier_rb_problem. //////////////////////////////////////////////////////////////////////// // update final pose // ------------------------------------- m_assembler.set_rb_poses(this->dofs_to_poses(dof)); PosesD poses_q1 = m_assembler.rb_poses_t1(); // Update the velocities // This need to be done AFTER updating poses for (RigidBody& rb : m_assembler.m_rbs) { if (rb.type != RigidBodyType::DYNAMIC) { continue; } // Assume linear velocity through the time-step. rb.velocity.position = (rb.pose.position - rb.pose_prev.position) / timestep(); if (dim() == 2) { rb.velocity.rotation = (rb.pose.rotation - rb.pose_prev.rotation) / timestep(); } else { // Compute the rotation R s.t. // R * Rᵗ = Rᵗ⁺¹ → R = Rᵗ⁺¹(Rᵗ)ᵀ Eigen::Matrix3d R = rb.pose.construct_rotation_matrix() * rb.pose_prev.construct_rotation_matrix().transpose(); // TODO: Make sure we did not loose momentum do to π modulus // ω = rotation_vector(R) Eigen::AngleAxisd omega(R); rb.velocity.rotation = omega.angle() / timestep() * rb.R0.transpose() * omega.axis(); // Q̇ = Q[ω] // Q̇ᵗ = (Qᵗ - Qᵗ⁻¹) / h Eigen::Matrix3d Q = rb.pose.construct_rotation_matrix(); Eigen::Matrix3d Qdot = (Q - rb.pose_prev.construct_rotation_matrix()) / timestep(); // Eigen::Matrix3d omega_hat = Q.transpose() * Qdot; // std::cout << omega_hat << std::endl << std::endl; // rb.velocity.rotation.x() = omega_hat(2, 1); // rb.velocity.rotation.y() = omega_hat(0, 2); // rb.velocity.rotation.z() = omega_hat(1, 0); rb.Qdot = Qdot; } rb.velocity.zero_dof(rb.is_dof_fixed, rb.R0); } if (do_intersection_check) { // Check for intersections instead of collision along the entire // step. We only guarentee a piecewise collision-free trajectory. // return detect_collisions(poses_t0, poses_q1, // CollisionCheck::EXACT); return detect_intersections(poses_q1); } return false; } bool RigidBodyProblem::detect_collisions( const PosesD& poses_q0, const PosesD& poses_q1, const CollisionCheck check_type) const { Impacts impacts; double scale = check_type == CollisionCheck::EXACT ? 1.0 : (1.0 + collision_eps); PosesD scaled_pose_q1 = interpolate(poses_q0, poses_q1, scale); constraint().construct_collision_set( m_assembler, poses_q0, scaled_pose_q1, impacts); return impacts.size(); } // Check if the geometry is intersecting bool RigidBodyProblem::detect_intersections(const PosesD& poses) const { if (num_bodies() <= 1) { return false; } PROFILE_POINT("RigidBodyProblem::detect_intersections"); PROFILE_START(); const Eigen::MatrixXd vertices = m_assembler.world_vertices(poses); const Eigen::MatrixXi& edges = this->edges(); const Eigen::MatrixXi& faces = this->faces(); bool is_intersecting = false; if (dim() == 2) { // Need to check segment-segment intersections in 2D assert(vertices.cols() == 2); double inflation_radius = 1e-8; // Conservative broad phase std::vector<std::pair<int, int>> close_bodies = m_assembler.close_bodies(poses, poses, inflation_radius); if (close_bodies.size() == 0) { PROFILE_END(); return false; } RigidBodyHashGrid hashgrid; hashgrid.resize(m_assembler, poses, close_bodies, inflation_radius); hashgrid.addBodies(m_assembler, poses, close_bodies, inflation_radius); const Eigen::VectorXi& vertex_group_ids = group_ids(); auto can_vertices_collide = [&vertex_group_ids](size_t vi, size_t vj) { return vertex_group_ids[vi] != vertex_group_ids[vj]; }; std::vector<EdgeEdgeCandidate> ee_candidates; hashgrid.getEdgeEdgePairs(edges, ee_candidates, can_vertices_collide); for (const EdgeEdgeCandidate& ee_candidate : ee_candidates) { if (igl::predicates::segment_segment_intersect( vertices.row(edges(ee_candidate.edge0_index, 0)).head<2>(), vertices.row(edges(ee_candidate.edge0_index, 1)).head<2>(), vertices.row(edges(ee_candidate.edge1_index, 0)).head<2>(), vertices.row(edges(ee_candidate.edge1_index, 1)) .head<2>())) { is_intersecting = true; break; } } } else { // Need to check segment-triangle intersections in 3D assert(dim() == 3); std::vector<EdgeFaceCandidate> ef_candidates; detect_intersection_candidates_rigid_bvh( m_assembler, poses, ef_candidates); for (const EdgeFaceCandidate& ef_candidate : ef_candidates) { if (is_edge_intersecting_triangle( vertices.row(edges(ef_candidate.edge_index, 0)), vertices.row(edges(ef_candidate.edge_index, 1)), vertices.row(faces(ef_candidate.face_index, 0)), vertices.row(faces(ef_candidate.face_index, 1)), vertices.row(faces(ef_candidate.face_index, 2)))) { is_intersecting = true; break; } } } PROFILE_END(); return is_intersecting; } } // namespace ipc::rigid
33.589532
80
0.606988
[ "geometry", "vector", "3d" ]
b2910fa2d2f9ae048b759934004f548e8da2718f
15,095
cpp
C++
ks/KsEventLoop.cpp
preet/kscore
5460cb12d60f10bb07ca1a7f07b02730b5d94a12
[ "Apache-2.0" ]
3
2015-12-12T01:39:25.000Z
2018-04-24T00:02:16.000Z
ks/KsEventLoop.cpp
preet/kscore
5460cb12d60f10bb07ca1a7f07b02730b5d94a12
[ "Apache-2.0" ]
null
null
null
ks/KsEventLoop.cpp
preet/kscore
5460cb12d60f10bb07ca1a7f07b02730b5d94a12
[ "Apache-2.0" ]
4
2017-01-13T10:07:13.000Z
2018-09-27T06:43:18.000Z
/* Copyright (C) 2015 Preet Desai (preet.desai@gmail.com) 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. */ // stl #include <map> // asio #include <ks/thirdparty/asio/asio.hpp> // ks #include <ks/KsLog.hpp> #include <ks/KsEvent.hpp> #include <ks/KsTask.hpp> #include <ks/KsTimer.hpp> #include <ks/KsEventLoop.hpp> #include <ks/KsException.hpp> namespace ks { // ============================================================= // EventLoopCalledFromWrongThread::EventLoopCalledFromWrongThread(std::string msg) : Exception(ErrorLevel::FATAL,std::move(msg),true) {} EventLoopInactive::EventLoopInactive(std::string msg) : Exception(ErrorLevel::WARN,std::move(msg),true) {} // ============================================================= // std::mutex EventLoop::s_id_mutex; // Start at one so that an Id of 0 // can be considered invalid / unset Id EventLoop::s_id_counter(1); Id EventLoop::genId() { std::lock_guard<std::mutex> lock(s_id_mutex); Id id = s_id_counter; s_id_counter++; return id; } // ============================================================= // struct TimerInfo { TimerInfo(Id id, weak_ptr<Timer> timer, asio::io_service & service, Milliseconds interval_ms, bool repeat) : id(id), timer(timer), interval_ms(interval_ms), asio_timer(service,interval_ms), repeat(repeat), canceled(false) { // empty } Id id; weak_ptr<Timer> timer; Milliseconds interval_ms; asio::steady_timer asio_timer; bool repeat; bool canceled; }; // ============================================================= // class TimeoutHandler { public: TimeoutHandler(shared_ptr<TimerInfo> &timerinfo, bool move) { if(move) { m_timerinfo = std::move(timerinfo); } else { m_timerinfo = timerinfo; } } TimeoutHandler(TimeoutHandler const &other) { m_timerinfo = other.m_timerinfo; } TimeoutHandler(TimeoutHandler && other) { m_timerinfo = std::move(other.m_timerinfo); } void operator()(asio::error_code const &ec) { if((ec == asio::error::operation_aborted) || m_timerinfo->canceled) { // The timer was canceled return; } auto timer = m_timerinfo->timer.lock(); if(!timer) { // The ks::Timer object has been destroyed return; } // If this is a repeating timer, post another timeout if(m_timerinfo->repeat) { TimerInfo * timerinfo = m_timerinfo.get(); timerinfo->asio_timer.expires_from_now( timerinfo->interval_ms); timerinfo->asio_timer.async_wait( TimeoutHandler(m_timerinfo,true)); } else { // mark inactive timer->m_active = false; } // Emit the timeout signal timer->signal_timeout.Emit(); } private: shared_ptr<TimerInfo> m_timerinfo; }; // ============================================================= // class TaskHandler { public: TaskHandler(shared_ptr<Task> task, asio::io_service* service) : m_task(task), m_service(service) { // empty } ~TaskHandler() { // empty } TaskHandler(TaskHandler const &); TaskHandler(TaskHandler&& other) { m_task = std::move(other.m_task); m_service = other.m_service; } void operator()() { m_task->Invoke(); } private: shared_ptr<Task> m_task; asio::io_service* m_service; }; // ============================================================= // class EventHandler { public: EventHandler(unique_ptr<Event> &event, asio::io_service * service) : m_event(std::move(event)), m_service(service) { // empty } ~EventHandler() { // empty } // NOTE: asio requires handlers to be copy constructible, // but we want to force them to be move only (as @event // is not meant to be a shared resource). Apparently a // workaround is to declare but not define the copy // constructor: // http://stackoverflow.com/questions/17211263/... // how-to-trick-boostasio-to-allow-move-only-handlers EventHandler(EventHandler const &other); EventHandler(EventHandler && other) { m_event = std::move(other.m_event); m_service = other.m_service; } void operator()() { auto const ev_type = m_event->GetType(); if(ev_type == Event::Type::Slot) { SlotEvent * ev = static_cast<SlotEvent*>( m_event.get()); ev->Invoke(); } else if(ev_type == Event::Type::BlockingSlot) { BlockingSlotEvent * ev = static_cast<BlockingSlotEvent*>( m_event.get()); ev->Invoke(); } } private: unique_ptr<Event> m_event; asio::io_service * m_service; }; // ============================================================= // // EventLoop implementation struct EventLoop::Impl { Impl() { // empty } asio::io_service m_asio_service; unique_ptr<asio::io_service::work> m_asio_work; }; // ============================================================= // // ============================================================= // EventLoop::EventLoop() : m_id(genId()), m_started(false), m_running(false), m_impl(new Impl()) { // empty } EventLoop::~EventLoop() { this->Stop(); } Id EventLoop::GetId() const { return m_id; } std::thread::id EventLoop::GetThreadId() { std::lock_guard<std::mutex> lock(m_mutex); return m_thread_id; } bool EventLoop::GetStarted() { std::lock_guard<std::mutex> lock(m_mutex); return m_started; } bool EventLoop::GetRunning() { std::lock_guard<std::mutex> lock(m_mutex); return m_running; } void EventLoop::GetState(std::thread::id& thread_id, bool& started, bool& running) { std::lock_guard<std::mutex> lock(m_mutex); thread_id = m_thread_id; started = m_started; running = m_running; } void EventLoop::Start() { std::lock_guard<std::mutex> lock(m_mutex); if(m_started || m_impl->m_asio_work) { return; } m_impl->m_asio_service.reset(); m_impl->m_asio_work.reset( new asio::io_service::work( m_impl->m_asio_service)); this->setActiveThread(); m_started = true; m_cv_started.notify_all(); } void EventLoop::Run() { { std::lock_guard<std::mutex> lock(m_mutex); ensureActiveLoop(); ensureActiveThread(); m_running = true; m_cv_running.notify_all(); } m_impl->m_asio_service.run(); // blocks! std::lock_guard<std::mutex> lock(m_mutex); m_running = false; } void EventLoop::Stop() { std::lock_guard<std::mutex> lock(m_mutex); m_impl->m_asio_work.reset(nullptr); m_impl->m_asio_service.stop(); unsetActiveThread(); m_started = false; m_cv_stopped.notify_all(); } void EventLoop::Wait() { this->waitUntilStopped(); } void EventLoop::ProcessEvents() { { std::lock_guard<std::mutex> lock(m_mutex); ensureActiveLoop(); ensureActiveThread(); } m_impl->m_asio_service.poll(); } void EventLoop::PostEvent(unique_ptr<Event> event) { // Timer events are handled immediately instead of // posting them to the event queue to avoid delaying // their start and end times if(event->GetType() == Event::Type::StartTimer) { this->startTimer( std::unique_ptr<StartTimerEvent>( static_cast<StartTimerEvent*>( event.release()))); } else if(event->GetType() == Event::Type::StopTimer) { this->stopTimer(std::unique_ptr<StopTimerEvent>( static_cast<StopTimerEvent*>( event.release()))); } else { m_impl->m_asio_service.post( EventHandler( event, &(m_impl->m_asio_service))); } } void EventLoop::PostTask(shared_ptr<Task> task) { if(std::this_thread::get_id() == this->GetThreadId()) { // Invoke right away to prevent deadlock in case // the calling thread calls Wait() on the task task->Invoke(); return; } m_impl->m_asio_service.post( TaskHandler( task, &(m_impl->m_asio_service))); } void EventLoop::PostCallback(std::function<void()> callback) { unique_ptr<Event> event = make_unique<SlotEvent>(std::move(callback)); m_impl->m_asio_service.post( EventHandler( event, &(m_impl->m_asio_service))); } void EventLoop::PostStopEvent() { m_impl->m_asio_service.post(std::bind(&EventLoop::Stop,this)); } std::thread EventLoop::LaunchInThread(shared_ptr<EventLoop> event_loop) { std::thread thread( [event_loop] () { event_loop->Start(); event_loop->Run(); }); event_loop->waitUntilRunning(); return thread; } void EventLoop::RemoveFromThread(shared_ptr<EventLoop> event_loop, std::thread &thread, bool post_stop) { if(post_stop) { event_loop->PostStopEvent(); } else { event_loop->Stop(); } thread.join(); } void EventLoop::waitUntilStarted() { std::unique_lock<std::mutex> lock(m_mutex); while(!m_started) { m_cv_started.wait(lock); } } void EventLoop::waitUntilRunning() { std::unique_lock<std::mutex> lock(m_mutex); while(!m_running) { m_cv_running.wait(lock); } } void EventLoop::waitUntilStopped() { std::unique_lock<std::mutex> lock(m_mutex); while(m_started) { m_cv_stopped.wait(lock); } } void EventLoop::setActiveThread() { auto const calling_thread_id = std::this_thread::get_id(); m_thread_id = calling_thread_id; } void EventLoop::ensureActiveThread() { auto const calling_thread_id = std::this_thread::get_id(); // Ensure that the thread is this event loop's // active thread if(m_thread_id != calling_thread_id) { throw EventLoopCalledFromWrongThread( "EventLoop: ProcessEvents/Run called from " "a thread that did not start the event loop"); } } void EventLoop::ensureActiveLoop() { if(!(m_started && m_impl->m_asio_work)) { throw EventLoopInactive( "EventLoop: ProcessEvents/Run called but " "event loop has not been started"); } } void EventLoop::unsetActiveThread() { m_thread_id = m_thread_id_null; } void EventLoop::startTimer(unique_ptr<StartTimerEvent> ev) { // lock because we modify m_list_timers std::unique_lock<std::mutex> lock(m_mutex); auto timer = ev->GetTimer().lock(); if(!timer) { // The timer object was destroyed return; } auto timerinfo_it = m_list_timers.find(ev->GetTimerId()); if(timerinfo_it != m_list_timers.end()) { // If a timer for the given id already exists, erase it timerinfo_it->second->asio_timer.cancel(); timerinfo_it->second->canceled = true; m_list_timers.erase(timerinfo_it); } // Insert a new timer and start it timerinfo_it = m_list_timers.emplace( ev->GetTimerId(), make_shared<TimerInfo>( ev->GetTimerId(), ev->GetTimer(), m_impl->m_asio_service, ev->GetInterval(), ev->GetRepeating())).first; timer->m_active = true; timerinfo_it->second->asio_timer.async_wait( TimeoutHandler(timerinfo_it->second,false)); } void EventLoop::stopTimer(unique_ptr<StopTimerEvent> ev) { // lock because we modify m_list_timers std::unique_lock<std::mutex> lock(m_mutex); // Cancel and remove the timer for the given id auto timerinfo_it = m_list_timers.find(ev->GetTimerId()); if(timerinfo_it == m_list_timers.end()) { return; } auto timer = timerinfo_it->second->timer.lock(); if(timer) { timer->m_active = false; } timerinfo_it->second->asio_timer.cancel(); timerinfo_it->second->canceled = true; m_list_timers.erase(timerinfo_it); } } // ks
26.669611
85
0.499304
[ "object" ]
b29e30214f8f86e25432271431fdb7abb4f876c4
4,989
cpp
C++
hackathon/xiaoxiaol/consensus_skeleton_2/kd-tree.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/xiaoxiaol/consensus_skeleton_2/kd-tree.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
hackathon/xiaoxiaol/consensus_skeleton_2/kd-tree.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
#include "kd-tree.h" #include "color_xyz.h" using namespace std; ANNkd_tree *nt_to_kdt(NeuronTree nt, int nPts) { const int dim = 3; ANNpointArray kd_pts = annAllocPts(nPts, dim); //add all points from the neuron tree to the ANN point array for (int m = 0; m < nPts; ++m) { //hard-coded for 3D kd_pts[m][0] = nt.listNeuron[m].x; kd_pts[m][1] = nt.listNeuron[m].y; kd_pts[m][2] = nt.listNeuron[m].z; } return new ANNkd_tree(kd_pts, nPts, dim); } double kd_correspondingPointFromNeuron( XYZ pt, NeuronTree * p_nt, ANNkd_tree *kd, XYZ & closest_p) { double min_dist = LONG_MAX; closest_p.x = -1; closest_p.y = -1; closest_p.z = -1; const int dim = 3; ANNpoint queryPt = annAllocPt(dim); queryPt[0] = pt.x; queryPt[1] = pt.y; queryPt[2] = pt.z; //if tree only has one point, just return that point if (kd->nPoints() < 2) { closest_p = p_nt->listNeuron.at(0); return dist_L2(closest_p, pt); } int k = 2; //neighbors to find ANNidxArray nIdx = new ANNidx[k]; ANNdistArray dist = new ANNdist[k]; kd->annkSearch(queryPt, k, nIdx, dist, 0); int closest1 = nIdx[0]; int closest2 = nIdx[1]; QHash<int, int> h =p_nt->hashNeuron; NeuronSWC *tp1, *tp2; //check c_node1 and parent tp1 = (NeuronSWC *)(&(p_nt->listNeuron.at(closest1))); if (tp1->pn < 0 ) //if root { min_dist =dist_L2( XYZ(tp1->x,tp1->y,tp1->z), pt); closest_p = XYZ(tp1->x,tp1->y,tp1->z); } else { tp2 = (NeuronSWC *)(&(p_nt->listNeuron.at(h.value(tp1->pn)))); //use hash table XYZ c_p; min_dist = dist_pt_to_line_seg(pt, XYZ(tp1->x,tp1->y,tp1->z), XYZ(tp2->x,tp2->y,tp2->z),c_p); closest_p = c_p; } //check if c_node2 and parent are closer tp1 = (NeuronSWC *)(&(p_nt->listNeuron.at(closest2))); if (tp1->pn < 0 ) //if root { double sec_dist =dist_L2( XYZ(tp1->x,tp1->y,tp1->z), pt); if (sec_dist < min_dist) { min_dist = sec_dist; closest_p = XYZ(tp1->x,tp1->y,tp1->z); } } else { tp2 = (NeuronSWC *)(&(p_nt->listNeuron.at(h.value(tp1->pn)))); //use hash table //now compute the distance between the pt and the current segment XYZ c_p; double cur_d = dist_pt_to_line_seg(pt, XYZ(tp1->x,tp1->y,tp1->z), XYZ(tp2->x,tp2->y,tp2->z),c_p); //now find the min distance if (min_dist > cur_d){ min_dist = cur_d; closest_p = c_p; } } delete [] nIdx; delete [] dist; return min_dist; } double kd_correspondingNodeFromNeuron(XYZ pt, QList<NeuronSWC> listNodes, int &closestNodeIdx, ANNkd_tree * kd, int TYPE_MERGED) { double min_dist = LONG_MAX; closestNodeIdx = -1; const int dim = 3; ANNpoint queryPt = annAllocPt(dim); queryPt[0] = pt.x; queryPt[1] = pt.y; queryPt[2] = pt.z; NeuronSWC tp; bool found = false; int k = 4; int cur = 0; while (!found && (k <= listNodes.size())) { ANNidxArray nIdx = new ANNidx[k]; ANNdistArray dist = new ANNdist[k]; kd->annkSearch(queryPt, k, nIdx, dist, 0); int id; //are any of the nodes found not merged while (cur < k) { id = nIdx[cur]; tp = listNodes.at(id); if (tp.type != TYPE_MERGED) { found = true; min_dist = sqrt(dist[cur]); //cout << "setting node idx to " << id << endl; closestNodeIdx = id; break; } //if merged, check distance for cutoff point - since sorted can exit when reach a node further if (sqrt(dist[cur]) > 1.0) { found = true; break; } cur++; } k = 2 * k; //num of neighbors to look for delete [] nIdx; delete [] dist; } return min_dist; } double dist_pt_to_line_seg(const XYZ p0, const XYZ p1, const XYZ p2, XYZ & closestPt) //p1 and p2 are the two ends of the line segment, and p0 the point { if (p1==p2) { closestPt = p1; return norm(p0-p1); } else if (p0==p1 || p0==p2) { closestPt = p0; return 0.0; } XYZ d12 = p2-p1; XYZ d01 = p1-p0; float v01 = dot(d01, d01); float v12 = dot(d12, d12); float d012 = dot(d12, d01); float t = -d012/v12; if (t<0 || t>1) //then no intersection within the lineseg { double d01 = dist_L2(p0, p1); double d02 = dist_L2(p0, p2); if (d01<d02){ closestPt=XYZ(p1.x,p1.y,p1.z); return d01; } else { closestPt=XYZ(p2.x,p2.y,p2.z); return d02; } } else {//intersection XYZ xpt(p1.x+d12.x*t, p1.y+d12.y*t, p1.z+d12.z*t); closestPt=xpt; return dist_L2(xpt, p0); } }
25.454082
152
0.538384
[ "3d" ]
b2a81bf65bb9df8175de3f09dce2c0cd5a13d88b
20,243
cpp
C++
IntervalManagement/IMKinematicTimeBasedMaintain.cpp
mitre/im_sample_algorithm
c49038f56faf05e15484ac9b01526fd6a0a8169f
[ "Apache-2.0" ]
null
null
null
IntervalManagement/IMKinematicTimeBasedMaintain.cpp
mitre/im_sample_algorithm
c49038f56faf05e15484ac9b01526fd6a0a8169f
[ "Apache-2.0" ]
8
2020-01-27T14:12:50.000Z
2021-08-10T14:41:41.000Z
IntervalManagement/IMKinematicTimeBasedMaintain.cpp
mitre/im_sample_algorithm
c49038f56faf05e15484ac9b01526fd6a0a8169f
[ "Apache-2.0" ]
1
2019-11-07T08:31:17.000Z
2019-11-07T08:31:17.000Z
// **************************************************************************** // NOTICE // // This is the copyright work of The MITRE Corporation, and was produced // for the U. S. Government under Contract Number DTFAWA-10-C-00080, and // is subject to Federal Aviation Administration Acquisition Management // System Clause 3.5-13, Rights In Data-General, Alt. III and Alt. IV // (Oct. 1996). No other use other than that granted to the U. S. // Government, or to those acting on behalf of the U. S. Government, // under that Clause is authorized without the express written // permission of The MITRE Corporation. For further information, please // contact The MITRE Corporation, Contracts Office, 7515 Colshire Drive, // McLean, VA 22102-7539, (703) 983-6000. // // Copyright 2020 The MITRE Corporation. All Rights Reserved. // **************************************************************************** #include <numeric> #include <aaesim/Bada.h> #include "public/SimulationTime.h" #include "imalgs/IMKinematicTimeBasedMaintain.h" #include "public/AircraftCalculations.h" #include "math/CustomMath.h" #include "public/CoreUtils.h" #include "imalgs/IMScenario.h" log4cplus::Logger IMKinematicTimeBasedMaintain::logger = log4cplus::Logger::getInstance( LOG4CPLUS_TEXT("IMKinematicTimeBasedMaintain")); IMKinematicTimeBasedMaintain::IMKinematicTimeBasedMaintain() { m_stage_of_im_operation = MAINTAIN; } IMKinematicTimeBasedMaintain::~IMKinematicTimeBasedMaintain() = default; Guidance IMKinematicTimeBasedMaintain::Update(const DynamicsState &dynamics_state, const AircraftState &ownship_aircraft_state, const AircraftState &target_aircraft_state_projected_asg_adjusted, const KinematicTrajectoryPredictor &ownship_kinematic_trajectory_predictor, const Guidance &guidance_in, const vector<AircraftState> &target_aircraft_state_history, const AchievePointCalcs &ownship_achieve_point_calcs, const AchievePointCalcs &traffic_reference_point_calcs, PilotDelay &pilot_delay_model, const Units::Length &target_kinematic_dtg_to_end_of_route) { /* * Developer's note: In this level of the algorithm, all uses of the /target state/ * must be projected onto ownship's route prior to use. This includes all items * in the targethistory vector (they have not already been projected). Some lower * level algorithms carry this load automatically */ Guidance guidanceout = guidance_in; guidanceout.SetValid(true); Units::MetersLength tmpdist; m_ownship_decrementing_distance_calculator.CalculateAlongPathDistanceFromPosition( Units::FeetLength(ownship_aircraft_state.m_x), Units::FeetLength(ownship_aircraft_state.m_y), tmpdist); const Units::Length ownship_true_dtg = tmpdist; // This will give us a state projected onto ownship's h-path // NOTE: targetin has already been projected. We only need the distance // calculation here. But we must use projectTargetPos() to get protection // against being off the back of the horizontal path. Units::Length targetProjectedX = Units::zero(); Units::Length targetProjectedY = Units::zero(); const bool foundProjectedPos = IMUtils::ProjectTargetPosition( Units::FeetLength(target_aircraft_state_projected_asg_adjusted.m_x), Units::FeetLength(target_aircraft_state_projected_asg_adjusted.m_y), ownship_kinematic_trajectory_predictor.GetHorizontalPath(), targetProjectedX, targetProjectedY, tmpdist); const Units::Length target_projected_dtg = tmpdist; bool storespacingerror = true; const Units::Speed targetvelocity = target_aircraft_state_projected_asg_adjusted.GetGroundSpeed(); Units::Time spacingerrorformaintainstats = Units::zero(); Units::Time target_crossing_time = Units::zero(); m_measured_spacing_interval = Units::NegInfinity(); Units::Length projected_x; Units::Length projected_y; if (!target_aircraft_state_history.empty()) { vector<AircraftState> history = target_aircraft_state_history; if (history.back().m_time < target_aircraft_state_projected_asg_adjusted.m_time) { // This is an edge case. The incoming state was extrapolated to get to the current // time. In this case, the history vector needs to have this extrapolated state also // in order for GetCrossingTime to operate consistently with this method. history.push_back(target_aircraft_state_projected_asg_adjusted); } storespacingerror = IMUtils::GetCrossingTime(ownship_true_dtg, history, m_ownship_distance_calculator, target_crossing_time, projected_x, projected_y); if (!storespacingerror) { LOG4CPLUS_WARN(IMKinematicTimeBasedMaintain::logger, "update ac " << ownship_aircraft_state.m_id << " time " << ownship_aircraft_state.m_time << std::endl << "Bad target crossing time computing spacing error for maintain stats" << std::endl); } else { spacingerrorformaintainstats = Units::SecondsTime(ownship_aircraft_state.m_time) - target_crossing_time - m_im_clearance.GetAssignedTimeSpacingGoal(); m_measured_spacing_interval = Units::SecondsTime(ownship_aircraft_state.m_time) - target_crossing_time; } } if (m_ownship_reference_lookup_index == -1) { m_ownship_reference_lookup_index = static_cast<int>( ownship_kinematic_trajectory_predictor.GetVerticalPathDistances().size() - 1); } // if target distance is inside the range of the precalculated trajectory, use that to find the precalc index for the +- 10% calculation if (target_aircraft_state_projected_asg_adjusted.m_id != IMUtils::UNINITIALIZED_AIRCRAFT_ID && foundProjectedPos) { if (Units::abs(ownship_true_dtg) <= Units::abs(Units::MetersLength(ownship_kinematic_trajectory_predictor.GetVerticalPathDistances().back()))) { // Compute precalculated index from own descent and current distance. m_ownship_reference_lookup_index = CoreUtils::FindNearestIndex(Units::MetersLength(ownship_true_dtg).value(), ownship_kinematic_trajectory_predictor.GetVerticalPathDistances()); if (m_ownship_reference_lookup_index > ownship_kinematic_trajectory_predictor.GetVerticalPathDistances().size() - 1) { m_ownship_reference_lookup_index = static_cast<int>( ownship_kinematic_trajectory_predictor.GetVerticalPathDistances().size() - 1); } } else { guidanceout.SetValid(false); } } else { guidanceout.SetValid(false); } if (guidanceout.IsValid()) { if (!target_aircraft_state_history.empty()) { InternalObserver::getInstance()->updateFinalGS(target_aircraft_state_projected_asg_adjusted.m_id, Units::MetersPerSecondSpeed( AircraftCalculations::GsAtACS( target_aircraft_state_history.back())).value()); InternalObserver::getInstance()->updateFinalGS(ownship_aircraft_state.m_id, Units::MetersPerSecondSpeed( AircraftCalculations::GsAtACS(ownship_aircraft_state)).value()); if (m_previous_reference_im_speed_command_tas == Units::zero()) { m_previous_reference_im_speed_command_tas = m_weather_prediction.getAtmosphere()->CAS2TAS( Units::MetersPerSecondSpeed( ownship_kinematic_trajectory_predictor.GetVerticalPathVelocities().back()), Units::MetersLength(ownship_kinematic_trajectory_predictor.GetVerticalPathAltitudes().back())); m_previous_im_speed_command_ias = Units::MetersPerSecondSpeed( ownship_kinematic_trajectory_predictor.GetVerticalPathVelocities().back()); m_previous_reference_im_speed_command_mach = Units::MetersPerSecondSpeed(m_previous_reference_im_speed_command_tas).value() / sqrt(GAMMA * R.value() * m_weather_prediction.getAtmosphere()->GetTemperature( Units::MetersLength( ownship_kinematic_trajectory_predictor.GetVerticalPathAltitudes().back())).value()); } if (InternalObserver::getInstance()->GetRecordMaintainMetrics()) { if (Units::abs(ownship_true_dtg) < ownship_achieve_point_calcs.GetDistanceFromWaypoint()) { MaintainMetric &maintain_metric = InternalObserver::getInstance()->GetMaintainMetric( ownship_aircraft_state.m_id); if (storespacingerror) { maintain_metric.AddSpacingErrorSec( Units::SecondsTime(spacingerrorformaintainstats).value()); } if (!maintain_metric.TimeAtAbpRecorded()) { maintain_metric.SetTimeAtAbp( ownship_aircraft_state.m_time); } maintain_metric.ComputeTotalMaintainTime( ownship_aircraft_state.m_time); } } } Units::Speed gscommand = targetvelocity + (ownship_true_dtg - target_projected_dtg) * m_maintain_control_gain; Units::Speed tascommand = sqrt(Units::sqr(gscommand - Units::MetersPerSecondSpeed(ownship_aircraft_state.m_Vw_para)) + Units::sqr(Units::MetersPerSecondSpeed(ownship_aircraft_state.m_Vw_perp))) / cos(ownship_aircraft_state.m_gamma); m_previous_reference_im_speed_command_tas = tascommand; // remember the speed command if (tascommand < Units::zero()) { tascommand = Units::zero(); } m_im_speed_command_ias = m_weather_prediction.getAtmosphere()->TAS2CAS(tascommand, Units::FeetLength( ownship_aircraft_state.m_z)); m_unmodified_im_speed_command_ias = m_im_speed_command_ias; if (guidanceout.GetSelectedSpeed().GetSpeedType() == INDICATED_AIR_SPEED) { CalculateIas(Units::FeetLength(ownship_aircraft_state.m_z), dynamics_state, ownship_kinematic_trajectory_predictor, pilot_delay_model); } else { CalculateMach(Units::FeetLength(ownship_aircraft_state.m_z), tascommand, ownship_kinematic_trajectory_predictor, pilot_delay_model); } m_previous_im_speed_command_ias = m_im_speed_command_ias; if (InternalObserver::getInstance()->GetScenarioIter() >= 0) { InternalObserver::getInstance()->IM_command_output(ownship_aircraft_state.m_id, ownship_aircraft_state.m_time, ownship_aircraft_state.m_z, Units::MetersPerSecondSpeed( dynamics_state.v_true_airspeed).value(), Units::MetersPerSecondSpeed( ownship_aircraft_state.GetGroundSpeed()).value(), Units::MetersPerSecondSpeed(m_im_speed_command_ias).value(), Units::MetersPerSecondSpeed( m_unmodified_im_speed_command_ias).value(), Units::MetersPerSecondSpeed(tascommand).value(), Units::MetersPerSecondSpeed(targetvelocity).value(), Units::MetersLength(-target_projected_dtg).value(), Units::MetersLength(-ownship_true_dtg).value(), Units::MetersLength(ownship_true_dtg).value()); } if (pilot_delay_model.IsPilotDelayOn()) { guidanceout.m_ias_command = m_im_speed_command_with_pilot_delay; if (guidanceout.GetSelectedSpeed().GetSpeedType() == MACH_SPEED) { const auto true_airspeed_equivalent = m_weather_prediction.CAS2TAS(m_im_speed_command_ias, ownship_aircraft_state.GetPositionZ()); const auto mach_equivalent = m_weather_prediction.TAS2Mach(true_airspeed_equivalent, ownship_aircraft_state.GetPositionZ()); guidanceout.SetMachCommand(mach_equivalent); } } else { guidanceout.m_ias_command = m_im_speed_command_ias; if (guidanceout.GetSelectedSpeed().GetSpeedType() == MACH_SPEED) { guidanceout.SetMachCommand(m_previous_reference_im_speed_command_mach); } } if (InternalObserver::getInstance()->outputNM()) { NMObserver &nm_observer = InternalObserver::getInstance()->GetNMObserver(ownship_aircraft_state.m_id); if (nm_observer.curr_NM == -2 && guidanceout.IsValid()) { nm_observer.curr_NM = static_cast<int>(std::fabs(Units::NauticalMilesLength(-ownship_true_dtg).value())); } if (Units::abs(ownship_true_dtg) <= Units::NauticalMilesLength(nm_observer.curr_NM) && guidanceout.IsValid()) { --nm_observer.curr_NM; double lval = LowLimit(ownship_kinematic_trajectory_predictor.GetVerticalPathVelocityByIndex( m_ownship_reference_lookup_index)); double hval = HighLimit(ownship_kinematic_trajectory_predictor.GetVerticalPathVelocityByIndex( m_ownship_reference_lookup_index)); double ltas = Units::MetersPerSecondSpeed( m_weather_prediction.getAtmosphere()->CAS2TAS(Units::MetersPerSecondSpeed(lval), Units::FeetLength(ownship_aircraft_state.m_z))).value(); double htas = Units::MetersPerSecondSpeed( m_weather_prediction.getAtmosphere()->CAS2TAS(Units::MetersPerSecondSpeed(hval), Units::FeetLength(ownship_aircraft_state.m_z))).value(); nm_observer.output_NM_values( Units::MetersLength(ownship_true_dtg).value(), Units::MetersLength(-ownship_true_dtg).value(), ownship_aircraft_state.m_time, Units::MetersPerSecondSpeed(m_im_speed_command_ias).value(), Units::MetersPerSecondSpeed(ownship_aircraft_state.GetGroundSpeed()).value(), Units::MetersPerSecondSpeed(target_aircraft_state_projected_asg_adjusted.GetGroundSpeed()).value(), lval, hval, ltas, htas); } } } return guidanceout; } void IMKinematicTimeBasedMaintain::CalculateIas(const Units::Length current_ownship_altitude, const DynamicsState &dynamics_state, const KinematicTrajectoryPredictor &ownship_kinematic_trajectory_predictor, PilotDelay &pilot_delay) { BadaWithCalc &bada_calculator = ownship_kinematic_trajectory_predictor.GetKinematicDescent4dPredictor()->m_bada_calculator; Units::Speed rf_leg_limit_speed = Units::zero(); if (m_has_rf_leg) { rf_leg_limit_speed = GetRFLegSpeedLimit(Units::MetersLength( ownship_kinematic_trajectory_predictor.GetVerticalPathDistanceByIndex(m_ownship_reference_lookup_index))); } m_im_speed_command_ias = LimitImSpeedCommand(m_im_speed_command_ias, ownship_kinematic_trajectory_predictor.GetVerticalPathVelocityByIndex( m_ownship_reference_lookup_index), Units::zero(), bada_calculator, current_ownship_altitude, dynamics_state.m_flap_configuration, rf_leg_limit_speed); if (m_im_speed_command_ias != m_previous_im_speed_command_ias) { m_total_number_of_im_speed_changes++; } if (pilot_delay.IsPilotDelayOn()) { m_im_speed_command_with_pilot_delay = pilot_delay.UpdateIAS(m_previous_im_speed_command_ias, m_im_speed_command_ias, current_ownship_altitude, ownship_kinematic_trajectory_predictor.GetAltitudeAtFinalWaypoint()); } } void IMKinematicTimeBasedMaintain::CalculateMach(const Units::Length current_ownship_altitude, const Units::Speed true_airspeed_command, const KinematicTrajectoryPredictor &ownship_kinematic_trajectory_predictor, PilotDelay &pilot_delay) { BadaWithCalc &bada_calculator = ownship_kinematic_trajectory_predictor.GetKinematicDescent4dPredictor()->m_bada_calculator; // Make sure velocity is within nominal limits (AAES-694) Units::Speed nominal_profile_ias = Units::MetersPerSecondSpeed( ownship_kinematic_trajectory_predictor.GetVerticalPathVelocityByIndex(m_ownship_reference_lookup_index)); Units::Speed nominal_profile_tas = m_weather_prediction.getAtmosphere()->CAS2TAS(nominal_profile_ias, current_ownship_altitude); double estimated_mach = Units::MetersPerSecondSpeed(true_airspeed_command).value() / sqrt(GAMMA * R.value() * m_weather_prediction.getAtmosphere()->GetTemperature(current_ownship_altitude).value()); double nominal_mach = Units::MetersPerSecondSpeed(nominal_profile_tas).value() / sqrt(GAMMA * R.value() * m_weather_prediction.getAtmosphere()->GetTemperature(current_ownship_altitude).value()); estimated_mach = LimitImMachCommand(estimated_mach, nominal_mach, bada_calculator, current_ownship_altitude); if (estimated_mach != m_previous_reference_im_speed_command_mach) { m_total_number_of_im_speed_changes++; } if (pilot_delay.IsPilotDelayOn()) { m_im_speed_command_with_pilot_delay = pilot_delay.UpdateMach(m_previous_reference_im_speed_command_mach, estimated_mach, current_ownship_altitude, ownship_kinematic_trajectory_predictor.GetAltitudeAtFinalWaypoint()); } m_previous_reference_im_speed_command_mach = estimated_mach; m_im_speed_command_ias = m_weather_prediction.getAtmosphere()->MachToIAS(estimated_mach, current_ownship_altitude); } void IMKinematicTimeBasedMaintain::IterationReset() { IMMaintain::IterationReset(); m_measured_spacing_interval = Units::NegInfinity(); } void IMKinematicTimeBasedMaintain::DumpParameters(const std::string &parameters_to_print) { IMMaintain::DumpParameters(parameters_to_print); }
56.074792
147
0.624315
[ "vector" ]
b2accd5334da142c4c8be7a814e48ec34ca9fd0a
1,329
cpp
C++
gdip/core/src/opendubins/dubins3D.cpp
jarajanos/gdip
5b56268d8eef2b2a845e3e1433ffa2b1f09b7726
[ "BSD-2-Clause" ]
null
null
null
gdip/core/src/opendubins/dubins3D.cpp
jarajanos/gdip
5b56268d8eef2b2a845e3e1433ffa2b1f09b7726
[ "BSD-2-Clause" ]
null
null
null
gdip/core/src/opendubins/dubins3D.cpp
jarajanos/gdip
5b56268d8eef2b2a845e3e1433ffa2b1f09b7726
[ "BSD-2-Clause" ]
null
null
null
/** * @file dubins3D.cpp * @author Jaroslav Janos (janosjar@fel.cvut.cz) * @brief * @version 1.0 * @date 04. 02. 2022 * * @copyright Copyright (c) 2022 * */ #include "dubins3D.h" namespace opendubins { Dubins3D::Dubins3D() : radiusMin{GDIP_NAN}, maxPitch{GDIP_NAN}, minPitch{GDIP_NAN}, length{std::numeric_limits<double>::max()} { } Dubins3D::~Dubins3D() { } bool Dubins3D::check() { return false; } State3D Dubins3D::getState(double len) const { State lonState{this->path.DubinsLon.getState(len)}; double latLen{lonState.getPoint().getX()}; State latState{this->path.DubinsLat.getState(latLen)}; return State3D(latState.getPoint().getX(), latState.getPoint().getY(), lonState.getPoint().getY(), latState.getAngle(), lonState.getAngle()); } StateAtDistance<State3D> Dubins3D::getClosestStateAndDistance(const Point &p) const { throw "Not implemented!"; return StateAtDistance<State3D>(); } std::ostream &operator<<(std::ostream &os, const Dubins3D &d) { os << "Dubins maneuver 3D, horizontal maneuver: " << d.path.DubinsLat \ << ",\nvertical maneuver: " << d.path.DubinsLon << ",\ntotal length: " << d.length << '\n'; return os; } } // namespace opendubins
26.058824
95
0.62152
[ "3d" ]
b2af6a6b0f249fc98e89b9f0d2c3eb07c20da5e8
1,357
hpp
C++
src/Record.hpp
ddovod/libkvs
81497d95541a1581bdeefd68b55ede61e8b6683c
[ "MIT" ]
null
null
null
src/Record.hpp
ddovod/libkvs
81497d95541a1581bdeefd68b55ede61e8b6683c
[ "MIT" ]
null
null
null
src/Record.hpp
ddovod/libkvs
81497d95541a1581bdeefd68b55ede61e8b6683c
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <vector> #include "ValueType.hpp" namespace kvs { /** A low level value record. */ class Record { public: Record() = default; Record(ValueType valueType, const std::vector<uint8_t>& rawValue, int64_t creationTimestampMs, int64_t expirationTimestampMs) : m_valueType(valueType) , m_rawValue(rawValue) , m_creationTimestampMs(creationTimestampMs) , m_expirationTimestampMs(expirationTimestampMs) { } /** Returns the type of the value. */ ValueType getValueType() const { return m_valueType; } /** Returns the byte array which stores the value. */ const std::vector<uint8_t>& getRawValue() const { return m_rawValue; } /** Returns the timestamp of the value creation, in milliseconds. */ int64_t getCreationTimestampMs() const { return m_creationTimestampMs; } /** Returns the timestamp of the value expiration, in milliseconds. */ int64_t getExpirationTimestampMs() const { return m_expirationTimestampMs; } private: ValueType m_valueType = ValueType::kUndefined; std::vector<uint8_t> m_rawValue; int64_t m_creationTimestampMs = 0; int64_t m_expirationTimestampMs = 0; }; }
30.155556
84
0.638909
[ "vector" ]
b2b18de79bb23154461fc593fcf922a57b0ac6eb
4,612
cc
C++
src/renderer/renderer.cc
DoCGameDev/RPG-Engine
a2553f25c801816e37a3499c39f9ed2d15a32f39
[ "MIT" ]
1
2019-04-22T09:09:53.000Z
2019-04-22T09:09:53.000Z
src/renderer/renderer.cc
JamesLinus/RPG-Engine
a2553f25c801816e37a3499c39f9ed2d15a32f39
[ "MIT" ]
null
null
null
src/renderer/renderer.cc
JamesLinus/RPG-Engine
a2553f25c801816e37a3499c39f9ed2d15a32f39
[ "MIT" ]
1
2016-03-07T12:19:20.000Z
2016-03-07T12:19:20.000Z
// This file is part of the :(){ :|:& };:'s project // Licensing information can be found in the LICENSE file // (C) 2014 :(){ :|:& };:. All rights reserved. #include "sys/common.h" // ----------------------------------------------------------------------------- CVar Renderer::vpWidth("vpWidth", CVAR_INT, "800", "Width of the viewport"); CVar Renderer::vpHeight("vpHeight", CVAR_INT, "600", "Height of the viewport"); CVar Renderer::vpReload("vpReload", CVAR_BOOL, "true", "Rebuild buffers"); // ----------------------------------------------------------------------------- // Implementation of the renderer // ----------------------------------------------------------------------------- class RendererImpl : public Renderer { public: RendererImpl(); void Init(); void Destroy(); void Run(); void Frame(); rbBuffer_t *SwapBuffers(); private: void RenderSprite(rbSprite_t *sprite); void RenderDynMesh(rbDynMesh_t *mesh); rbBuffer_t buffers[2]; rbBuffer_t *front; rbBuffer_t *back; Signal *frontSignal; Signal *backSignal; union { Program *programs[2]; struct { Program *p_sprite; Program *p_dyn_mesh; }; }; union { GLuint textures[10]; }; }; // ----------------------------------------------------------------------------- static RendererImpl rendererImpl; Renderer *renderer = &rendererImpl; // ----------------------------------------------------------------------------- RendererImpl::RendererImpl() : front(&buffers[0]) , back(&buffers[1]) { memset(programs, 0, sizeof(programs)); memset(textures, 0, sizeof(textures)); buffers[0].index = 0; buffers[1].index = 1; } // ----------------------------------------------------------------------------- void RendererImpl::Init() { frontSignal = threadMngr->CreateSignal(); backSignal = threadMngr->CreateSignal(); struct { const char *name; struct { const char *file; GLenum type; } src[10]; } desc[] = { { "sprite", { { "assets/shader/sprite.vs.glsl", GL_VERTEX_SHADER }, { "assets/shader/sprite.fs.glsl", GL_FRAGMENT_SHADER } } }, { "dyn_mesh", { { "assets/shader/dyn_mesh.vs.glsl", GL_VERTEX_SHADER }, { "assets/shader/dyn_mesh.fs.glsl", GL_FRAGMENT_SHADER } } } }; for (size_t i = 0; i < sizeof(desc) / sizeof(desc[0]); ++i) { programs[i] = new Program(desc[i].name); for (size_t j = 0; desc[i].src[j].file; ++j) { programs[i]->Compile(desc[i].src[j].file, desc[i].src[j].type); } programs[i]->Link(); } glGenTextures(sizeof(textures) / sizeof(textures[0]), textures); } // ----------------------------------------------------------------------------- void RendererImpl::Destroy() { glDeleteTextures(sizeof(textures) / sizeof(textures[0]), textures); for (size_t i = 0; i < sizeof(programs) / sizeof(programs[0]); ++i) { if (programs[i]) { delete programs[i]; programs[i] = NULL; } } } // ----------------------------------------------------------------------------- void RendererImpl::Frame() { backSignal->Wait(); glViewport(0, 0, vpWidth.GetInt(), vpHeight.GetInt()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); vpReload.ClearModified(); // Render sprites p_sprite->Bind(); p_sprite->Uniform("u_proj", front->camProj); p_sprite->Uniform("u_view", front->camView); for (size_t i = 0; i < front->spriteCount; ++i) { RenderSprite(&front->sprite[i]); } // Render dynamic meshes p_dyn_mesh->Bind(); p_dyn_mesh->Uniform("u_proj", front->camProj); p_dyn_mesh->Uniform("u_view", front->camView); for (size_t i = 0; i < front->dynMeshCount; ++i) { RenderDynMesh(&front->dynMesh[i]); } frontSignal->Notify(); } // ----------------------------------------------------------------------------- rbBuffer_t *RendererImpl::SwapBuffers() { rbBuffer_t *tmp; frontSignal->Wait(); tmp = front; front = back; back = tmp; backSignal->Notify(); return back; } // ----------------------------------------------------------------------------- void RendererImpl::RenderSprite(rbSprite_t *sprite) { } // ----------------------------------------------------------------------------- void RendererImpl::RenderDynMesh(rbDynMesh_t *mesh) { glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 32, mesh->vertData); glDrawArrays(GL_TRIANGLES, 0, mesh->vertCount); glDisableClientState(GL_VERTEX_ARRAY); }
24.795699
80
0.501518
[ "mesh", "render" ]
b2b88b15232c55f8c13f9e8b55757aad31106972
21,928
cpp
C++
src/spec_miaf_brands.cpp
y-guyon/ComplianceWarden
7315f1266b083a1cd958eae9ce7c8f07a8a6ad2d
[ "BSD-3-Clause" ]
3
2020-01-02T17:30:16.000Z
2021-09-27T18:32:18.000Z
src/spec_miaf_brands.cpp
y-guyon/ComplianceWarden
7315f1266b083a1cd958eae9ce7c8f07a8a6ad2d
[ "BSD-3-Clause" ]
34
2020-01-22T01:41:22.000Z
2021-12-09T13:20:33.000Z
src/spec_miaf_brands.cpp
y-guyon/ComplianceWarden
7315f1266b083a1cd958eae9ce7c8f07a8a6ad2d
[ "BSD-3-Clause" ]
2
2020-11-05T01:41:08.000Z
2021-11-19T13:12:35.000Z
#include "spec.h" #include "fourcc.h" #include <algorithm> // std::find #include <cstring> #include <map> bool isVisualSampleEntry(uint32_t fourcc); bool checkRuleSection(const SpecDesc& spec, const char* section, Box const& root); const std::initializer_list<RuleDesc> getRulesMiafBrands(const SpecDesc& spec) { static const SpecDesc& globalSpec = spec; static const std::initializer_list<RuleDesc> rulesBrands = { { "Section 10.2\n" "'MiPr' in the compatible_brands in the FileTypeBox specifies that a file\n" "conforming to 'miaf' brand also conforms to the following constraints:\n" "- The MetaBox shall follow the FileTypeBox. There shall be no intervening boxes\n" " between the FileTypeBox and the MetaBox except at most one BoxFileIndexBox.\n" "- The MediaDataBox shall not occur before the MetaBox.\n" "- At most one top-level FreeSpaceBox is allowed, which, if present, shall be\n" " between the MetaBox and the MediaDataBox. There shall be no other top-level\n" " FreeSpaceBox in the file.\n" "- The primary image item conforms to a MIAF profile.\n" "- There is at least one MIAF thumbnail image item present for the primary image\n" " item and the coded data for the thumbnail image items precede in file order\n" " the coded data for the primary item.\n" "- The maximum number of bytes from the beginning of the file to the last byte\n" " of the coded data for at least one of the thumbnail images of the primary\n" " item, or the primary item itself, is 128 000 bytes.", [] (Box const& root, IReport* out) { bool found = false; for(auto& box : root.children) if(box.fourcc == FOURCC("ftyp")) for(auto& sym : box.syms) if(!strcmp(sym.name, "compatible_brand")) if(sym.value == FOURCC("MiPr")) found = true; if(!found) return; auto boxOrderCheck = [&] () -> bool { if(root.children.size() < 2) return false; if(root.children[0].fourcc != FOURCC("ftyp")) return false; if(root.children[1].fourcc == FOURCC("meta")) return true; else if(root.children.size() >= 3 && root.children[1].fourcc == FOURCC("fidx") && root.children[2].fourcc == FOURCC("meta")) return true; else return false; }; if(!boxOrderCheck()) out->error("'MiPr' brand: the MetaBox shall follow the FileTypeBox (with at most one intervening BoxFileIndexBox)"); for(auto& b : root.children) { if(b.fourcc == FOURCC("mdat")) out->error("'MiPr' brand: the MediaDataBox shall not occur before the MetaBox"); if(b.fourcc == FOURCC("meta")) break; } int numFreeSpaceBox = 0; bool seenMeta = false; for(auto& b : root.children) { if(b.fourcc == FOURCC("mdat")) break; if(b.fourcc == FOURCC("meta")) seenMeta = true; if(b.fourcc == FOURCC("free")) { numFreeSpaceBox++; if(!seenMeta) out->error("'MiPr' brand: top-level FreeSpaceBox shall be between the MetaBox and the MediaDataBox"); } } if(numFreeSpaceBox > 1) out->error("'MiPr' brand: at most one top-level FreeSpaceBox is allowed"); // The primary image item conforms to a MIAF profile. if(!checkRuleSection(globalSpec, "7.", root)) out->error("'MiPr' brand: this file shall conform to MIAF (Section 7)"); if(!checkRuleSection(globalSpec, "8.", root)) out->error("'MiPr' brand: this file shall conform to MIAF (Section 8)"); found = false; uint32_t primaryItemId = -1; for(auto& box : root.children) if(box.fourcc == FOURCC("meta")) for(auto& metaChild : box.children) if(metaChild.fourcc == FOURCC("pitm")) { found = true; for(auto& field : metaChild.syms) if(!strcmp(field.name, "item_ID")) primaryItemId = field.value; } if(!found) out->error("'MiPr' brand: PrimaryItemBox is required"); std::map<uint32_t /*itemId*/, int64_t /*offset*/> pitmSelfAndThmbs; pitmSelfAndThmbs.insert({ primaryItemId, -1 }); // self for(auto& box : root.children) if(box.fourcc == FOURCC("meta")) for(auto& metaChild : box.children) if(metaChild.fourcc == FOURCC("iref")) { uint32_t boxType = -1; for(auto& field : metaChild.syms) { if(!strcmp(field.name, "box_type")) boxType = field.value; if(boxType != FOURCC("thmb")) continue; if(!strcmp(field.name, "to_item_ID")) { if(field.value != primaryItemId) for(auto& sym : metaChild.syms) if(!strcmp(sym.name, "from_item_ID")) pitmSelfAndThmbs.insert({ sym.value, -1 }); } } } if(pitmSelfAndThmbs.empty()) out->error("'MiPr' brand: there is at least one MIAF thumbnail image item present for the primary image item"); int64_t pitmFirstOffset = -1; for(auto& box : root.children) if(box.fourcc == FOURCC("meta")) for(auto& metaChild : box.children) if(metaChild.fourcc == FOURCC("iloc")) { // for MIAF coded image items construction_method==0 and data_reference_index==0 uint32_t itemId = 0; for(auto& sym : metaChild.syms) { if(!strcmp(sym.name, "item_ID")) itemId = sym.value; if(pitmSelfAndThmbs.find(itemId) != pitmSelfAndThmbs.end()) { if(itemId == primaryItemId) if(!strcmp(sym.name, "base_offset")) pitmFirstOffset = sym.value; if(!strcmp(sym.name, "base_offset") || !strcmp(sym.name, "extent_offset")) pitmSelfAndThmbs[itemId] = sym.value; if(!strcmp(sym.name, "base_offset") || !strcmp(sym.name, "extent_offset")) pitmSelfAndThmbs[itemId] += sym.value; } } } found = false; for(auto& item : pitmSelfAndThmbs) { if(item.second < pitmSelfAndThmbs[primaryItemId]) out->error("'MiPr' brand: coded data offset thumbnail (item_ID=%u offset=%lld) precedes coded data for the primary item (item_ID=%u offset=%lld)", item.first, item.second, primaryItemId, pitmFirstOffset); if(item.second < 128000) found = true; } if(!found) out->error("'MiPr' brand: The maximum number of bytes from the beginning of the file to\n" " the last byte of the coded data for at least one of the thumbnail images of the\n" " primary item, or the primary item itself, is 128 000 bytes."); } }, { "Section 10.3\n" "The presence of the animation MIAF application brand indication ('MiAn') in the\n" "FileTypeBox indicates that the file conforms to the following additional\n" "constraints:\n" "- There shall be:\n" " * exactly one non-auxiliary video track or non-auxiliary image sequence track\n" " * at most one auxiliary video track (which shall be an alpha plane track,\n" " when present),\n" " * at most one audio track, and\n" " * no other media tracks.\n" "- The luma sample rate of each video track shall be less than or equal to\n" " 62 914 560 samples per second.\n" "- The constraints of subclause 8.6 apply.", [] (Box const& root, IReport* out) { bool found = false; for(auto& box : root.children) if(box.fourcc == FOURCC("ftyp")) for(auto& sym : box.syms) if(!strcmp(sym.name, "compatible_brand")) if(sym.value == FOURCC("MiAn")) found = true; if(!found) return; { std::vector<uint32_t> trackHandlers; bool foundAlphaTrack = false; for(auto& box : root.children) if(box.fourcc == FOURCC("moov")) for(auto& moovChild : box.children) if(moovChild.fourcc == FOURCC("trak")) for(auto& trakChild : moovChild.children) if(trakChild.fourcc == FOURCC("mdia")) { for(auto& mdiaChild : trakChild.children) if(mdiaChild.fourcc == FOURCC("minf")) { for(auto& minfChild : mdiaChild.children) if(minfChild.fourcc == FOURCC("stbl")) for(auto& stblChild : minfChild.children) if(stblChild.fourcc == FOURCC("stsd")) for(auto& stsdChild : stblChild.children) if(isVisualSampleEntry(stsdChild.fourcc)) for(auto& sampleEntryChild : stsdChild.children) if(sampleEntryChild.fourcc == FOURCC("auxi")) { std::string auxType; for(auto& sym : sampleEntryChild.syms) if(!strcmp(sym.name, "aux_track_type")) { auxType.push_back((char)sym.value); if(auxType == "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha") foundAlphaTrack = true; } } } else if(mdiaChild.fourcc == FOURCC("hdlr")) for(auto& sym : mdiaChild.syms) if(!strcmp(sym.name, "handler_type")) trackHandlers.push_back(sym.value); } int numVideoTracks = 0, numAudioTracks = 0, numAuxTracks = 0; for(auto hdlr : trackHandlers) { switch(hdlr) { case FOURCC("vide"): case FOURCC("pict"): numVideoTracks++; break; case FOURCC("soun"): numAudioTracks++; break; case FOURCC("auxv"): numAuxTracks++; break; default: out->error("'MiAn' brand: no other media tracks than video/image sequence, audio, and auxiliary allowed. Found \"%s\"", toString(hdlr).c_str()); break; } if(numVideoTracks != 1) out->error("'MiAn' brand: there shall be exactly one non-auxiliary video track or non-auxiliary image sequence track, found %d", numVideoTracks); if(numAudioTracks > 1) out->error("'MiAn' brand: at most one audio track, found %d", numAudioTracks); if(numAuxTracks > 1 || !foundAlphaTrack) out->error("'MiAn' brand: there shall be at most one auxiliary video track 'auxv' (found %d) (which shall be an alpha plane track: \"%s\")", numAuxTracks, foundAlphaTrack ? "true" : "false"); } if(!checkRuleSection(globalSpec, "10.6", root)) out->error(" 'MiAn' brand: this file shall conform to the 'MiCm' brand"); } } }, { "Section 10.4\n" "A track indicated to conform to this brand shall be constrained as follows:\n" "- The track shall be an image sequence ('pict') track.\n" "- In the image sequence track, any single coded picture shall be decodable by\n" " decoding a maximum of two coded pictures (i.e. the picture itself and at most\n" " one reference), and these two coded pictures shall be a valid bitstream.", [] (Box const& root, IReport* out) { bool found = false; for(auto& box : root.children) if(box.fourcc == FOURCC("ftyp")) for(auto& sym : box.syms) if(!strcmp(sym.name, "compatible_brand")) if(sym.value == FOURCC("MiBu")) found = true; if(!found) return; for(auto& box : root.children) if(box.fourcc == FOURCC("meta")) for(auto& metaChild : box.children) if(metaChild.fourcc == FOURCC("hdlr")) for(auto& field : metaChild.syms) if(!strcmp(field.name, "handler_type")) if(field.value != FOURCC("pict")) out->error("'MiBu' brand: the track shall be an image sequence ('pict') track"); } }, { "Section 10.5\n" "The presence of the brand 'MiAC' in the FileTypeBox indicates that the file\n" "conforms to the following additional constraints:\n" " - It conforms to the constraints of both the 'MiCm' and the 'MiAn' brands,\n" " with the following constraints:\n" " - There is exactly one auxiliary alpha video track.\n" " - The non-auxiliary video track uses the 'vide' handler, and is not\n" " pre-multiplied.\n" " - The tracks are fragmented.", [] (Box const& root, IReport* out) { bool found = false; for(auto& box : root.children) if(box.fourcc == FOURCC("ftyp")) for(auto& sym : box.syms) if(!strcmp(sym.name, "compatible_brand")) if(sym.value == FOURCC("MiAC")) found = true; if(!found) return; if(!checkRuleSection(globalSpec, "10.6", root)) out->error("'MiAC' brand: this file shall conform to the 'MiCm' brand"); if(!checkRuleSection(globalSpec, "10.3", root)) out->error("'MiAC' brand: this file shall conform to the 'MiAn' brand"); { int alphaTrackNum = 0; for(auto& box : root.children) if(box.fourcc == FOURCC("moov")) for(auto& moovChild : box.children) if(moovChild.fourcc == FOURCC("trak")) for(auto& trakChild : moovChild.children) if(trakChild.fourcc == FOURCC("mdia")) for(auto& mdiaChild : trakChild.children) if(mdiaChild.fourcc == FOURCC("minf")) for(auto& minfChild : mdiaChild.children) if(minfChild.fourcc == FOURCC("stbl")) for(auto& stblChild : minfChild.children) if(stblChild.fourcc == FOURCC("stsd")) for(auto& stsdChild : stblChild.children) if(isVisualSampleEntry(stsdChild.fourcc)) for(auto& sampleEntryChild : stsdChild.children) if(sampleEntryChild.fourcc == FOURCC("auxi")) { std::string auxType; for(auto& sym : sampleEntryChild.syms) if(!strcmp(sym.name, "aux_track_type")) { auxType.push_back((char)sym.value); if(auxType == "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha") alphaTrackNum++; } } if(alphaTrackNum != 1) out->error("'MiAC' brand: there shall be exactly one auxiliary alpha video track, found %d.", alphaTrackNum); } { std::vector<uint32_t /*hdlr*/> trackHandlers; for(auto& box : root.children) if(box.fourcc == FOURCC("moov")) for(auto& moovChild : box.children) if(moovChild.fourcc == FOURCC("trak")) for(auto& trakChild : moovChild.children) if(trakChild.fourcc == FOURCC("mdia")) for(auto& mdiaChild : trakChild.children) if(mdiaChild.fourcc == FOURCC("hdlr")) for(auto& sym : mdiaChild.syms) if(!strcmp(sym.name, "handler_type")) trackHandlers.push_back((uint32_t)sym.value); if(trackHandlers.size() != 2) out->error("'MiAC' brand: \"the non-auxiliary video track shall use the 'vide' handler\" implies 2 tracks but %d were found", (int)trackHandlers.size()); if(!(trackHandlers[0] == FOURCC("auxv") && trackHandlers[1] == FOURCC("vide")) && !(trackHandlers[0] == FOURCC("vide") && trackHandlers[1] == FOURCC("auxv"))) out->error("'MiAC' brand: the non-auxiliary video track shall use the 'vide' handler, found handlers '%s' and '%s'", toString(trackHandlers[0]).c_str(), toString(trackHandlers[1]).c_str()); } found = false; for(auto& box : root.children) if(box.fourcc == FOURCC("moov")) for(auto& moovChild : box.children) if(moovChild.fourcc == FOURCC("mvex")) found = true; if(!found) out->error("'MiAC' brand: the tracks are fragmented"); } }, { "Section 10.6\n" "The presence of the brand 'MiCm' in the FileTypeBox indicates that the file\n" "contains movie fragments that conform to the constraints of the 'cmfc' brand of\n" "ISO/IEC 23000-19, and the following additional constraints that apply when a\n" "MIAF file contains multiple tracks (e.g. a video or image sequence track and an\n" "auxiliary track):\n" " - each track, if considered separately, shall be a conforming CMAF track as\n" " defined in ISO/IEC 23000-19. In other words, if all boxes related to the\n" " other tracks were removed (e.g. file-level boxes such as MovieFragmentBoxes,\n" " and boxes in the MovieBox such as the TrackBox or the TrackExtendsBox), the\n" " content shall be conforming to the brand 'cmfc' defined in ISO/IEC 23000-19;\n" " - the set of CMAF tracks associated with all MIAF tracks (including any audio)\n" " shall be of the same duration, within a tolerance of the longest CMAF\n" " fragment duration of any CMAF track;\n" " - the set of CMAF tracks associated with the MIAF visual tracks shall have the\n" " same duration, same number of fragments and fragments shall be time-aligned.\n" " Fragments of the different CMAF tracks shall also be interleaved in the MIAF\n" " file.", [] (Box const& root, IReport* /*out*/) { bool found = false; for(auto& box : root.children) if(box.fourcc == FOURCC("ftyp")) for(auto& sym : box.syms) if(!strcmp(sym.name, "compatible_brand")) if(sym.value == FOURCC("MiCm")) found = true; if(!found) return; // TODO: CMAF } }, #if 0 { "Section 7.2.1.2\n" "The FileTypeBox shall contain, in the compatible_brands list [...] brand(s)\n" "identifying conformance to this document (specified in Clause 10).", [] (Box const& root, IReport* out) { std::vector<uint32_t> compatibleBrands; for(auto& box : root.children) if(box.fourcc == FOURCC("ftyp")) for(auto& sym : box.syms) if(!strcmp(sym.name, "compatible_brand")) compatibleBrands.push_back(sym.value); if(checkRuleSection(globalSpec, "10.2", root) && std::find(compatibleBrands.begin(), compatibleBrands.end(), FOURCC("MiPr")) == compatibleBrands.end()) out->warning("File conforms to 'MiPr' brand but 'MiPr' is not in the 'ftyp' compatible_brand list"); if(!checkRuleSection(globalSpec, "10.3", root) && std::find(compatibleBrands.begin(), compatibleBrands.end(), FOURCC("MiAn")) == compatibleBrands.end()) out->warning("File conforms to 'MiAn' brand but 'MiAn' is not in the 'ftyp' compatible_brand list"); if(!checkRuleSection(globalSpec, "10.4", root) && std::find(compatibleBrands.begin(), compatibleBrands.end(), FOURCC("MiBu")) == compatibleBrands.end()) out->warning("File conforms to 'MiBu' brand but 'MiBu' is not in the 'ftyp' compatible_brand list"); if(!checkRuleSection(globalSpec, "10.5", root) && std::find(compatibleBrands.begin(), compatibleBrands.end(), FOURCC("MiAC")) == compatibleBrands.end()) out->warning("File conforms to 'MiAC' brand but 'MiAC' is not in the 'ftyp' compatible_brand list"); if(!checkRuleSection(globalSpec, "10.6", root) && std::find(compatibleBrands.begin(), compatibleBrands.end(), FOURCC("MiCm")) == compatibleBrands.end()) out->warning("File conforms to 'MiCm' brand but 'MiCm' is not in the 'ftyp' compatible_brand list"); } } #endif }; return rulesBrands; }
42.911937
201
0.530281
[ "vector" ]
b2bbf15e68506d57cd8b64bcf387e5e25cdb87ef
4,876
cpp
C++
Tool Jump/main.cpp
Barry0310/Tool-jump-Game-in-cpp
b54bd672045e9dfd2156074255ada3073f553d3f
[ "MIT" ]
null
null
null
Tool Jump/main.cpp
Barry0310/Tool-jump-Game-in-cpp
b54bd672045e9dfd2156074255ada3073f553d3f
[ "MIT" ]
null
null
null
Tool Jump/main.cpp
Barry0310/Tool-jump-Game-in-cpp
b54bd672045e9dfd2156074255ada3073f553d3f
[ "MIT" ]
null
null
null
#include <SFML/Graphics.hpp> #include <math.h> #include <stdlib.h> #include <time.h> #include <vector> #include "Player.h" #include "platform.h" #include "Menu.h" int main() { srand(time(0)); sf::RenderWindow window(sf::VideoMode(400.0f,600.0f),"Tool Jump",sf::Style::Close); sf::RectangleShape background(sf::Vector2f(400.0f,600.0f)); //////set menu//////////// sf::Texture pic; pic.loadFromFile("toolman.jpg"); Menu Menu(&pic,(float)window.getSize().x,(float)window.getSize().y); bool game=false; bool option=false; //////set player picture////// sf::Texture doodle; doodle.loadFromFile("tooldoodleee.png"); Player tooldoodle(&doodle,sf::Vector2u(2,1),200.0f); //////set background picture////// sf::Texture bg; bg.loadFromFile("backgrond.png"); background.setTexture(&bg); //////set stair////////////////// sf::Texture stair; stair.loadFromFile("finish.png"); std::vector<platform> stairs; stairs.push_back(platform(&stair,200,590,0)); for(int i=1; i<15; i++) { stairs.push_back(platform(&stair,float(rand()%304+48),float(-1*(rand()%50+40)),stairs[i-1].Getposition())); } //////////////////////////////// int SCORE=0; float deltatime=0.0f; sf::Clock clock; while(window.isOpen()) { deltatime=clock.restart().asSeconds(); if(deltatime>1.0f/20.0f) { deltatime=1.0f/20.0f; } sf::Event evnt; while(window.pollEvent(evnt)) { switch(evnt.type) { case sf::Event::KeyReleased: { switch(evnt.key.code) { case sf::Keyboard::Up: { Menu.Moveup(); break; } case sf::Keyboard::Down: { Menu.Movedown(); break; } case sf::Keyboard::Return: { switch(Menu.GetPressitem()) { case 0: game=true; case 1: option=true; } } } } break; case (sf::Event::Closed): { window.close(); break; } } } ///////menu/////// window.clear(); window.draw(background); if(game==false&&option==false) { Menu.Draw(window); } //////option////// if(game==false&&option==true) { Menu.Drawoption(window); if(sf::Keyboard::isKeyPressed(sf::Keyboard::B)) option=false; } //////game start/////// if(tooldoodle.GetPosition().y<625&&game==true) { sf::Vector2f derection; tooldoodle.Update(deltatime); /////stairs move////// if(tooldoodle.JumpTooHigh()) { for(int i=0; i<15; i++) { stairs[i].Move(tooldoodle.JumpTooHigh()+10); } for(int g=0; g<15; g++) { if(stairs[g].Getposition()>600) { SCORE++; stairs.erase(stairs.begin()+g); stairs.push_back(platform(&stair,float(rand()%304+48),float(-1*(rand()%50+40)),stairs[stairs.size()-1].Getposition())); } } } printf("%d\n",SCORE); /////////////////////////////// for(platform& platform : stairs) { if(platform.GetCollider().checkcollision(tooldoodle.GetCollider(),derection,0.0f)&&tooldoodle.velocity.y>0) tooldoodle.Oncollition(derection); } for(int i=0; i<15; i++) { stairs[i].Draw(window); } tooldoodle.Draw(window); } ///////////reset///////// if(tooldoodle.GetPosition().y>625) { Menu.Drawdead(window); if(sf::Keyboard::isKeyPressed(sf::Keyboard::R)) { SCORE=0; stairs.clear(); stairs.push_back(platform(&stair,200,590,0)); for(int i=1; i<15; i++) { stairs.push_back(platform(&stair,float(rand()%304+48),float(-1*(rand()%50+40)),stairs[i-1].Getposition())); } tooldoodle.Reset(); } } window.display(); if(sf::Keyboard::isKeyPressed(sf::Keyboard::E)) { window.close(); } } return 0; }
30.098765
143
0.431501
[ "vector" ]
b2c230a15ed71b41a1453834cec6963349ca1903
2,965
cpp
C++
plaidml/bridge/openvino/tests/functional/shared_tests_instances/single_layer_tests/psroi_pooling.cpp
IsolatedMy/plaidml
34538a9224e770fd79151105399d8d7ea08678c0
[ "Apache-2.0" ]
null
null
null
plaidml/bridge/openvino/tests/functional/shared_tests_instances/single_layer_tests/psroi_pooling.cpp
IsolatedMy/plaidml
34538a9224e770fd79151105399d8d7ea08678c0
[ "Apache-2.0" ]
65
2020-08-24T07:41:09.000Z
2021-07-19T09:13:49.000Z
plaidml/bridge/openvino/tests/functional/shared_tests_instances/single_layer_tests/psroi_pooling.cpp
Flex-plaidml-team/plaidml
1070411a87b3eb3d94674d4d041ed904be3e7d87
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include "common_test_utils/test_constants.hpp" #include "single_layer_tests/psroi_pooling.hpp" using LayerTestsDefinitions::PSROIPoolingLayerTest; namespace { const std::vector<InferenceEngine::Precision> netPrecisions = { InferenceEngine::Precision::FP32, // InferenceEngine::Precision::FP16 // TODO: Not yet working }; const std::vector<std::vector<size_t>> coords = {{1, 5}, {2, 5}}; const std::vector<float> spatial_scale = {1.0, 0.5}; const std::vector<std::string> mode = {"average", "bilinear"}; INSTANTIATE_TEST_CASE_P(smoke_PSROIPooling, PSROIPoolingLayerTest, ::testing::Combine(::testing::Values(std::vector<size_t>({1, 8, 10, 10})), // ::testing::ValuesIn(coords), // ::testing::Values(2), // ::testing::Values(2), // ::testing::ValuesIn(spatial_scale), // ::testing::Values(2), // ::testing::Values(2), // ::testing::ValuesIn(mode), // ::testing::ValuesIn(netPrecisions), // ::testing::Values(CommonTestUtils::DEVICE_PLAIDML)), // PSROIPoolingLayerTest::getTestCaseName); INSTANTIATE_TEST_CASE_P(PSROIPooling, PSROIPoolingLayerTest, ::testing::Combine(::testing::Values(std::vector<size_t>({1, 18, 10, 10})), // ::testing::ValuesIn(coords), // ::testing::Values(2), // ::testing::Values(3), // ::testing::ValuesIn(spatial_scale), // ::testing::Values(3), // ::testing::Values(3), // ::testing::ValuesIn(mode), // ::testing::ValuesIn(netPrecisions), // ::testing::Values(CommonTestUtils::DEVICE_PLAIDML)), // PSROIPoolingLayerTest::getTestCaseName); } // namespace
60.510204
103
0.382799
[ "vector" ]