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
8717decc4b9d6928da383486391806380c4903a0
38,985
cpp
C++
cocos2d/cocos/editor-support/cocostudio/FlatBuffersSerialize.cpp
triompha/EarthWarrior3D
d68a347902fa1ca1282df198860f5fb95f326797
[ "MIT" ]
null
null
null
cocos2d/cocos/editor-support/cocostudio/FlatBuffersSerialize.cpp
triompha/EarthWarrior3D
d68a347902fa1ca1282df198860f5fb95f326797
[ "MIT" ]
null
null
null
cocos2d/cocos/editor-support/cocostudio/FlatBuffersSerialize.cpp
triompha/EarthWarrior3D
d68a347902fa1ca1282df198860f5fb95f326797
[ "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2013 cocos2d-x.org http://www.cocos2d-x.org 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 "FlatBuffersSerialize.h" #include "base/ObjectFactory.h" #include "ui/CocosGUI.h" #include "cocostudio/CocoStudio.h" #include "CSParseBinary_generated.h" #include "WidgetReader/NodeReaderProtocol.h" #include "WidgetReader/NodeReaderDefine.h" #include "WidgetReader/NodeReader/NodeReader.h" #include "WidgetReader/SingleNodeReader/SingleNodeReader.h" #include "WidgetReader/SpriteReader/SpriteReader.h" #include "WidgetReader/ParticleReader/ParticleReader.h" #include "WidgetReader/GameMapReader/GameMapReader.h" #include "WidgetReader/ComAudioReader/ComAudioReader.h" #include "WidgetReader/ProjectNodeReader/ProjectNodeReader.h" #include "WidgetReader/ButtonReader/ButtonReader.h" #include "WidgetReader/CheckBoxReader/CheckBoxReader.h" #include "WidgetReader/ImageViewReader/ImageViewReader.h" #include "WidgetReader/TextBMFontReader/TextBMFontReader.h" #include "WidgetReader/TextReader/TextReader.h" #include "WidgetReader/TextFieldReader/TextFieldReader.h" #include "WidgetReader/TextAtlasReader/TextAtlasReader.h" #include "WidgetReader/LoadingBarReader/LoadingBarReader.h" #include "WidgetReader/SliderReader/SliderReader.h" #include "WidgetReader/LayoutReader/LayoutReader.h" #include "WidgetReader/ScrollViewReader/ScrollViewReader.h" #include "WidgetReader/PageViewReader/PageViewReader.h" #include "WidgetReader/ListViewReader/ListViewReader.h" #include "tinyxml2/tinyxml2.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/util.h" USING_NS_CC; using namespace cocos2d::ui; using namespace cocostudio; using namespace cocostudio::timeline; using namespace flatbuffers; namespace cocostudio { static const char* FrameType_VisibleFrame = "VisibleFrame"; static const char* FrameType_PositionFrame = "PositionFrame"; static const char* FrameType_ScaleFrame = "ScaleFrame"; static const char* FrameType_RotationSkewFrame = "RotationSkewFrame"; static const char* FrameType_AnchorFrame = "AnchorPointFrame"; static const char* FrameType_ColorFrame = "ColorFrame"; static const char* FrameType_TextureFrame = "TextureFrame"; static const char* FrameType_EventFrame = "EventFrame"; static const char* FrameType_ZOrderFrame = "ZOrderFrame"; static FlatBuffersSerialize* _instanceFlatBuffersSerialize = nullptr; FlatBuffersSerialize::FlatBuffersSerialize() : _isSimulator(false) , _builder(nullptr) , _csparsebinary(nullptr) { CREATE_CLASS_NODE_READER_INFO(NodeReader); CREATE_CLASS_NODE_READER_INFO(SingleNodeReader); CREATE_CLASS_NODE_READER_INFO(SpriteReader); CREATE_CLASS_NODE_READER_INFO(ParticleReader); CREATE_CLASS_NODE_READER_INFO(GameMapReader); CREATE_CLASS_NODE_READER_INFO(ButtonReader); CREATE_CLASS_NODE_READER_INFO(CheckBoxReader); CREATE_CLASS_NODE_READER_INFO(ImageViewReader); CREATE_CLASS_NODE_READER_INFO(TextBMFontReader); CREATE_CLASS_NODE_READER_INFO(TextReader); CREATE_CLASS_NODE_READER_INFO(TextFieldReader); CREATE_CLASS_NODE_READER_INFO(TextAtlasReader); CREATE_CLASS_NODE_READER_INFO(LoadingBarReader); CREATE_CLASS_NODE_READER_INFO(SliderReader); CREATE_CLASS_NODE_READER_INFO(LayoutReader); CREATE_CLASS_NODE_READER_INFO(ScrollViewReader); CREATE_CLASS_NODE_READER_INFO(PageViewReader); CREATE_CLASS_NODE_READER_INFO(ListViewReader); } FlatBuffersSerialize::~FlatBuffersSerialize() { purge(); } FlatBuffersSerialize* FlatBuffersSerialize::getInstance() { if (!_instanceFlatBuffersSerialize) { _instanceFlatBuffersSerialize = new FlatBuffersSerialize(); } return _instanceFlatBuffersSerialize; } void FlatBuffersSerialize::purge() { CC_SAFE_DELETE(_instanceFlatBuffersSerialize); } void FlatBuffersSerialize::deleteFlatBufferBuilder() { if (_builder != nullptr) { _builder->Clear(); CC_SAFE_DELETE(_builder); } } std::string FlatBuffersSerialize::serializeFlatBuffersWithXMLFile(const std::string &xmlFileName, const std::string &flatbuffersFileName) { std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName).c_str(); // xml read if (!FileUtils::getInstance()->isFileExist(inFullpath)) { return ".csd file doesn not exists "; } ssize_t size; std::string content =(char*)FileUtils::getInstance()->getFileData(inFullpath, "r", &size); // xml parse tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument(); document->Parse(content.c_str()); const tinyxml2::XMLElement* rootElement = document->RootElement();// Root // CCLOG("rootElement name = %s", rootElement->Name()); const tinyxml2::XMLElement* element = rootElement->FirstChildElement(); bool serializeEnabled = false; std::string rootType = ""; while (element) { // CCLOG("entity name = %s", element->Name()); if (strcmp("Content", element->Name()) == 0) { const tinyxml2::XMLAttribute* attribute = element->FirstAttribute(); // if (!attribute) { serializeEnabled = true; rootType = "NodeObjectData"; } // // // while (attribute) // { // std::string name = attribute->Name(); // std::string value = attribute->Value(); // CCLOG("attribute name = %s, value = %s", name, value); // if (name == "") // { // serializeEnabled = true; // rootType = (strcmp("", value) == 0) ? "Node" : value; // } // // if (serializeEnabled) // { // break; // } // // attribute = attribute->Next(); // } // } if (serializeEnabled) { break; } const tinyxml2::XMLElement* child = element->FirstChildElement(); if (child) { element = child; } else { element = element->NextSiblingElement(); } } if (serializeEnabled) { _builder = new FlatBufferBuilder(); Offset<NodeTree> nodeTree; Offset<NodeAction> aciton; const tinyxml2::XMLElement* child = element->FirstChildElement(); while (child) { std::string name = child->Name(); if (name == "Animation") // action { const tinyxml2::XMLElement* animation = child; aciton = createNodeAction(animation); } else if (name == "ObjectData") // nodeTree { const tinyxml2::XMLElement* objectData = child; nodeTree = createNodeTree(objectData, rootType); } child = child->NextSiblingElement(); } auto csparsebinary = CreateCSParseBinary(*_builder, _builder->CreateVector(_textures), _builder->CreateVector(_texturePngs), nodeTree, aciton); _builder->Finish(csparsebinary); _textures.clear(); _texturePngs.clear(); std::string outFullPath = FileUtils::getInstance()->fullPathForFilename(flatbuffersFileName); size_t pos = outFullPath.find_last_of('.'); std::string convert = outFullPath.substr(0, pos).append(".csb"); auto save = flatbuffers::SaveFile(convert.c_str(), reinterpret_cast<const char *>(_builder->GetBufferPointer()), _builder->GetSize(), true); if (!save) { return "couldn't save files!"; } deleteFlatBufferBuilder(); } return ""; } // NodeTree Offset<NodeTree> FlatBuffersSerialize::createNodeTree(const tinyxml2::XMLElement *objectData, std::string classType) { std::string classname = classType.substr(0, classType.find("ObjectData")); // CCLOG("classname = %s", classname.c_str()); std::string name = ""; Offset<Options> options; std::vector<Offset<NodeTree>> children; if (classname == "ProjectNode") { auto reader = ProjectNodeReader::getInstance(); options = CreateOptions(*_builder, reader->createOptionsWithFlatBuffers(objectData, _builder)); } else if (classname == "SimpleAudio") { auto reader = ComAudioReader::getInstance(); options = CreateOptions(*_builder, reader->createOptionsWithFlatBuffers(objectData, _builder)); } else { std::string readername = getGUIClassName(classname); readername.append("Reader"); NodeReaderProtocol* reader = dynamic_cast<NodeReaderProtocol*>(ObjectFactory::getInstance()->createObject(readername)); options = CreateOptions(*_builder, reader->createOptionsWithFlatBuffers(objectData, _builder)); } // children bool containChildrenElement = false; const tinyxml2::XMLElement* child = objectData->FirstChildElement(); while (child) { // CCLOG("child name = %s", child->Name()); if (strcmp("Children", child->Name()) == 0) { containChildrenElement = true; break; } child = child->NextSiblingElement(); } if (containChildrenElement) { child = child->FirstChildElement(); // CCLOG("element name = %s", child->Name()); while (child) { const tinyxml2::XMLAttribute* attribute = child->FirstAttribute(); bool bHasType = false; while (attribute) { std::string attriname = attribute->Name(); std::string value = attribute->Value(); if (attriname == "ctype") { children.push_back(createNodeTree(child, value)); bHasType = true; break; } attribute = attribute->Next(); } if(!bHasType) { children.push_back(createNodeTree(child, "NodeObjectData")); } child = child->NextSiblingElement(); } } // std::string customClassName = ""; const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string attriname = attribute->Name(); std::string value = attribute->Value(); if (attriname == "CustomClassName") { customClassName = value; break; } attribute = attribute->Next(); } return CreateNodeTree(*_builder, _builder->CreateString(classname), _builder->CreateVector(children), options, _builder->CreateString(customClassName)); } int FlatBuffersSerialize::getResourceType(std::string key) { if(key == "Normal" || key == "Default") { return 0; } if(_isSimulator) { if(key == "MarkedSubImage") { return 0; } } return 1; } std::string FlatBuffersSerialize::getGUIClassName(const std::string &name) { std::string convertedClassName = name; if (name == "Panel") { convertedClassName = "Layout"; } else if (name == "TextArea") { convertedClassName = "Text"; } else if (name == "TextButton") { convertedClassName = "Button"; } else if (name == "Label") { convertedClassName = "Text"; } else if (name == "LabelAtlas") { convertedClassName = "TextAtlas"; } else if (name == "LabelBMFont") { convertedClassName = "TextBMFont"; } return convertedClassName; } std::string FlatBuffersSerialize::getWidgetReaderClassName(Widget* widget) { std::string readerName; // 1st., custom widget parse properties of parent widget with parent widget reader if (dynamic_cast<Button*>(widget)) { readerName = "ButtonReader"; } else if (dynamic_cast<CheckBox*>(widget)) { readerName = "CheckBoxReader"; } else if (dynamic_cast<ImageView*>(widget)) { readerName = "ImageViewReader"; } else if (dynamic_cast<TextAtlas*>(widget)) { readerName = "TextAtlasReader"; } else if (dynamic_cast<TextBMFont*>(widget)) { readerName = "TextBMFontReader"; } else if (dynamic_cast<Text*>(widget)) { readerName = "TextReader"; } else if (dynamic_cast<LoadingBar*>(widget)) { readerName = "LoadingBarReader"; } else if (dynamic_cast<Slider*>(widget)) { readerName = "SliderReader"; } else if (dynamic_cast<TextField*>(widget)) { readerName = "TextFieldReader"; } else if (dynamic_cast<ListView*>(widget)) { readerName = "ListViewReader"; } else if (dynamic_cast<PageView*>(widget)) { readerName = "PageViewReader"; } else if (dynamic_cast<ScrollView*>(widget)) { readerName = "ScrollViewReader"; } else if (dynamic_cast<Layout*>(widget)) { readerName = "LayoutReader"; } else if (dynamic_cast<Widget*>(widget)) { readerName = "WidgetReader"; } return readerName; } // // NodeAction Offset<NodeAction> FlatBuffersSerialize::createNodeAction(const tinyxml2::XMLElement *objectData) { int duration = 0; float speed = 0.0f; // CCLOG("animation name = %s", objectData->Name()); // ActionTimeline const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); // attibutes while (attribute) { std::string name = attribute->Name(); std::string value = attribute->Value(); if (name == "Duration") { duration = atoi(value.c_str()); } else if (name == "Speed") { speed = atof(value.c_str()); } attribute = attribute->Next(); } // all Timeline std::vector<Offset<TimeLine>> timelines; const tinyxml2::XMLElement* timelineElement = objectData->FirstChildElement(); while (timelineElement) { auto timeLine = createTimeLine(timelineElement); timelines.push_back(timeLine); timelineElement = timelineElement->NextSiblingElement(); } return CreateNodeAction(*_builder, duration, speed, _builder->CreateVector(timelines)); } Offset<TimeLine> FlatBuffersSerialize::createTimeLine(const tinyxml2::XMLElement *objectData) { int actionTag = 0; std::string frameType = ""; // TimelineData attrsibutes const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string name = attribute->Name(); std::string value = attribute->Value(); if (name == "ActionTag") { actionTag = atoi(value.c_str()); } else if (name == "FrameType") { frameType = value; } attribute = attribute->Next(); } // all Frame std::vector<Offset<flatbuffers::Frame>> frames; const tinyxml2::XMLElement* frameElement = objectData->FirstChildElement(); while (frameElement) { Offset<flatbuffers::Frame> frame; if (frameType == FrameType_VisibleFrame) { auto visibleFrame = createTimeLineBoolFrame(frameElement); frame = CreateFrame(*_builder, visibleFrame); } else if (frameType == FrameType_ZOrderFrame) { auto zOrderFrame = createTimeLineIntFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame zOrderFrame); } else if (frameType == FrameType_RotationSkewFrame) { auto rotationSkewFrame = createTimeLinePointFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame rotationSkewFrame); } else if (frameType == FrameType_EventFrame) { auto eventFrame = createTimeLineStringFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame 0, // RotationSkewFrame eventFrame); } else if (frameType == FrameType_AnchorFrame) { auto anchorPointFrame = createTimeLinePointFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame 0, // RotationSkewFrame 0, // EventFrame anchorPointFrame); } else if (frameType == FrameType_PositionFrame) { auto positionFrame = createTimeLinePointFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame 0, // RotationSkewFrame 0, // EventFrame 0, // AnchorPointFrame positionFrame); } else if (frameType == FrameType_ScaleFrame) { auto scaleFrame = createTimeLinePointFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame 0, // RotationSkewFrame 0, // EventFrame 0, // AnchorPointFrame 0, // PositionFrame scaleFrame); } else if (frameType == FrameType_ColorFrame) { auto colorFrame = createTimeLineColorFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame 0, // RotationSkewFrame 0, // EventFrame 0, // AnchorPointFrame 0, // PositionFrame 0, // ScaleFrame colorFrame); } else if (frameType == FrameType_TextureFrame) { auto textureFrame = createTimeLineTextureFrame(frameElement); frame = CreateFrame(*_builder, 0, // VisibleFrame 0, // ZOrderFrame 0, // RotationSkewFrame 0, // EventFrame 0, // AnchorPointFrame 0, // PositionFrame 0, // ScaleFrame 0, // ColorFrame textureFrame); } frames.push_back(frame); frameElement = frameElement->NextSiblingElement(); } return CreateTimeLine(*_builder, _builder->CreateString(frameType), actionTag, _builder->CreateVector(frames)); } Offset<TimeLineBoolFrame> FlatBuffersSerialize::createTimeLineBoolFrame(const tinyxml2::XMLElement *objectData) { int frameIndex = 0; bool tween = true; bool value = false; const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string name = attribute->Name(); std::string attrivalue = attribute->Value(); if (name == "Value") { value = (attrivalue == "True") ? true : false; } else if (name == "FrameIndex") { frameIndex = atoi(attrivalue.c_str()); } else if (name == "Tween") { tween = atoi(attrivalue.c_str()); } attribute = attribute->Next(); } return CreateTimeLineBoolFrame(*_builder, frameIndex, tween, value); } Offset<TimeLineIntFrame> FlatBuffersSerialize::createTimeLineIntFrame(const tinyxml2::XMLElement *objectData) { int frameIndex = 0; bool tween = true; int value = 0; const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string name = attribute->Name(); std::string attrivalue = attribute->Value(); if (name == "Value") // to be gonna modify { value = atoi(attrivalue.c_str()); } else if (name == "FrameIndex") { frameIndex = atoi(attrivalue.c_str()); } else if (name == "Tween") { tween = (attrivalue == "True") ? true : false; } attribute = attribute->Next(); } return CreateTimeLineIntFrame(*_builder, frameIndex, tween, value); } Offset<TimeLineStringFrame> FlatBuffersSerialize::createTimeLineStringFrame(const tinyxml2::XMLElement *objectData) { int frameIndex = 0; bool tween = true; std::string value = ""; const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string name = attribute->Name(); std::string attrivalue = attribute->Value(); if (name == "Value") // to be gonna modify { value = attrivalue; } else if (name == "FrameIndex") { frameIndex = atoi(attrivalue.c_str()); } else if (name == "Tween") { tween = (attrivalue == "True") ? true : false; } attribute = attribute->Next(); } return CreateTimeLineStringFrame(*_builder, frameIndex, tween, _builder->CreateString(value)); } Offset<TimeLinePointFrame> FlatBuffersSerialize::createTimeLinePointFrame(const tinyxml2::XMLElement *objectData) { int frameIndex = 0; bool tween = true; Vec2 position; const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string name = attribute->Name(); std::string value = attribute->Value(); if (name == "X") { position.x = atof(value.c_str()); } else if (name == "Y") { position.y = atof(value.c_str()); } else if (name == "FrameIndex") { frameIndex = atoi(value.c_str()); } else if (name == "Tween") { tween = (value == "True") ? true : false; } attribute = attribute->Next(); } Position f_position(position.x, position.y); return CreateTimeLinePointFrame(*_builder, frameIndex, tween, &f_position); } Offset<TimeLineColorFrame> FlatBuffersSerialize::createTimeLineColorFrame(const tinyxml2::XMLElement *objectData) { int frameIndex = 0; bool tween = true; Color4B color; const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string name = attribute->Name(); std::string value = attribute->Value(); if (name == "FrameIndex") { frameIndex = atoi(value.c_str()); } else if (name == "Alpha") { color.a = atoi(value.c_str()); } else if (name == "Tween") { tween = (value == "True") ? true : false; } attribute = attribute->Next(); } // color const tinyxml2::XMLElement* child = objectData->FirstChildElement(); while (child) { attribute = child->FirstAttribute(); while (attribute) { std::string name = attribute->Name(); std::string value = attribute->Value(); if (name == "R") { color.r = atoi(value.c_str()); } else if (name == "G") { color.g = atoi(value.c_str()); } else if (name == "B") { color.b = atoi(value.c_str()); } attribute = attribute->Next(); } child = child->NextSiblingElement(); } Color f_color(color.a, color.r, color.g, color.b); return CreateTimeLineColorFrame(*_builder, frameIndex, tween, &f_color); } Offset<TimeLineTextureFrame> FlatBuffersSerialize::createTimeLineTextureFrame(const tinyxml2::XMLElement *objectData) { int frameIndex = 0; bool tween = true; std::string path = ""; std::string plistFile = ""; int resourceType = 0; std::string texture = ""; std::string texturePng = ""; const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string attriname = attribute->Name(); std::string value = attribute->Value(); if (attriname == "FrameIndex") { frameIndex = atoi(value.c_str()); } else if (attriname == "Tween") { tween = (value == "True") ? true : false; } attribute = attribute->Next(); } const tinyxml2::XMLElement* child = objectData->FirstChildElement(); while (child) { attribute = child->FirstAttribute(); while (attribute) { std::string attriname = attribute->Name(); std::string value = attribute->Value(); if (attriname == "Path") { path = value; } else if (attriname == "Type") { resourceType = getResourceType(value); } else if (attriname == "Plist") { plistFile = value; texture = value; } attribute = attribute->Next(); } if (resourceType == 1) { _textures.push_back(_builder->CreateString(texture)); } child = child->NextSiblingElement(); } return CreateTimeLineTextureFrame(*_builder, frameIndex, tween, CreateResourceData(*_builder, _builder->CreateString(path), _builder->CreateString(plistFile), resourceType)); } /* create flat buffers with XML */ FlatBufferBuilder* FlatBuffersSerialize::createFlatBuffersWithXMLFileForSimulator(const std::string &xmlFileName) { std::string inFullpath = FileUtils::getInstance()->fullPathForFilename(xmlFileName).c_str(); // xml read if (!FileUtils::getInstance()->isFileExist(inFullpath)) { // CCLOG(".csd file doesn not exists "); } ssize_t size; std::string content =(char*)FileUtils::getInstance()->getFileData(inFullpath, "r", &size); // xml parse tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument(); document->Parse(content.c_str()); const tinyxml2::XMLElement* rootElement = document->RootElement();// Root // CCLOG("rootElement name = %s", rootElement->Name()); const tinyxml2::XMLElement* element = rootElement->FirstChildElement(); bool serializeEnabled = false; std::string rootType = ""; while (element) { // CCLOG("entity name = %s", element->Name()); if (strcmp("Content", element->Name()) == 0) { const tinyxml2::XMLAttribute* attribute = element->FirstAttribute(); // if (!attribute) { serializeEnabled = true; rootType = "NodeObjectData"; } } if (serializeEnabled) { break; } const tinyxml2::XMLElement* child = element->FirstChildElement(); if (child) { element = child; } else { element = element->NextSiblingElement(); } } if (serializeEnabled) { _builder = new FlatBufferBuilder(); Offset<NodeTree> nodeTree; Offset<NodeAction> aciton; const tinyxml2::XMLElement* child = element->FirstChildElement(); while (child) { std::string name = child->Name(); if (name == "Animation") // action { const tinyxml2::XMLElement* animation = child; aciton = createNodeAction(animation); } else if (name == "ObjectData") // nodeTree { const tinyxml2::XMLElement* objectData = child; nodeTree = createNodeTreeForSimulator(objectData, rootType); } child = child->NextSiblingElement(); } auto csparsebinary = CreateCSParseBinary(*_builder, _builder->CreateVector(_textures), _builder->CreateVector(_texturePngs), nodeTree, aciton); _builder->Finish(csparsebinary); _textures.clear(); _texturePngs.clear(); } return _builder; } Offset<NodeTree> FlatBuffersSerialize::createNodeTreeForSimulator(const tinyxml2::XMLElement *objectData, std::string classType) { std::string classname = classType.substr(0, classType.find("ObjectData")); // CCLOG("classname = %s", classname.c_str()); std::string name = ""; Offset<Options> options; std::vector<Offset<NodeTree>> children; if (classname == "ProjectNode") { auto projectNodeOptions = createProjectNodeOptionsForSimulator(objectData); options = CreateOptions(*_builder, *(Offset<Table>*)(&projectNodeOptions)); } else if (classname == "SimpleAudio") { auto reader = ComAudioReader::getInstance(); options = CreateOptions(*_builder, reader->createOptionsWithFlatBuffers(objectData, _builder)); } else { std::string readername = getGUIClassName(classname); readername.append("Reader"); NodeReaderProtocol* reader = dynamic_cast<NodeReaderProtocol*>(ObjectFactory::getInstance()->createObject(readername)); options = CreateOptions(*_builder, reader->createOptionsWithFlatBuffers(objectData, _builder)); } // children bool containChildrenElement = false; const tinyxml2::XMLElement* child = objectData->FirstChildElement(); while (child) { // CCLOG("child name = %s", child->Name()); if (strcmp("Children", child->Name()) == 0) { containChildrenElement = true; break; } child = child->NextSiblingElement(); } if (containChildrenElement) { child = child->FirstChildElement(); // CCLOG("element name = %s", child->Name()); while (child) { const tinyxml2::XMLAttribute* attribute = child->FirstAttribute(); bool bHasType = false; while (attribute) { std::string attriname = attribute->Name(); std::string value = attribute->Value(); if (attriname == "ctype") { children.push_back(createNodeTreeForSimulator(child, value)); bHasType = true; break; } attribute = attribute->Next(); } if(!bHasType) { children.push_back(createNodeTreeForSimulator(child, "NodeObjectData")); } child = child->NextSiblingElement(); } } // std::string customClassName = ""; const tinyxml2::XMLAttribute* attribute = objectData->FirstAttribute(); while (attribute) { std::string attriname = attribute->Name(); std::string value = attribute->Value(); if (attriname == "CustomClassName") { customClassName = value; break; } attribute = attribute->Next(); } return CreateNodeTree(*_builder, _builder->CreateString(classname), _builder->CreateVector(children), options, _builder->CreateString(customClassName)); } Offset<ProjectNodeOptions> FlatBuffersSerialize::createProjectNodeOptionsForSimulator(const tinyxml2::XMLElement *objectData) { auto temp = NodeReader::getInstance()->createOptionsWithFlatBuffers(objectData, _builder); auto nodeOptions = *(Offset<WidgetOptions>*)(&temp); std::string filename = ""; // FileData const tinyxml2::XMLElement* child = objectData->FirstChildElement(); while (child) { std::string name = child->Name(); if (name == "FileData") { const tinyxml2::XMLAttribute* attribute = child->FirstAttribute(); while (attribute) { name = attribute->Name(); std::string value = attribute->Value(); if (name == "Path") { filename = value; } attribute = attribute->Next(); } } child = child->NextSiblingElement(); } return CreateProjectNodeOptions(*_builder, nodeOptions, _builder->CreateString(filename)); } } /**/
32.272351
128
0.511787
[ "vector" ]
26bd30c529898af4eae1e07bcf1b9a8b24f090df
517
cpp
C++
leetcode/837. New 21 Game/s3.cpp
zhuohuwu0603/leetcode_cpp_lzl124631x
6a579328810ef4651de00fde0505934d3028d9c7
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/837. New 21 Game/s3.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/837. New 21 Game/s3.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/new-21-game/ // Author: github.com/lzl124631x // Time: O(K + W) // Space: O(K + W) class Solution { public: double new21Game(int N, int K, int W) { if (!K || N >= K + W - 1) return 1; vector<double> dp(K + W); for (int i = K; i < K + W && i <= N; ++i) dp[i] = 1; double sum = min(N - K + 1, W); for (int i = K - 1; i >= 0; --i) { dp[i] = sum / W; sum += dp[i] - dp[i + W]; } return dp[0]; } }
28.722222
60
0.431335
[ "vector" ]
26bf6e6505b69c9dfe14bb2690d8e58345fbd236
34,914
cpp
C++
libstorage/CachedStorage.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
libstorage/CachedStorage.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
libstorage/CachedStorage.cpp
imtypist/FISCO-BCOS
30a281d31e83ca666ef203193963a6d32e39e36a
[ "Apache-2.0" ]
null
null
null
/* * @CopyRight: * FISCO-BCOS 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. * * FISCO-BCOS 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 FISCO-BCOS. If not, see <http://www.gnu.org/licenses/> * (c) 2016-2018 fisco-dev contributors. */ /** @file storage.h * @author monan * @date 20190409 */ #include "CachedStorage.h" #include "StorageException.h" #include <libdevcore/Common.h> #include <libdevcore/FixedHash.h> #include <tbb/concurrent_vector.h> #include <tbb/parallel_for.h> #include <tbb/parallel_for_each.h> #include <tbb/parallel_sort.h> #include <thread> using namespace std; using namespace dev; using namespace dev::storage; Cache::Cache() { m_entries = std::make_shared<Entries>(); m_num.store(0); } std::string Cache::key() { return m_key; } void Cache::setKey(const std::string& key) { m_key = key; } Entries::Ptr Cache::entries() { return m_entries; } Entries* Cache::entriesPtr() { return m_entries.get(); } void Cache::setEntries(Entries::Ptr entries) { m_entries = entries; } uint64_t Cache::num() const { return m_num; } void Cache::setNum(int64_t num) { m_num = num; } Cache::RWMutex* Cache::mutex() { return &m_mutex; } bool Cache::empty() { return m_empty; } void Cache::setEmpty(bool empty) { m_empty = empty; } TableInfo::Ptr Cache::tableInfo() { return m_tableInfo; } void Cache::setTableInfo(TableInfo::Ptr tableInfo) { m_tableInfo = tableInfo; } CachedStorage::CachedStorage(dev::GROUP_ID const& _groupID) : m_groupID(_groupID) { CACHED_STORAGE_LOG(INFO) << "Init flushStorage thread"; m_taskThreadPool = std::make_shared<dev::ThreadPool>("taskPool-" + std::to_string(m_groupID), 1); m_asyncThreadPool = std::make_shared<dev::ThreadPool>("touchMRU-" + std::to_string(m_groupID), 1); m_mruQueue = std::make_shared<tbb::concurrent_queue<std::tuple<std::string, std::string, ssize_t>>>(); m_mru = std::make_shared<boost::multi_index_container<std::pair<std::string, std::string>, boost::multi_index::indexed_by<boost::multi_index::sequenced<>, boost::multi_index::hashed_unique< boost::multi_index::identity<std::pair<std::string, std::string>>>>>>(); m_syncNum.store(0); m_commitNum.store(0); m_capacity.store(0); m_hitTimes.store(0); m_queryTimes.store(0); m_running = std::make_shared<tbb::atomic<bool>>(); m_running->store(true); } CachedStorage::~CachedStorage() { if (m_running->load()) { stop(); } } Entries::Ptr CachedStorage::select( int64_t num, TableInfo::Ptr tableInfo, const std::string& key, Condition::Ptr condition) { auto out = std::make_shared<Entries>(); auto result = selectNoCondition(num, tableInfo, key, condition); Cache::Ptr caches = std::get<1>(result); for (auto entry : *(caches->entries())) { if (condition && !condition->process(entry)) { continue; } auto outEntry = std::make_shared<Entry>(); outEntry->copyFrom(entry); out->addEntry(outEntry); } return out; } std::tuple<std::shared_ptr<Cache::RWScoped>, Cache::Ptr> CachedStorage::selectNoCondition( int64_t num, TableInfo::Ptr tableInfo, const std::string& key, Condition::Ptr condition) { (void)condition; if (!tableInfo->enableCache) { std::shared_ptr<RWMutexScoped> emptyScoped; auto cache = std::make_shared<Cache>(); if (m_backend) { auto conditionKey = std::make_shared<Condition>(); conditionKey->EQ(tableInfo->key, key); auto backendData = m_backend->select(num, tableInfo, key, conditionKey); cache->setEntries(backendData); cache->setEmpty(false); } else { CACHED_STORAGE_LOG(FATAL) << "backend storage doesn't set."; } return std::make_tuple(emptyScoped, cache); } auto result = touchCache(tableInfo, key, true); auto caches = std::get<1>(result); if (caches->empty()) { if (m_backend) { auto conditionKey = std::make_shared<Condition>(); conditionKey->EQ(tableInfo->key, key); auto backendData = m_backend->select(num, tableInfo, key, conditionKey); CACHED_STORAGE_LOG(TRACE) << tableInfo->name << ": " << key << " miss the cache"; caches->setEntries(backendData); caches->setEmpty(false); size_t totalCapacity = 0; for (auto it : *backendData) { totalCapacity += it->capacity(); } touchMRU(tableInfo->name, key, totalCapacity); } else { CACHED_STORAGE_LOG(FATAL) << "backend storage doesn't set."; } } else { touchMRU(tableInfo->name, key, 0); } return std::make_tuple(std::get<0>(result), caches); } size_t CachedStorage::commit(int64_t num, const std::vector<TableData::Ptr>& datas) { CACHED_STORAGE_LOG(INFO) << "commit: " << datas.size() << " num: " << num; tbb::atomic<size_t> total = 0; TIME_RECORD("Process dirty entries"); std::shared_ptr<std::vector<TableData::Ptr>> commitDatas = std::make_shared<std::vector<TableData::Ptr>>(); commitDatas->resize(datas.size()); tbb::parallel_for( tbb::blocked_range<size_t>(0, datas.size()), [&](const tbb::blocked_range<size_t>& range) { for (size_t idx = range.begin(); idx < range.end(); ++idx) { auto requestData = datas[idx]; auto commitData = std::make_shared<TableData>(); commitData->info = requestData->info; if (!commitData->info->enableCache) { commitData->dirtyEntries->shallowFrom(requestData->dirtyEntries); } else { commitData->dirtyEntries->resize(requestData->dirtyEntries->size()); // addtion data std::set<std::string> addtionKey; std::set<uint64_t> duplicateIDs; tbb::spin_mutex addtionKeyMutex; tbb::parallel_for( tbb::blocked_range<size_t>(0, requestData->dirtyEntries->size()), [&](const tbb::blocked_range<size_t>& rangeEntries) { for (size_t i = rangeEntries.begin(); i < rangeEntries.end(); ++i) { ++total; auto entry = requestData->dirtyEntries->get(i); auto key = entry->getField(requestData->info->key); auto id = entry->getID(); ssize_t change = 0; if (id == 0) { // impossible, should exit CACHED_STORAGE_LOG(FATAL) << "Dirty entry id equal to 0, table: " << requestData->info->name << LOG_KV("key", key); } else { auto result = touchCache(requestData->info, key, true); auto caches = std::get<1>(result); if (caches->empty()) { if (m_backend) { auto conditionKey = std::make_shared<Condition>(); conditionKey->EQ(requestData->info->key, key); auto backendData = m_backend->select( num, requestData->info, key, conditionKey); CACHED_STORAGE_LOG(DEBUG) << requestData->info->name << "-" << key << " miss the cache while commit dirty entries"; caches->setEntries(backendData); size_t totalCapacity = 0; for (auto it : *backendData) { totalCapacity += it->capacity(); } touchMRU(requestData->info->name, key, totalCapacity); } restoreCache(requestData->info, key, caches); } caches->setNum(num); caches->setEmpty(false); auto entryIt = std::lower_bound(caches->entries()->begin(), caches->entries()->end(), entry, [](const Entry::Ptr& lhs, const Entry::Ptr& rhs) { return lhs->getID() < rhs->getID(); }); if (entryIt != caches->entries()->end() && (*entryIt)->getID() == id) { auto oldSize = (*entryIt)->capacity(); for (auto fieldIt : *entry) { (*entryIt)->setField(fieldIt.first, fieldIt.second); } (*entryIt)->setStatus(entry->getStatus()); change = (ssize_t)( (ssize_t)(*entryIt)->capacity() - (ssize_t)oldSize); (*entryIt)->setNum(num); auto commitEntry = std::make_shared<Entry>(); commitEntry->copyFrom(*entryIt); (*commitData->dirtyEntries)[i] = commitEntry; if (m_backend && !m_backend->onlyCommitDirty()) { // Only for RocksDB tbb::spin_mutex::scoped_lock lock(addtionKeyMutex); auto inserted = addtionKey.insert(key).second; if (inserted) { for (auto it = caches->entries()->begin(); it != caches->entries()->end(); ++it) { if (it != entryIt) { // This addEntry is necessary, because // backend storage processDirtyEntries() // will not get data from real DB auto copyLostEntry = make_shared<Entry>(); copyLostEntry->copyFrom(*it); commitData->dirtyEntries->addEntry( copyLostEntry); } } } else { CACHED_STORAGE_LOG(DEBUG) << LOG_BADGE("duplicate entry") << LOG_KV("key", key) << LOG_KV("ID", (*entryIt)->getID()); duplicateIDs.insert((*entryIt)->getID()); } } } else { // impossible, should exit stringstream ss; ss << ", the cache of key:" << key << " has entries:"; for (auto it = caches->entries()->begin(); it != caches->entries()->end(); ++it) { ss << (*it)->getID() << " "; } CACHED_STORAGE_LOG(FATAL) << "Can not find entry in cache, key:" << key << LOG_KV("num", num) << ",id " << id << " != " << (*entryIt)->getID() << ss.str(); } } touchMRU(requestData->info->name, key, change); } }); tbb::parallel_for(tbb::blocked_range<size_t>(requestData->dirtyEntries->size(), commitData->dirtyEntries->size()), [&](const tbb::blocked_range<size_t>& rangeEntries) { for (size_t i = rangeEntries.begin(); i < rangeEntries.end(); ++i) { // remove duplicate entries, rocksdb need this if (duplicateIDs.find((*commitData->dirtyEntries)[i]->getID()) != duplicateIDs.end()) { auto duplicateEntry = make_shared<Entry>(); duplicateEntry->copyFrom((*commitData->dirtyEntries)[i]); duplicateEntry->setDeleted(true); (*commitData->dirtyEntries)[i] = duplicateEntry; } } }); tbb::parallel_sort(commitData->dirtyEntries->begin(), commitData->dirtyEntries->end(), EntryLessNoLock(commitData->info)); } commitData->newEntries->shallowFrom(requestData->newEntries); (*commitDatas)[idx] = commitData; } }); TIME_RECORD("Process new entries"); auto commitDatasSize = commitDatas->size(); // Cache the key corresponding to each table newEntries std::shared_ptr<std::vector<tbb::concurrent_unordered_set<std::string>>> processedKeys = std::make_shared<std::vector<tbb::concurrent_unordered_set<std::string>>>( commitDatasSize, tbb::concurrent_unordered_set<std::string>()); tbb::parallel_for(tbb::blocked_range<size_t>(0, commitDatasSize), [&](const tbb::blocked_range<size_t>& range) { for (size_t i = range.begin(); i < range.end(); ++i) { auto commitData = (*commitDatas)[i]; if (!commitData->info->enableCache) { continue; } auto newEntriesSize = commitData->newEntries->size(); tbb::parallel_for(tbb::blocked_range<size_t>(0, newEntriesSize), [&](const tbb::blocked_range<size_t>& range) { for (size_t j = range.begin(); j < range.end(); ++j) { auto commitEntry = commitData->newEntries->get(j); commitEntry->setNum(num); ++total; auto key = commitEntry->getField(commitData->info->key); (*processedKeys)[i].insert(key); auto cacheEntry = std::make_shared<Entry>(); cacheEntry->copyFrom(commitEntry); if (cacheEntry->force()) { auto result = touchCache(commitData->info, key, true); auto caches = std::get<1>(result); caches->setNum(num); caches->entries()->addEntry(cacheEntry); caches->setEmpty(false); } else { auto result = touchCache(commitData->info, key, true); auto caches = std::get<1>(result); if (caches->empty()) { if (m_backend) { auto conditionKey = std::make_shared<Condition>(); conditionKey->EQ(commitData->info->key, key); auto backendData = m_backend->select( num, commitData->info, key, conditionKey); CACHED_STORAGE_LOG(TRACE) << commitData->info->name << "-" << key << " miss the cache while commit new entries"; caches->setEntries(backendData); size_t totalCapacity = 0; for (auto it : *backendData) { totalCapacity += it->capacity(); } #if 0 CACHED_STORAGE_LOG(TRACE) << "backend capacity: " << commitData->info->name << "-" << key << ", capacity: " << totalCapacity; #endif touchMRU(commitData->info->name, key, totalCapacity); } restoreCache(commitData->info, key, caches); } caches->entries()->addEntry(cacheEntry); caches->setNum(num); caches->setEmpty(false); } #if 0 CACHED_STORAGE_LOG(TRACE) << "new cached: " << commitData->info->name << "-" << key << ", capacity: " << cacheEntry->capacity(); #endif touchMRU(commitData->info->name, key, cacheEntry->capacity()); } }); } }); // sort the caches TIME_RECORD("sort caches"); sortCaches(commitDatas, processedKeys); if (m_backend) { TIME_RECORD("Submit commit task"); // new task write to backend Task::Ptr task = std::make_shared<Task>(); task->num = num; task->datas = commitDatas; auto backend = m_backend; auto self = std::weak_ptr<CachedStorage>( std::dynamic_pointer_cast<CachedStorage>(shared_from_this())); m_commitNum.store(num); if (!disabled()) { m_taskThreadPool->enqueue([task, self]() { auto storage = self.lock(); if (storage) { storage->commitBackend(task); } }); CACHED_STORAGE_LOG(INFO) << "Submited block task: " << num << ", current syncd block: " << m_syncNum; uint64_t waitCount = 0; while (((size_t)(m_commitNum - m_syncNum) > m_maxForwardBlock) && m_running->load()) { CACHED_STORAGE_LOG(INFO) << "Current block number: " << m_commitNum << " greater than syncd block number: " << m_syncNum << ", waiting..."; if (waitCount < 5) { std::this_thread::yield(); } else { std::this_thread::sleep_for( std::chrono::milliseconds((waitCount < 100 ? waitCount : 100) * 50)); } ++waitCount; } } else { if (!commitBackend(task)) { m_running->store(false); m_taskThreadPool->stop(); raise(SIGTERM); BOOST_THROW_EXCEPTION(StorageException(-1, std::string("backend DB dead!"))); } } } else { CACHED_STORAGE_LOG(INFO) << "No backend storage, skip commit..."; setSyncNum(num); } return total; } void CachedStorage::sortCaches(std::shared_ptr<std::vector<TableData::Ptr>> _commitDatas, std::shared_ptr<std::vector<tbb::concurrent_unordered_set<std::string>>> _processedKeys) { auto commitDataSize = _commitDatas->size(); tbb::parallel_for(tbb::blocked_range<size_t>(0, commitDataSize), [&](const tbb::blocked_range<size_t>& range) { for (size_t i = range.begin(); i < range.end(); i++) { auto commitData = (*_commitDatas)[i]; auto processedKey = (*_processedKeys)[i]; // get caches and parallel sort the caches tbb::parallel_for(processedKey.range(), [&](tbb::concurrent_unordered_set<std::string>::range_type& range) { for (auto it = range.begin(); it != range.end(); ++it) { auto result = touchCache(commitData->info, *it, true); auto caches = std::get<1>(result); tbb::parallel_sort(caches->entries()->begin(), caches->entries()->end(), EntryLessNoLock(commitData->info)); } }); } }); } void CachedStorage::setBackend(Storage::Ptr backend) { m_backend = backend; } void CachedStorage::init() { if (!disabled()) { startClearThread(); } } void CachedStorage::stop() { if (!m_running) { CACHED_STORAGE_LOG(INFO) << LOG_DESC("already stopped!"); return; } CACHED_STORAGE_LOG(INFO) << "Stopping flushStorage thread"; m_running->store(false); m_taskThreadPool->stop(); if (m_clearThread) { if (m_clearThread->get_id() != std::this_thread::get_id()) { m_clearThread->join(); m_clearThread.reset(); } else { m_clearThread->detach(); } } CACHED_STORAGE_LOG(INFO) << "flushStorage thread stopped."; } void CachedStorage::clear() { RWMutexScoped lockCache(m_cachesMutex, true); m_caches.clear(); } int64_t CachedStorage::syncNum() { return m_syncNum; } void CachedStorage::setSyncNum(int64_t syncNum) { m_syncNum.store(syncNum); } void CachedStorage::setMaxCapacity(int64_t maxCapacity) { m_maxCapacity = maxCapacity; } void CachedStorage::setMaxForwardBlock(size_t maxForwardBlock) { m_maxForwardBlock = maxForwardBlock; } void CachedStorage::startClearThread() { std::weak_ptr<CachedStorage> self(std::dynamic_pointer_cast<CachedStorage>(shared_from_this())); auto running = m_running; auto groupID = m_groupID; m_clearThread = std::make_shared<std::thread>([running, self, groupID]() { dev::pthread_setThreadName("MemClear-" + to_string(groupID)); while (true) { auto storage = self.lock(); if (storage && running->load()) { std::this_thread::sleep_for(std::chrono::milliseconds(storage->m_clearInterval)); storage->checkAndClear(); } else { return; } } }); } void CachedStorage::touchMRU(const std::string& table, const std::string& key, ssize_t capacity) { if (disabled()) { return; } m_asyncThreadPool->enqueue([this, table, key, capacity]() { m_mruQueue->push(std::make_tuple(table, key, capacity)); }); } void CachedStorage::updateMRU(const std::string& table, const std::string& key, ssize_t capacity) { if (capacity != 0) { updateCapacity(capacity); } auto r = m_mru->push_back(std::make_pair(table, key)); if (!r.second) { m_mru->relocate(m_mru->end(), r.first); } } std::tuple<std::shared_ptr<Cache::RWScoped>, Cache::Ptr, bool> CachedStorage::touchCache( TableInfo::Ptr tableInfo, const std::string& key, bool write) { bool hit = true; ++m_queryTimes; auto cache = std::make_shared<Cache>(); auto cacheKey = tableInfo->name + "_" + key; bool inserted = false; { RWMutexScoped lockCache(m_cachesMutex, false); auto result = m_caches.insert(std::make_pair(cacheKey, cache)); cache = result.first->second; inserted = result.second; } auto cacheLock = std::make_shared<Cache::RWScoped>(*(cache->mutex()), write); if (inserted) { hit = false; cache->setKey(key); cache->setTableInfo(tableInfo); } else { RWMutexScoped lockCache(m_cachesMutex, false); auto result = m_caches.insert(std::make_pair(cacheKey, cache)); if (!result.second && cache != result.first->second) { cache = result.first->second; cacheLock.reset(); cacheLock = std::make_shared<Cache::RWScoped>(*(cache->mutex()), write); } } if (hit) { ++m_hitTimes; } return std::make_tuple(cacheLock, cache, true); } void CachedStorage::restoreCache(TableInfo::Ptr table, const std::string& key, Cache::Ptr cache) { /* If the checkAndClear() run ahead of commit() at same key, commit() may flush data to the cache object which erased in m_caches, the data will lost, to avoid this, re-insert the data into the m_caches */ RWMutexScoped lockCache(m_cachesMutex, false); auto cacheKey = table->name + "_" + key; auto result = m_caches.insert(std::make_pair(cacheKey, cache)); if (!result.second && result.first->second != cache) { CACHED_STORAGE_LOG(FATAL) << "Restore cache fail! Cache not equal: " << cacheKey << " " << result.first->second << " " << cache; exit(1); } } void CachedStorage::removeCache(const std::string& table, const std::string& key) { auto cacheKey = table + "_" + key; RWMutexScoped lockCache; while (true) { if (lockCache.try_acquire(m_cachesMutex, true)) { break; } std::this_thread::yield(); } auto c = m_caches.unsafe_erase(cacheKey); if (c != 1) { CACHED_STORAGE_LOG(FATAL) << "Can not remove cache: " << table << "-" << key; exit(1); } } bool CachedStorage::disabled() { return ((m_maxCapacity == 0) && (m_maxForwardBlock == 0)); } bool CachedStorage::commitBackend(Task::Ptr task) { auto now = std::chrono::steady_clock::now(); CACHED_STORAGE_LOG(INFO) << "Start commit block: " << task->num << " to backend storage"; try { m_backend->commit(task->num, *(task->datas)); setSyncNum(task->num); std::chrono::duration<double> elapsed = std::chrono::steady_clock::now() - now; CACHED_STORAGE_LOG(INFO) << "\n---------------------------------------------------------------------\n" << "Commit block: " << task->num << " to backend storage finished, current cached block: " << m_commitNum << "\n" << "Flush elapsed time: " << std::setiosflags(std::ios::fixed) << std::setprecision(4) << elapsed.count() << "s" << "\n---------------------------------------------------------------------\n"; if (disabled()) { clear(); } } catch (std::exception& e) { // stop() commit thread to exit m_running->store(false); m_taskThreadPool->stop(); raise(SIGTERM); CACHED_STORAGE_LOG(ERROR) << "Stop commit thread. Fail to commit data: " << e.what(); return false; } return true; } void CachedStorage::checkAndClear() { uint64_t count = 0; // calculate and calculate m_capacity with all elements of m_mruQueue // since inner loop will break once m_mruQueue is empty, here use while(true) while (true) { std::tuple<std::string, std::string, ssize_t> mru; auto result = m_mruQueue->try_pop(mru); if (!result) { break; } updateMRU(std::get<0>(mru), std::get<1>(mru), std::get<2>(mru)); ++count; } CACHED_STORAGE_LOG(DEBUG) << "CheckAndClear pop: " << count << " elements"; TIME_RECORD("Check and clear"); bool needClear = false; size_t clearTimes = 0; auto currentCapacity = m_capacity.load(); size_t clearCount = 0; size_t clearThrough = 0; do { needClear = false; if (m_syncNum > 0) { if (m_capacity > m_maxCapacity && !m_mru->empty()) { needClear = true; } } if (needClear) { for (auto it = m_mru->begin(); it != m_mru->end() && m_running->load();) { if (m_capacity <= (int64_t)m_maxCapacity || m_mru->empty()) { break; } ++clearThrough; auto tableInfo = std::make_shared<TableInfo>(); tableInfo->name = it->first; // The life cycle of the cache must be longer than the result, because the // deconstruction order of the tuple is related to the gcc version and the compiler. // It must be ensured that RWMutexScoped is deconstructed first, and the cache is // deconstructed, otherwise the program will coredump Cache::Ptr cache; auto result = touchCache(tableInfo, it->second, true); cache = std::get<1>(result); if (std::get<2>(result)) { // FIXME: if always true, simplify this if (m_syncNum > 0 && (cache->num() <= m_syncNum)) { int64_t totalCapacity = 0; for (auto entryIt : *(cache->entries())) { totalCapacity += entryIt->capacity(); } ++clearCount; updateCapacity(0 - totalCapacity); cache->setEmpty(true); removeCache(it->first, it->second); it = m_mru->erase(it); } else { break; } } else { ++it; } } ++clearTimes; } } while (needClear && m_running->load()); if (clearThrough > 0) { CACHED_STORAGE_LOG(INFO) << "Clear finished, total: " << clearCount << " entries, " << "through: " << clearThrough << " entries, " << readableCapacity(currentCapacity - m_capacity) << ", Current total entries: " << m_caches.size() << ", Current total mru entries: " << m_mru->size() << ", total capacaity: " << readableCapacity(m_capacity); CACHED_STORAGE_LOG(DEBUG) << "Cache Status: \n\n" << "\n---------------------------------------------------------------------\n" << "Total query: " << m_queryTimes << "\n" << "Total cache hit: " << m_hitTimes << "\n" << "Total cache miss: " << m_queryTimes - m_hitTimes << "\n" << "Total hit ratio: " << std::setiosflags(std::ios::fixed) << std::setprecision(4) << ((double)m_hitTimes / m_queryTimes) * 100 << "%" << "\n\n" << "Cache capacity: " << readableCapacity(m_capacity) << "\n" << "Cache size: " << m_mru->size() << "\n---------------------------------------------------------------------\n"; } } void CachedStorage::updateCapacity(ssize_t capacity) { m_capacity.fetch_and_add(capacity); } std::string CachedStorage::readableCapacity(size_t num) { std::stringstream capacityNum; if (num > 1024 * 1024 * 1024) { capacityNum << std::setiosflags(std::ios::fixed) << std::setprecision(4) << ((double)num / (1024 * 1024 * 1024)) << " GB"; } else if (num > 1024 * 1024) { capacityNum << std::setiosflags(std::ios::fixed) << std::setprecision(4) << ((double)num / (1024 * 1024)) << " MB"; } else if (num > 1024) { capacityNum << std::setiosflags(std::ios::fixed) << std::setprecision(4) << ((double)num / (1024)) << " KB"; } else { capacityNum << num << " B"; } return capacityNum.str(); }
35.338057
100
0.458928
[ "object", "vector" ]
26c45d1ae5f25c6b01eb15475994498e87eb1dc5
1,017
hpp
C++
sln/Tools/MixedFEM.hpp
frfly/CATSPDEs
41bcc7cf4fe5636572603199e807fa6c7c25dd93
[ "MIT" ]
3
2019-09-09T13:30:40.000Z
2021-04-24T19:37:44.000Z
sln/Tools/MixedFEM.hpp
frfly/CATSPDEs
41bcc7cf4fe5636572603199e807fa6c7c25dd93
[ "MIT" ]
1
2016-04-10T09:07:58.000Z
2016-04-10T09:07:58.000Z
sln/Tools/MixedFEM.hpp
frfly/Solving-elliptic-equation-using-FEM
41bcc7cf4fe5636572603199e807fa6c7c25dd93
[ "MIT" ]
6
2016-12-08T15:45:37.000Z
2022-03-26T21:44:50.000Z
#pragma once // tools #include <boost/tuple/tuple.hpp> #pragma once // mesh #include "Triangulation.hpp" // PDE #include "OseenProblem.hpp" #include "BoundaryCondition.hpp" // FEs #include "AbstractFiniteElement.hpp" // for global system matrix #include "CSlCMatrix.hpp" #include "CSCMatrix.hpp" namespace FEM { namespace Mixed { boost::tuple< CSlCMatrix<double>, // diffusion + convection + reaction matrix CSCMatrix<double>, CSCMatrix<double>, // divirgence matrices std::vector<double> // rhs vector > assembleSystem( OseenProblem2D const &, // (1) PDE, Triangulation const &, // (2) discretized domain (mesh), and BCs that connects (1) and (2): VectorBoundaryCondition2D const &, // natural BC, VectorBoundaryCondition2D const &, // essential BC; TriangularScalarFiniteElement const &, // for each velocity component TriangularScalarFiniteElement const &, // for pressure boost::optional<Index&> activeElementIndex = boost::none // index of the active element ); } }
27.486486
94
0.718781
[ "mesh", "vector" ]
26c8c6742bba67bcb6ec4dc26e6c91faeeaf4648
2,405
cpp
C++
base/resource/ResourceGroup.cpp
dispyfree/xhstt
12059c96dbdecddf9495d16bdd81b905f9986960
[ "MIT" ]
null
null
null
base/resource/ResourceGroup.cpp
dispyfree/xhstt
12059c96dbdecddf9495d16bdd81b905f9986960
[ "MIT" ]
null
null
null
base/resource/ResourceGroup.cpp
dispyfree/xhstt
12059c96dbdecddf9495d16bdd81b905f9986960
[ "MIT" ]
null
null
null
/* * File: ResourceGroup.cpp * */ #include "ResourceGroup.h" #include "ResourceType.h" #include "ObjectCreation.h" #include "Instance.h" #include "Resource.h" using namespace khe; ResourceGroup::ResourceGroup(ResourceType t, const std::string &id, const std::string &name, bool isPartition){ if(!KheResourceGroupMake(t, Util::sTc(id), Util::sTc(id), isPartition, &grp)) throw ObjectCreation("Unable to create object of type ResourceGroup"); } ResourceGroup::ResourceGroup(KHE_RESOURCE_GROUP t){ Util::rnn(t); grp = t; } ResourceGroup::~ResourceGroup() { } void ResourceGroup::setBack(void *back){ KheResourceGroupSetBack(grp, back); } ResourceType ResourceGroup::getType() const{ return KheResourceGroupResourceType(grp); } Instance ResourceGroup::getInstance() const{ return KheResourceGroupInstance(grp); } std::string ResourceGroup::getId() const{ return KheResourceGroupId(grp); } std::string ResourceGroup::getName() const{ return KheResourceGroupName(grp); } bool ResourceGroup::isPartition() const{ return KheResourceGroupIsPartition(grp); } void ResourceGroup::add(Resource r){ KheResourceGroupAddResource(grp, r); } ResourceGroup &ResourceGroup::operator+=(const Resource &r){ add(r); } void ResourceGroup::sub(Resource r){ KheResourceGroupSubResource(grp, r); } ResourceGroup &ResourceGroup::operator-=(const Resource &r){ sub(r); } void ResourceGroup::doUnion(ResourceGroup b){ KheResourceGroupUnion(grp, b); } void ResourceGroup::intersect(ResourceGroup b){ KheResourceGroupIntersect(grp, b); } void ResourceGroup::difference(ResourceGroup b){ KheResourceGroupDifference(grp, b); } IR<Resource> ResourceGroup::getResources() const{ return createIter<Resource>(*this); } bool ResourceGroup::contains(const Resource &r) const{ KheResourceGroupContains(grp, r); } bool ResourceGroup::equals(const ResourceGroup &r) const{ KheResourceGroupEqual(grp, r); } bool ResourceGroup::isSubSet(const ResourceGroup &b) const{ KheResourceGroupSubset(grp, b); } bool ResourceGroup::operator<=(const ResourceGroup &b) const{ return isSubSet(b); } bool ResourceGroup::isDisjoint(const ResourceGroup &b) const{ return KheResourceGroupDisjoint(grp, b); } ResourceGroup ResourceGroup::getPartition() const{ return KheResourceGroupPartition(grp); }
22.688679
111
0.728898
[ "object" ]
26d4ccebe818fd25654b04f20f1a6c4f3b30efc2
3,995
cc
C++
mindspore/ccsrc/plugin/device/cpu/kernel/dynamic_stitch_cpu_kernel.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
1
2022-03-05T02:59:21.000Z
2022-03-05T02:59:21.000Z
mindspore/ccsrc/plugin/device/cpu/kernel/dynamic_stitch_cpu_kernel.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/plugin/device/cpu/kernel/dynamic_stitch_cpu_kernel.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021-2022 Huawei Technologies Co., Ltd * * 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 "plugin/device/cpu/kernel/dynamic_stitch_cpu_kernel.h" #include <functional> #include <algorithm> #include "plugin/device/cpu/hal/device/cpu_device_address.h" namespace mindspore { namespace kernel { namespace { constexpr size_t kDynamicStitchOutputNum = 1; } // namespace template <typename T> void DynamicStitchCpuKernelMod<T>::InitKernel(const CNodePtr &kernel_node) { cnode_ptr_ = kernel_node; } size_t GetShapeSize(const std::vector<size_t> &shape) { return std::accumulate(shape.begin(), shape.end(), size_t(1), std::multiplies<size_t>()); } template <typename T> void DynamicStitchCpuKernelMod<T>::LaunchKernel(const std::vector<kernel::AddressPtr> &inputs, const std::vector<kernel::AddressPtr> &outputs) { CHECK_KERNEL_OUTPUTS_NUM(outputs.size(), kDynamicStitchOutputNum, kernel_name_); auto node_ = cnode_ptr_.lock(); int first_dim_size = 0; size_t input_count = common::AnfAlgo::GetInputTensorNum(node_); input_tuple_num_ = input_count / 2; int max_index = -1; for (size_t i = 0; i < input_tuple_num_; ++i) { auto indice = reinterpret_cast<int32_t *>(inputs[i]->addr); auto shape_size = GetShapeSize(common::AnfAlgo::GetPrevNodeOutputInferShape(node_, i)); for (size_t j = 0; j < shape_size; ++j) { max_index = std::max(indice[j], max_index); } } first_dim_size = max_index + 1; std::vector<TypeId> dtypes{AnfAlgo::GetOutputDeviceDataType(node_, 0)}; std::vector<size_t> result_shape{IntToSize(first_dim_size)}; auto data0_shape = common::AnfAlgo::GetPrevNodeOutputInferShape(node_, input_tuple_num_); auto indice_dims = common::AnfAlgo::GetPrevNodeOutputInferShape(node_, 0).size(); for (size_t d = indice_dims; d < data0_shape.size(); ++d) { result_shape.emplace_back(data0_shape[d]); } common::AnfAlgo::SetOutputInferTypeAndShape(dtypes, {result_shape}, node_.get()); size_t num_out_dims = 2; std::vector<size_t> out_dims(num_out_dims, 0); for (size_t out_dim = 0; out_dim <= num_out_dims - 1; ++out_dim) { out_dims[out_dim] = out_dim >= result_shape.size() ? 1 : result_shape[out_dim]; } for (size_t in_dim = num_out_dims; in_dim < result_shape.size(); ++in_dim) { out_dims[num_out_dims - 1] *= result_shape[in_dim]; } auto merged = reinterpret_cast<T *>(outputs[0]->addr); size_t slice_size = out_dims[1]; size_t slice_bytes = slice_size * sizeof(T); for (size_t i = 0; i < input_tuple_num_; i++) { auto indice = reinterpret_cast<int32_t *>(inputs[i]->addr); auto data = reinterpret_cast<T *>(inputs[i + input_tuple_num_]->addr); auto shape_size = GetShapeSize(common::AnfAlgo::GetPrevNodeOutputInferShape(node_, i)); for (size_t j = 0; j < shape_size; ++j) { auto ret = memcpy_s(merged + indice[j] * slice_size, slice_bytes, data + j * slice_size, slice_bytes); if (ret != 0) { MS_LOG(EXCEPTION) << "For '" << kernel_name_ << "', memcpy_s error. Error no: " << ret; } } } } template <typename T> bool DynamicStitchCpuKernelMod<T>::Launch(const std::vector<kernel::AddressPtr> &inputs, const std::vector<kernel::AddressPtr> &, const std::vector<kernel::AddressPtr> &outputs) { LaunchKernel(inputs, outputs); return true; } } // namespace kernel } // namespace mindspore
40.765306
108
0.691865
[ "shape", "vector" ]
26d60334c4236cf45f34215fc6cc7dd0141196b2
49,843
cc
C++
chrome/browser/ui/webui/signin/profile_picker_handler.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/webui/signin/profile_picker_handler.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ui/webui/signin/profile_picker_handler.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/signin/profile_picker_handler.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/check.h" #include "base/containers/cxx20_erase.h" #include "base/feature_list.h" #include "base/json/values_util.h" #include "base/metrics/histogram_functions.h" #include "base/notreached.h" #include "base/strings/utf_string_conversions.h" #include "base/trace_event/trace_event.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/first_web_contents_profiler_base.h" #include "chrome/browser/new_tab_page/chrome_colors/chrome_colors_service.h" #include "chrome/browser/new_tab_page/chrome_colors/generated_colors_info.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_entry.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/profiles/profile_statistics.h" #include "chrome/browser/profiles/profile_statistics_factory.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/profiles/profiles_state.h" #include "chrome/browser/signin/signin_features.h" #include "chrome/browser/signin/signin_util.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/profile_picker.h" #include "chrome/browser/ui/signin/profile_colors_util.h" #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/webui/profile_helper.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/pref_names.h" #include "chrome/common/themes/autogenerated_theme_util.h" #include "chrome/common/webui_url_constants.h" #include "components/signin/public/identity_manager/account_info.h" #include "components/startup_metric_utils/browser/startup_metric_utils.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_ui.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/image/image.h" #if BUILDFLAG(IS_CHROMEOS_LACROS) #include "chrome/browser/lacros/account_manager/account_manager_util.h" #include "chrome/browser/lacros/account_manager/account_profile_mapper.h" #include "chrome/browser/lacros/lacros_url_handling.h" #include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom.h" #include "chrome/browser/ui/webui/signin/profile_picker_lacros_sign_in_provider.h" #include "components/account_manager_core/account.h" #endif namespace { const size_t kProfileCardAvatarSize = 74; const size_t kProfileCreationAvatarSize = 100; constexpr int kDefaultThemeColorId = -1; constexpr int kManuallyPickedColorId = 0; // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class ProfilePickerAction { kLaunchExistingProfile = 0, kLaunchExistingProfileCustomizeSettings = 1, kLaunchGuestProfile = 2, kLaunchNewProfile = 3, kDeleteProfile = 4, kMaxValue = kDeleteProfile, }; absl::optional<SkColor> GetChromeColorColorById(int color_id) { for (chrome_colors::ColorInfo color_info : chrome_colors::kGeneratedColorsInfo) { if (color_id == color_info.id) return color_info.color; } return absl::nullopt; } void RecordProfilePickerAction(ProfilePickerAction action) { base::UmaHistogramEnumeration("ProfilePicker.UserAction", action); } void RecordAskOnStartupChanged(bool value) { base::UmaHistogramBoolean("ProfilePicker.AskOnStartupChanged", value); } void RecordNewProfileSpec(absl::optional<SkColor> profile_color, bool create_shortcut) { int theme_id = profile_color.has_value() ? chrome_colors::ChromeColorsService::GetColorId(*profile_color) : chrome_colors::kDefaultColorId; base::UmaHistogramSparse("ProfilePicker.NewProfileTheme", theme_id); if (ProfileShortcutManager::IsFeatureEnabled()) { base::UmaHistogramBoolean("ProfilePicker.NewProfileCreateShortcut", create_shortcut); } } base::Value GetAutogeneratedProfileThemeInfoValue(int color_id, absl::optional<SkColor> color, SkColor frame_color, SkColor active_tab_color, SkColor frame_text_color, float scale_factor) { base::Value dict(base::Value::Type::DICTIONARY); dict.SetIntKey("colorId", color_id); if (color.has_value()) dict.SetIntKey("color", *color); dict.SetStringKey("themeFrameColor", color_utils::SkColorToRgbaString(frame_color)); dict.SetStringKey("themeShapeColor", color_utils::SkColorToRgbaString(active_tab_color)); dict.SetStringKey("themeFrameTextColor", color_utils::SkColorToRgbaString(frame_text_color)); gfx::Image icon = profiles::GetPlaceholderAvatarIconWithColors( /*fill_color=*/frame_color, /*stroke_color=*/GetAvatarStrokeColor(frame_color), kProfileCreationAvatarSize * scale_factor); dict.SetStringKey("themeGenericAvatar", webui::GetBitmapDataUrl(icon.AsBitmap())); return dict; } base::Value CreateDefaultProfileThemeInfo(float scale_factor, bool dark_mode) { SkColor frame_color = ThemeProperties::GetDefaultColor( ThemeProperties::COLOR_FRAME_ACTIVE, /*incognito=*/false, dark_mode); SkColor active_tab_color = ThemeProperties::GetDefaultColor( ThemeProperties::COLOR_TOOLBAR, /*incognito=*/false, dark_mode); SkColor frame_text_color = ThemeProperties::GetDefaultColor( ThemeProperties::COLOR_TAB_FOREGROUND_INACTIVE_FRAME_ACTIVE, /*incognito=*/false, dark_mode); return GetAutogeneratedProfileThemeInfoValue( kDefaultThemeColorId, absl::nullopt, frame_color, active_tab_color, frame_text_color, scale_factor); } base::Value CreateAutogeneratedProfileThemeInfo(int color_id, SkColor color, float scale_factor) { auto theme_colors = GetAutogeneratedThemeColors(color); SkColor frame_color = theme_colors.frame_color; SkColor active_tab_color = theme_colors.active_tab_color; SkColor frame_text_color = theme_colors.frame_text_color; return GetAutogeneratedProfileThemeInfoValue(color_id, color, frame_color, active_tab_color, frame_text_color, scale_factor); } void OpenOnSelectProfileTargetUrl(Browser* browser) { GURL target_page_url = ProfilePicker::GetOnSelectProfileTargetUrl(); if (target_page_url.is_empty()) return; if (target_page_url.spec() == chrome::kChromeUIHelpURL) { chrome::ShowAboutChrome(browser); } else if (target_page_url.spec() == chrome::kChromeUISettingsURL) { chrome::ShowSettings(browser); } else if (target_page_url.spec() == ProfilePicker::kTaskManagerUrl) { chrome::OpenTaskManager(browser); } else { NavigateParams params( GetSingletonTabNavigateParams(browser, target_page_url)); params.path_behavior = NavigateParams::RESPECT; ShowSingletonTabOverwritingNTP(browser, &params); } } base::Value CreateProfileEntry(const ProfileAttributesEntry* entry, int avatar_icon_size) { base::Value profile_entry(base::Value::Type::DICTIONARY); profile_entry.SetKey("profilePath", base::FilePathToValue(entry->GetPath())); profile_entry.SetStringKey("localProfileName", entry->GetLocalProfileName()); profile_entry.SetBoolKey( "isSyncing", entry->GetSigninState() == SigninState::kSignedInWithConsentedPrimaryAccount); profile_entry.SetBoolKey("needsSignin", entry->IsSigninRequired()); // GAIA full name/user name can be empty, if the profile is not signed in to // chrome. profile_entry.SetStringKey("gaiaName", entry->GetGAIAName()); profile_entry.SetStringKey("userName", entry->GetUserName()); profile_entry.SetBoolKey("isManaged", AccountInfo::IsManaged(entry->GetHostedDomain())); gfx::Image icon = profiles::GetSizedAvatarIcon(entry->GetAvatarIcon(avatar_icon_size), true, avatar_icon_size, avatar_icon_size); std::string icon_url = webui::GetBitmapDataUrl(icon.AsBitmap()); profile_entry.SetStringKey("avatarIcon", icon_url); #if BUILDFLAG(IS_CHROMEOS_LACROS) profile_entry.SetBoolKey("isPrimaryLacrosProfile", Profile::IsMainProfilePath(entry->GetPath())); #else profile_entry.SetBoolKey("isPrimaryLacrosProfile", false); #endif // BUILDFLAG(IS_CHROMEOS_LACROS) return profile_entry; } #if BUILDFLAG(IS_CHROMEOS_LACROS) base::FilePath GetCurrentProfilePath(content::WebUI* web_ui) { DCHECK(web_ui); return web_ui->GetWebContents()->GetBrowserContext()->GetPath(); } bool IsSelectingSecondaryAccount(content::WebUI* web_ui) { // If this WebUI page is rendered in a user profile (and not the default // picker profile), this means the page should show accounts that are // available as secondary for this specific profile. return GetCurrentProfilePath(web_ui) != ProfilePicker::GetPickerProfilePath(); } SkBitmap GetAvailableAccountBitmap(const gfx::Image& gaia_image, bool dark_mode) { if (!gaia_image.IsEmpty()) return gaia_image.AsBitmap(); // Return a default avatar. const int kAccountPictureSize = 128; ProfileThemeColors colors = GetDefaultProfileThemeColors(dark_mode); gfx::Image default_image = profiles::GetPlaceholderAvatarIconWithColors( colors.default_avatar_fill_color, colors.default_avatar_stroke_color, kAccountPictureSize); return default_image.AsBitmap(); } #endif // BUILDFLAG(IS_CHROMEOS_LACROS) void RecordProfilingFinishReason( metrics::StartupProfilingFinishReason finish_reason) { base::UmaHistogramEnumeration( "ProfilePicker.FirstProfileTime.FirstWebContentsFinishReason", finish_reason); } class FirstWebContentsProfilerForProfilePicker : public metrics::FirstWebContentsProfilerBase { public: explicit FirstWebContentsProfilerForProfilePicker( content::WebContents* web_contents, base::TimeTicks pick_time); FirstWebContentsProfilerForProfilePicker( const FirstWebContentsProfilerForProfilePicker&) = delete; FirstWebContentsProfilerForProfilePicker& operator=( const FirstWebContentsProfilerForProfilePicker&) = delete; protected: // FirstWebContentsProfilerBase: void RecordFinishReason( metrics::StartupProfilingFinishReason finish_reason) override; void RecordNavigationFinished(base::TimeTicks navigation_start) override; void RecordFirstNonEmptyPaint() override; bool WasStartupInterrupted() override; private: ~FirstWebContentsProfilerForProfilePicker() override; const base::TimeTicks pick_time_; }; FirstWebContentsProfilerForProfilePicker:: FirstWebContentsProfilerForProfilePicker(content::WebContents* web_contents, base::TimeTicks pick_time) : FirstWebContentsProfilerBase(web_contents), pick_time_(pick_time) { DCHECK(!pick_time_.is_null()); } FirstWebContentsProfilerForProfilePicker:: ~FirstWebContentsProfilerForProfilePicker() = default; void FirstWebContentsProfilerForProfilePicker::RecordFinishReason( metrics::StartupProfilingFinishReason finish_reason) { RecordProfilingFinishReason(finish_reason); } void FirstWebContentsProfilerForProfilePicker::RecordNavigationFinished( base::TimeTicks navigation_start) { // Nothing to record here for Profile Picker startups. } void FirstWebContentsProfilerForProfilePicker::RecordFirstNonEmptyPaint() { const char histogram_name[] = "ProfilePicker.FirstProfileTime.FirstWebContentsNonEmptyPaint"; base::TimeTicks paint_time = base::TimeTicks::Now(); base::UmaHistogramLongTimes100(histogram_name, paint_time - pick_time_); TRACE_EVENT_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0("startup", histogram_name, this, pick_time_); TRACE_EVENT_NESTABLE_ASYNC_END_WITH_TIMESTAMP0("startup", histogram_name, this, paint_time); } bool FirstWebContentsProfilerForProfilePicker::WasStartupInterrupted() { // We're assuming that no interruptions block opening an existing profile // from the profile picker. We would detect this by observing really high // latency on the tracked metric, and can start tracking interruptions if we // find that such cases occur. return false; } void BeginFirstWebContentsProfiling(Browser* browser, base::TimeTicks pick_time) { content::WebContents* visible_contents = metrics::FirstWebContentsProfilerBase::GetVisibleContents(browser); if (!visible_contents) { RecordProfilingFinishReason(metrics::StartupProfilingFinishReason:: kAbandonNoInitiallyVisibleContent); return; } if (visible_contents->CompletedFirstVisuallyNonEmptyPaint()) { RecordProfilingFinishReason( metrics::StartupProfilingFinishReason::kAbandonAlreadyPaintedContent); return; } // FirstWebContentsProfilerForProfilePicker owns itself and is also bound to // |visible_contents|'s lifetime by observing WebContentsDestroyed(). new FirstWebContentsProfilerForProfilePicker(visible_contents, pick_time); } } // namespace ProfilePickerHandler::ProfilePickerHandler() = default; ProfilePickerHandler::~ProfilePickerHandler() { OnJavascriptDisallowed(); } void ProfilePickerHandler::EnableStartupMetrics() { DCHECK(creation_time_on_startup_.is_null()); content::WebContents* contents = web_ui()->GetWebContents(); if (contents->GetVisibility() == content::Visibility::VISIBLE) { // Only record paint event if the window is visible. creation_time_on_startup_ = base::TimeTicks::Now(); Observe(web_ui()->GetWebContents()); } } void ProfilePickerHandler::RegisterMessages() { web_ui()->RegisterDeprecatedMessageCallback( "mainViewInitialize", base::BindRepeating(&ProfilePickerHandler::HandleMainViewInitialize, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "launchSelectedProfile", base::BindRepeating(&ProfilePickerHandler::HandleLaunchSelectedProfile, base::Unretained(this), /*open_settings=*/false)); web_ui()->RegisterDeprecatedMessageCallback( "openManageProfileSettingsSubPage", base::BindRepeating(&ProfilePickerHandler::HandleLaunchSelectedProfile, base::Unretained(this), /*open_settings=*/true)); web_ui()->RegisterDeprecatedMessageCallback( "launchGuestProfile", base::BindRepeating(&ProfilePickerHandler::HandleLaunchGuestProfile, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "askOnStartupChanged", base::BindRepeating(&ProfilePickerHandler::HandleAskOnStartupChanged, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "getNewProfileSuggestedThemeInfo", base::BindRepeating( &ProfilePickerHandler::HandleGetNewProfileSuggestedThemeInfo, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "getProfileThemeInfo", base::BindRepeating(&ProfilePickerHandler::HandleGetProfileThemeInfo, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "removeProfile", base::BindRepeating(&ProfilePickerHandler::HandleRemoveProfile, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "getProfileStatistics", base::BindRepeating(&ProfilePickerHandler::HandleGetProfileStatistics, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "loadSignInProfileCreationFlow", base::BindRepeating( &ProfilePickerHandler::HandleLoadSignInProfileCreationFlow, base::Unretained(this))); // TODO(crbug.com/1115056): Consider renaming this message to // 'createLocalProfile' as this is only used for local profiles. web_ui()->RegisterDeprecatedMessageCallback( "getAvailableIcons", base::BindRepeating(&ProfilePickerHandler::HandleGetAvailableIcons, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "createProfile", base::BindRepeating(&ProfilePickerHandler::HandleCreateProfile, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "getSwitchProfile", base::BindRepeating(&ProfilePickerHandler::HandleGetSwitchProfile, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "confirmProfileSwitch", base::BindRepeating(&ProfilePickerHandler::HandleConfirmProfileSwitch, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "cancelProfileSwitch", base::BindRepeating(&ProfilePickerHandler::HandleCancelProfileSwitch, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "setProfileName", base::BindRepeating(&ProfilePickerHandler::HandleSetProfileName, base::Unretained(this))); web_ui()->RegisterDeprecatedMessageCallback( "recordSignInPromoImpression", base::BindRepeating( &ProfilePickerHandler::HandleRecordSignInPromoImpression, base::Unretained(this))); #if BUILDFLAG(IS_CHROMEOS_LACROS) web_ui()->RegisterDeprecatedMessageCallback( "getAvailableAccounts", base::BindRepeating(&ProfilePickerHandler::HandleGetAvailableAccounts, base::Unretained(this))); web_ui()->RegisterMessageCallback( "openAshAccountSettingsPage", base::BindRepeating( &ProfilePickerHandler::HandleOpenAshAccountSettingsPage, base::Unretained(this))); #endif Profile* profile = Profile::FromWebUI(web_ui()); content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile)); } void ProfilePickerHandler::OnJavascriptAllowed() { ProfileManager* profile_manager = g_browser_process->profile_manager(); #if BUILDFLAG(IS_CHROMEOS_LACROS) account_profile_mapper_observation_.Observe( profile_manager->GetAccountProfileMapper()); #endif // BUILDFLAG(IS_CHROMEOS_LACROS) profile_attributes_storage_observation_.Observe( &profile_manager->GetProfileAttributesStorage()); } void ProfilePickerHandler::OnJavascriptDisallowed() { #if BUILDFLAG(IS_CHROMEOS_LACROS) account_profile_mapper_observation_.Reset(); #endif // BUILDFLAG(IS_CHROMEOS_LACROS) profile_attributes_storage_observation_.Reset(); weak_factory_.InvalidateWeakPtrs(); } void ProfilePickerHandler::HandleMainViewInitialize( const base::ListValue* args) { if (!creation_time_on_startup_.is_null() && !main_view_initialized_) { // This function can be called multiple times if the page is reloaded. The // histogram is only recorded once. main_view_initialized_ = true; base::UmaHistogramTimes("ProfilePicker.StartupTime.MainViewInitialized", base::TimeTicks::Now() - creation_time_on_startup_); } AllowJavascript(); PushProfilesList(); } void ProfilePickerHandler::HandleLaunchSelectedProfile( bool open_settings, const base::ListValue* args) { TRACE_EVENT1("browser", "ProfilePickerHandler::HandleLaunchSelectedProfile", "args", args->DebugString()); if (args->GetList().empty()) return; const base::Value& profile_path_value = args->GetList()[0]; absl::optional<base::FilePath> profile_path = base::ValueToFilePath(profile_path_value); if (!profile_path) return; ProfileAttributesEntry* entry = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(*profile_path); if (!entry) { NOTREACHED(); return; } if (entry->IsSigninRequired()) { DCHECK(signin_util::IsForceSigninEnabled()); if (entry->CanBeManaged() && base::FeatureList::IsEnabled(features::kForceSignInReauth)) { ProfilePickerForceSigninDialog::ShowReauthDialog( web_ui()->GetWebContents()->GetBrowserContext(), base::UTF16ToUTF8(entry->GetUserName()), *profile_path); } else if (entry->GetActiveTime() != base::Time()) { // If force-sign-in is enabled, do not allow users to sign in to a // pre-existing locked profile, as this may force unexpected profile data // merge. We consider a profile as pre-existing if it has been actived // previously. A pre-existed profile can still be used if it has been // signed in with an email address matched RestrictSigninToPattern policy // already. LoginUIServiceFactory::GetForProfile( Profile::FromWebUI(web_ui())->GetOriginalProfile()) ->SetProfileBlockingErrorMessage(); ProfilePickerForceSigninDialog::ShowDialogAndDisplayErrorMessage( web_ui()->GetWebContents()->GetBrowserContext()); } else { // Fresh sign in via profile picker without existing email address. ProfilePickerForceSigninDialog::ShowForceSigninDialog( web_ui()->GetWebContents()->GetBrowserContext(), *profile_path); } return; } #if BUILDFLAG(IS_CHROMEOS_LACROS) if (!profiles::AreSecondaryProfilesAllowed()) { if (!Profile::IsMainProfilePath(*profile_path)) { LoginUIServiceFactory::GetForProfile( Profile::FromWebUI(web_ui())->GetOriginalProfile()) ->SetProfileBlockingErrorMessage(); ProfilePickerForceSigninDialog::ShowDialogAndDisplayErrorMessage( web_ui()->GetWebContents()->GetBrowserContext()); return; } } #endif // BUILDFLAG(IS_CHROMEOS_LACROS) if (!creation_time_on_startup_.is_null() && // Avoid overriding the picked time if already recorded. This can happen // for example if multiple profiles are picked: https://crbug.com/1277466. profile_picked_time_on_startup_.is_null()) { profile_picked_time_on_startup_ = base::TimeTicks::Now(); } profiles::SwitchToProfile( *profile_path, /*always_create=*/false, base::BindRepeating(&ProfilePickerHandler::OnSwitchToProfileComplete, weak_factory_.GetWeakPtr(), false, open_settings)); } void ProfilePickerHandler::HandleLaunchGuestProfile( const base::ListValue* args) { // TODO(crbug.com/1063856): Add check |IsGuestModeEnabled| once policy // checking has been added to the UI. profiles::SwitchToGuestProfile( base::BindRepeating(&ProfilePickerHandler::OnSwitchToProfileComplete, weak_factory_.GetWeakPtr(), false, false)); } void ProfilePickerHandler::HandleAskOnStartupChanged( const base::ListValue* args) { const auto& list = args->GetList(); if (list.empty() || !list[0].is_bool()) return; const bool show_on_startup = list[0].GetBool(); PrefService* prefs = g_browser_process->local_state(); prefs->SetBoolean(prefs::kBrowserShowProfilePickerOnStartup, show_on_startup); RecordAskOnStartupChanged(show_on_startup); } void ProfilePickerHandler::HandleGetNewProfileSuggestedThemeInfo( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(1U, args->GetList().size()); const base::Value& callback_id = args->GetList()[0]; #if BUILDFLAG(IS_CHROMEOS_LACROS) if (IsSelectingSecondaryAccount(web_ui())) { // The picker offers secondary accounts for a given existing profile. // Extract the color from the current profile (where this is rendered). ThemeService* theme_service = ThemeServiceFactory::GetForProfile(Profile::FromBrowserContext( web_ui()->GetWebContents()->GetBrowserContext())); base::Value profile_dict; if (theme_service->UsingAutogeneratedTheme()) { // We'll never use `profile_dict` for showing the color picker so we can // pass in kManuallyPickedColorId to simplify the code. profile_dict = CreateAutogeneratedProfileThemeInfo( kManuallyPickedColorId, theme_service->GetAutogeneratedThemeColor(), web_ui()->GetDeviceScaleFactor()); } else { profile_dict = CreateDefaultProfileThemeInfo( web_ui()->GetDeviceScaleFactor(), webui::GetNativeTheme(web_ui()->GetWebContents()) ->ShouldUseDarkColors()); } ResolveJavascriptCallback(callback_id, std::move(profile_dict)); return; } #endif chrome_colors::ColorInfo color_info = GenerateNewProfileColor(); base::Value dict = CreateAutogeneratedProfileThemeInfo( color_info.id, color_info.color, web_ui()->GetDeviceScaleFactor()); ResolveJavascriptCallback(callback_id, std::move(dict)); } void ProfilePickerHandler::HandleGetProfileThemeInfo( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(2U, args->GetList().size()); const base::Value& callback_id = args->GetList()[0]; const base::Value& user_theme_choice = args->GetList()[1]; int color_id = user_theme_choice.FindIntKey("colorId").value(); absl::optional<SkColor> color = user_theme_choice.FindDoubleKey("color"); base::Value dict; switch (color_id) { case kDefaultThemeColorId: dict = CreateDefaultProfileThemeInfo( web_ui()->GetDeviceScaleFactor(), webui::GetNativeTheme(web_ui()->GetWebContents()) ->ShouldUseDarkColors()); break; case kManuallyPickedColorId: dict = CreateAutogeneratedProfileThemeInfo( color_id, *color, web_ui()->GetDeviceScaleFactor()); break; default: dict = CreateAutogeneratedProfileThemeInfo( color_id, *GetChromeColorColorById(color_id), web_ui()->GetDeviceScaleFactor()); break; } ResolveJavascriptCallback(callback_id, std::move(dict)); } void ProfilePickerHandler::HandleGetAvailableIcons( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(1U, args->GetList().size()); const base::Value& callback_id = args->GetList()[0]; ResolveJavascriptCallback( callback_id, base::Value(profiles::GetCustomProfileAvatarIconsAndLabels())); } void ProfilePickerHandler::HandleCreateProfile(const base::ListValue* args) { CHECK_EQ(4U, args->GetList().size()); std::u16string profile_name = base::UTF8ToUTF16(args->GetList()[0].GetString()); // profileColor is undefined for the default theme. absl::optional<SkColor> profile_color; if (args->GetList()[1].is_int()) profile_color = args->GetList()[1].GetInt(); size_t avatar_index = args->GetList()[2].GetInt(); bool create_shortcut = args->GetList()[3].GetBool(); base::TrimWhitespace(profile_name, base::TRIM_ALL, &profile_name); CHECK(!profile_name.empty()); #ifndef NDEBUG DCHECK(profiles::IsDefaultAvatarIconIndex(avatar_index)); #endif ProfileMetrics::LogProfileAddNewUser( ProfileMetrics::ADD_NEW_PROFILE_PICKER_LOCAL); ProfileManager::CreateMultiProfileAsync( profile_name, avatar_index, /*is_hidden=*/false, base::BindRepeating(&ProfilePickerHandler::OnProfileCreated, weak_factory_.GetWeakPtr(), profile_color, create_shortcut)); } void ProfilePickerHandler::HandleGetSwitchProfile(const base::ListValue* args) { AllowJavascript(); CHECK_EQ(1U, args->GetList().size()); const base::Value& callback_id = args->GetList()[0]; int avatar_icon_size = kProfileCardAvatarSize * web_ui()->GetDeviceScaleFactor(); base::FilePath profile_path = ProfilePicker::GetSwitchProfilePath(); ProfileAttributesEntry* entry = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(profile_path); CHECK(entry); base::Value dict = CreateProfileEntry(entry, avatar_icon_size); ResolveJavascriptCallback(callback_id, std::move(dict)); } void ProfilePickerHandler::HandleConfirmProfileSwitch( const base::ListValue* args) { if (args->GetList().empty()) return; const base::Value& profile_path_value = args->GetList()[0]; absl::optional<base::FilePath> profile_path = base::ValueToFilePath(profile_path_value); if (!profile_path) return; // TODO(https://crbug.com/1182206): remove the profile used for the sign-in // flow. profiles::SwitchToProfile( *profile_path, /*always_create=*/false, base::BindRepeating(&ProfilePickerHandler::OnSwitchToProfileComplete, weak_factory_.GetWeakPtr(), false, false)); } void ProfilePickerHandler::HandleCancelProfileSwitch( const base::ListValue* args) { ProfilePicker::CancelSignedInFlow(); } void ProfilePickerHandler::OnProfileCreated( absl::optional<SkColor> profile_color, bool create_shortcut, Profile* profile, Profile::CreateStatus status) { switch (status) { case Profile::CREATE_STATUS_LOCAL_FAIL: { NOTREACHED() << "Local fail in creating new profile"; break; } case Profile::CREATE_STATUS_CREATED: // Do nothing for an intermediate status. return; case Profile::CREATE_STATUS_INITIALIZED: { OnProfileCreationSuccess(profile_color, create_shortcut, profile); break; } } FireWebUIListener("create-profile-finished", base::Value()); } void ProfilePickerHandler::OnProfileCreationSuccess( absl::optional<SkColor> profile_color, bool create_shortcut, Profile* profile) { DCHECK(profile); DCHECK(!signin_util::IsForceSigninEnabled()); // Apply a new color to the profile or use the default theme. auto* theme_service = ThemeServiceFactory::GetForProfile(profile); if (profile_color.has_value()) theme_service->BuildAutogeneratedThemeFromColor(*profile_color); else theme_service->UseDefaultTheme(); // Create shortcut if needed. if (create_shortcut) { DCHECK(ProfileShortcutManager::IsFeatureEnabled()); ProfileShortcutManager* shortcut_manager = g_browser_process->profile_manager()->profile_shortcut_manager(); DCHECK(shortcut_manager); if (shortcut_manager) shortcut_manager->CreateProfileShortcut(profile->GetPath()); } // Skip the FRE for this profile as sign-in was offered as part of the flow. profile->GetPrefs()->SetBoolean(prefs::kHasSeenWelcomePage, true); RecordNewProfileSpec(profile_color, create_shortcut); // Launch profile and close the picker. profiles::OpenBrowserWindowForProfile( base::BindRepeating(&ProfilePickerHandler::OnSwitchToProfileComplete, weak_factory_.GetWeakPtr(), true, false), false, // Don't create a window if one already exists. true, // Create a first run window. false, // There is no need to unblock all extensions because we only open // browser window if the Profile is not locked. Hence there is no // extension blocked. profile, Profile::CREATE_STATUS_INITIALIZED); } void ProfilePickerHandler::HandleRecordSignInPromoImpression( const base::ListValue* /*args*/) { signin_metrics::RecordSigninImpressionUserActionForAccessPoint( signin_metrics::AccessPoint::ACCESS_POINT_USER_MANAGER); } void ProfilePickerHandler::HandleSetProfileName(const base::ListValue* args) { CHECK_EQ(2U, args->GetList().size()); const base::Value& profile_path_value = args->GetList()[0]; absl::optional<base::FilePath> profile_path = base::ValueToFilePath(profile_path_value); if (!profile_path) { NOTREACHED(); return; } std::u16string profile_name = base::UTF8ToUTF16(args->GetList()[1].GetString()); base::TrimWhitespace(profile_name, base::TRIM_ALL, &profile_name); CHECK(!profile_name.empty()); ProfileAttributesEntry* entry = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(profile_path.value()); CHECK(entry); entry->SetLocalProfileName(profile_name, /*is_default_name=*/false); } void ProfilePickerHandler::HandleRemoveProfile(const base::ListValue* args) { CHECK_EQ(1U, args->GetList().size()); const base::Value& profile_path_value = args->GetList()[0]; absl::optional<base::FilePath> profile_path = base::ValueToFilePath(profile_path_value); if (!profile_path) { NOTREACHED(); return; } #if BUILDFLAG(IS_CHROMEOS_LACROS) // On Lacros, the primary profile should never be deleted. CHECK(!Profile::IsMainProfilePath(*profile_path)); #endif // BUILDFLAG(IS_CHROMEOS_LACROS) RecordProfilePickerAction(ProfilePickerAction::kDeleteProfile); webui::DeleteProfileAtPath(*profile_path, ProfileMetrics::DELETE_PROFILE_USER_MANAGER); } void ProfilePickerHandler::HandleGetProfileStatistics( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(1U, args->GetList().size()); const base::Value& profile_path_value = args->GetList()[0]; absl::optional<base::FilePath> profile_path = base::ValueToFilePath(profile_path_value); if (!profile_path) return; Profile* profile = g_browser_process->profile_manager()->GetProfileByPath(*profile_path); if (profile) { GatherProfileStatistics(profile); } else { g_browser_process->profile_manager()->LoadProfileByPath( *profile_path, false, base::BindOnce(&ProfilePickerHandler::GatherProfileStatistics, weak_factory_.GetWeakPtr())); } } void ProfilePickerHandler::GatherProfileStatistics(Profile* profile) { if (!profile) { return; } ProfileStatisticsFactory::GetForProfile(profile)->GatherStatistics( base::BindRepeating(&ProfilePickerHandler::OnProfileStatisticsReceived, weak_factory_.GetWeakPtr(), profile->GetPath())); } void ProfilePickerHandler::OnProfileStatisticsReceived( const base::FilePath& profile_path, profiles::ProfileCategoryStats result) { base::Value dict(base::Value::Type::DICTIONARY); dict.SetKey("profilePath", base::FilePathToValue(profile_path)); base::Value stats(base::Value::Type::DICTIONARY); // Categories are defined in |kProfileStatisticsCategories| // {"BrowsingHistory", "Passwords", "Bookmarks", "Autofill"}. for (const auto& item : result) { stats.SetIntKey(item.category, item.count); } dict.SetKey("statistics", std::move(stats)); FireWebUIListener("profile-statistics-received", std::move(dict)); } void ProfilePickerHandler::HandleLoadSignInProfileCreationFlow( const base::ListValue* args) { AllowJavascript(); CHECK_EQ(2U, args->GetList().size()); absl::optional<SkColor> profile_color = args->GetList()[0].GetIfInt(); const std::string& gaia_id = args->GetList()[1].GetString(); #if BUILDFLAG(IS_CHROMEOS_LACROS) if (IsSelectingSecondaryAccount(web_ui())) { AccountProfileMapper* mapper = g_browser_process->profile_manager()->GetAccountProfileMapper(); if (gaia_id.empty()) { mapper->ShowAddAccountDialog(GetCurrentProfilePath(web_ui()), account_manager::AccountManagerFacade:: AccountAdditionSource::kOgbAddAccount, AccountProfileMapper::AddAccountCallback()); } else { mapper->AddAccount(GetCurrentProfilePath(web_ui()), account_manager::AccountKey( gaia_id, account_manager::AccountType::kGaia), AccountProfileMapper::AddAccountCallback()); } ProfilePicker::Hide(); return; } DCHECK(!lacros_sign_in_provider_); lacros_sign_in_provider_ = std::make_unique<ProfilePickerLacrosSignInProvider>(); ProfilePickerLacrosSignInProvider::SignedInCallback callback = base::BindOnce(&ProfilePickerHandler::OnLacrosSignedInProfileCreated, weak_factory_.GetWeakPtr(), profile_color); if (gaia_id.empty()) { lacros_sign_in_provider_->ShowAddAccountDialogAndCreateSignedInProfile( std::move(callback)); } else { lacros_sign_in_provider_->CreateSignedInProfileWithExistingAccount( gaia_id, std::move(callback)); } #elif BUILDFLAG(ENABLE_DICE_SUPPORT) DCHECK(gaia_id.empty()) << "gaiaId is only supported on Lacros."; if (signin_util::IsForceSigninEnabled()) { // Force sign-in policy uses a separate flow that doesn't initialize the // profile color. Generate a new profile color here. profile_color = GenerateNewProfileColor().color; } ProfilePicker::SwitchToDiceSignIn( profile_color, base::BindOnce(&ProfilePickerHandler::OnLoadSigninFinished, weak_factory_.GetWeakPtr())); #else NOTREACHED(); #endif } void ProfilePickerHandler::OnLoadSigninFinished(bool success) { FireWebUIListener("load-signin-finished", base::Value(success)); } void ProfilePickerHandler::OnSwitchToProfileComplete( bool new_profile, bool open_settings, Profile* profile, Profile::CreateStatus profile_create_status) { TRACE_EVENT2("browser", "ProfilePickerHandler::OnSwitchToProfileComplete", "profile_path", profile->GetPath().AsUTF8Unsafe(), "create_status", profile_create_status); Browser* browser = chrome::FindAnyBrowser(profile, false); DCHECK(browser); DCHECK(browser->window()); // Measure startup time to display first web contents if the profile picker // was displayed on startup and if the initiating action is instrumented. For // example we don't record pick time for profile creations. if (!profile_picked_time_on_startup_.is_null()) { BeginFirstWebContentsProfiling(browser, profile_picked_time_on_startup_); } // Only show the profile switch IPH when the user clicked the card, and there // are multiple profiles. std::vector<ProfileAttributesEntry*> entries = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetAllProfilesAttributes(); int profile_count = std::count_if( entries.begin(), entries.end(), [](ProfileAttributesEntry* entry) { return !entry->IsOmitted(); }); if (profile_count > 1 && !open_settings && ProfilePicker::GetOnSelectProfileTargetUrl().is_empty()) { browser->window()->MaybeShowProfileSwitchIPH(); } if (new_profile) { RecordProfilePickerAction(ProfilePickerAction::kLaunchNewProfile); ProfilePicker::Hide(); return; } if (profile->IsGuestSession()) { RecordProfilePickerAction(ProfilePickerAction::kLaunchGuestProfile); } else { RecordProfilePickerAction( open_settings ? ProfilePickerAction::kLaunchExistingProfileCustomizeSettings : ProfilePickerAction::kLaunchExistingProfile); } if (open_settings) { // User clicked 'Edit' from the profile card menu. chrome::ShowSettingsSubPage(browser, chrome::kManageProfileSubPage); } else { // Opens a target url upon user selecting a pre-existing profile. For // new profiles the chrome welcome page is displayed. OpenOnSelectProfileTargetUrl(browser); } ProfilePicker::Hide(); } void ProfilePickerHandler::PushProfilesList() { DCHECK(IsJavascriptAllowed()); FireWebUIListener("profiles-list-changed", GetProfilesList()); } void ProfilePickerHandler::SetProfilesOrder( const std::vector<ProfileAttributesEntry*>& entries) { profiles_order_.clear(); size_t index = 0; for (const ProfileAttributesEntry* entry : entries) { profiles_order_[entry->GetPath()] = index++; } } std::vector<ProfileAttributesEntry*> ProfilePickerHandler::GetProfileAttributes() { std::vector<ProfileAttributesEntry*> ordered_entries = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetAllProfilesAttributesSortedByLocalProfilName(); base::EraseIf(ordered_entries, [](const ProfileAttributesEntry* entry) { return entry->IsOmitted(); }); size_t number_of_profiles = ordered_entries.size(); if (profiles_order_.size() != number_of_profiles) { // Should only happen the first time the function is called. // Profile creation and deletion are handled at // 'OnProfileAdded', 'OnProfileWasRemoved'. DCHECK(!profiles_order_.size()); SetProfilesOrder(ordered_entries); return ordered_entries; } // Vector of nullptr entries. std::vector<ProfileAttributesEntry*> entries(number_of_profiles); for (ProfileAttributesEntry* entry : ordered_entries) { DCHECK(profiles_order_.find(entry->GetPath()) != profiles_order_.end()); size_t index = profiles_order_[entry->GetPath()]; DCHECK_LT(index, number_of_profiles); DCHECK(!entries[index]); entries[index] = entry; } return entries; } base::Value ProfilePickerHandler::GetProfilesList() { base::Value profiles_list(base::Value::Type::LIST); std::vector<ProfileAttributesEntry*> entries = GetProfileAttributes(); const int avatar_icon_size = kProfileCardAvatarSize * web_ui()->GetDeviceScaleFactor(); for (const ProfileAttributesEntry* entry : entries) { profiles_list.Append(CreateProfileEntry(entry, avatar_icon_size)); } return profiles_list; } void ProfilePickerHandler::AddProfileToList( const base::FilePath& profile_path) { size_t number_of_profiles = profiles_order_.size(); auto it_and_whether_inserted = profiles_order_.insert({profile_path, number_of_profiles}); // We shouldn't add the same profile to the list more than once. Use // `insert()` to not corrput the map in case this happens. // https://crbug.com/1195784 DCHECK(it_and_whether_inserted.second); } bool ProfilePickerHandler::RemoveProfileFromList( const base::FilePath& profile_path) { auto remove_it = profiles_order_.find(profile_path); // Guest and omitted profiles aren't added to the list. // It's possible that a profile gets marked as guest or as omitted after it // had been added to the list. In that case, the profile gets removed from the // list once in `OnProfileIsOmittedChanged()` but not the second time when // `OnProfileWasRemoved()` is called. if (remove_it == profiles_order_.end()) return false; size_t index = remove_it->second; profiles_order_.erase(remove_it); for (auto& it : profiles_order_) { if (it.second > index) --it.second; } return true; } void ProfilePickerHandler::OnProfileAdded(const base::FilePath& profile_path) { ProfileAttributesEntry* entry = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(profile_path); CHECK(entry); if (entry->IsOmitted()) return; AddProfileToList(profile_path); PushProfilesList(); } void ProfilePickerHandler::OnProfileWasRemoved( const base::FilePath& profile_path, const std::u16string& profile_name) { DCHECK(IsJavascriptAllowed()); if (RemoveProfileFromList(profile_path)) FireWebUIListener("profile-removed", base::FilePathToValue(profile_path)); } void ProfilePickerHandler::OnProfileIsOmittedChanged( const base::FilePath& profile_path) { ProfileAttributesEntry* entry = g_browser_process->profile_manager() ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(profile_path); CHECK(entry); if (entry->IsOmitted()) { if (RemoveProfileFromList(profile_path)) PushProfilesList(); } else { AddProfileToList(profile_path); PushProfilesList(); } } void ProfilePickerHandler::OnProfileAvatarChanged( const base::FilePath& profile_path) { PushProfilesList(); } void ProfilePickerHandler::OnProfileHighResAvatarLoaded( const base::FilePath& profile_path) { PushProfilesList(); } void ProfilePickerHandler::OnProfileNameChanged( const base::FilePath& profile_path, const std::u16string& old_profile_name) { PushProfilesList(); } void ProfilePickerHandler::OnProfileHostedDomainChanged( const base::FilePath& profile_path) { PushProfilesList(); } void ProfilePickerHandler::DidFirstVisuallyNonEmptyPaint() { DCHECK(!creation_time_on_startup_.is_null()); auto now = base::TimeTicks::Now(); base::UmaHistogramTimes("ProfilePicker.StartupTime.FirstPaint", now - creation_time_on_startup_); startup_metric_utils::RecordExternalStartupMetric( "ProfilePicker.StartupTime.FirstPaint.FromApplicationStart", now, /*set_non_browser_ui_displayed=*/true); // Stop observing so that the histogram is only recorded once. Observe(nullptr); } void ProfilePickerHandler::OnVisibilityChanged(content::Visibility visibility) { // If the profile picker is hidden, the first paint will be delayed until the // picker is visible again. Stop monitoring the first paint to avoid polluting // the metrics. if (visibility != content::Visibility::VISIBLE) Observe(nullptr); } #if BUILDFLAG(IS_CHROMEOS_LACROS) void ProfilePickerHandler::HandleOpenAshAccountSettingsPage( base::Value::ConstListView args) { std::string settings_url = chrome::kChromeUIOSSettingsURL; settings_url.append(chromeos::settings::mojom::kMyAccountsSubpagePath); lacros_url_handling::NavigateInAsh(GURL(settings_url)); } void ProfilePickerHandler::HandleGetAvailableAccounts( const base::ListValue* args) { AllowJavascript(); UpdateAvailableAccounts(); } void ProfilePickerHandler::UpdateAvailableAccounts() { AccountProfileMapper* mapper = g_browser_process->profile_manager()->GetAccountProfileMapper(); if (IsSelectingSecondaryAccount(web_ui())) { GetAccountsAvailableAsSecondary( mapper, GetCurrentProfilePath(web_ui()), base::BindOnce(&ProfilePickerHandler::GetAvailableAccountsInfo, weak_factory_.GetWeakPtr())); return; } GetAccountsAvailableAsPrimary( mapper, &g_browser_process->profile_manager()->GetProfileAttributesStorage(), base::BindOnce(&ProfilePickerHandler::GetAvailableAccountsInfo, weak_factory_.GetWeakPtr())); } void ProfilePickerHandler::GetAvailableAccountsInfo( const std::vector<account_manager::Account>& accounts) { // If there's a request in flight, it deletes the current helper and starts a // new request. lacros_account_info_helper_ = std::make_unique<GetAccountInformationHelper>(); std::vector<std::string> gaia_ids; for (const account_manager::Account& account : accounts) gaia_ids.push_back(account.key.id()); lacros_account_info_helper_->Start( gaia_ids, base::BindOnce(&ProfilePickerHandler::SendAvailableAccounts, weak_factory_.GetWeakPtr())); } void ProfilePickerHandler::SendAvailableAccounts( std::vector<GetAccountInformationHelper::GetAccountInformationResult> accounts) { base::Value accounts_list(base::Value::Type::LIST); for (const GetAccountInformationHelper::GetAccountInformationResult& account : accounts) { // TODO(https://crbug/1226050): Filter out items with no email as items // without an email are impossible to use. The email should be always // available, unless the mojo connection fails. This requires more robust // unit-tests. base::Value account_dict(base::Value::Type::DICTIONARY); account_dict.SetStringKey("gaiaId", account.gaia); account_dict.SetStringKey("email", account.email); account_dict.SetStringKey("name", account.full_name); SkBitmap account_bitmap = GetAvailableAccountBitmap( account.account_image, webui::GetNativeTheme(web_ui()->GetWebContents()) ->ShouldUseDarkColors()); account_dict.SetStringKey("accountImageUrl", webui::GetBitmapDataUrl(account_bitmap)); accounts_list.Append(std::move(account_dict)); } FireWebUIListener("available-accounts-changed", std::move(accounts_list)); } void ProfilePickerHandler::OnLacrosSignedInProfileCreated( absl::optional<SkColor> profile_color, Profile* profile) { DCHECK(lacros_sign_in_provider_); lacros_sign_in_provider_.reset(); if (!profile) { FireWebUIListener("load-signin-finished", base::Value(/*success=*/false)); return; } FireWebUIListener("load-signin-finished", base::Value(/*success=*/true)); ProfilePicker::SwitchToSignedInFlow(profile_color, profile); } void ProfilePickerHandler::OnAccountUpserted( const base::FilePath& profile_path, const account_manager::Account& account) { UpdateAvailableAccounts(); } void ProfilePickerHandler::OnAccountRemoved( const base::FilePath& profile_path, const account_manager::Account& account) { UpdateAvailableAccounts(); } #endif // BUILDFLAG(IS_CHROMEOS_LACROS)
39.620827
82
0.725317
[ "vector" ]
26dfb74ca5ccfb23092857de41b85263a8cecd68
46,197
cpp
C++
libsplit/src/Scheduler/Scheduler.cpp
phuchant/libsplitcl
4688bd9ab8c3b60c7848eab73519e44cb083cbbc
[ "MIT" ]
null
null
null
libsplit/src/Scheduler/Scheduler.cpp
phuchant/libsplitcl
4688bd9ab8c3b60c7848eab73519e44cb083cbbc
[ "MIT" ]
null
null
null
libsplit/src/Scheduler/Scheduler.cpp
phuchant/libsplitcl
4688bd9ab8c3b60c7848eab73519e44cb083cbbc
[ "MIT" ]
null
null
null
#include <Globals.h> #include <Handle/KernelHandle.h> #include <Options.h> #include <Scheduler/Scheduler.h> #include <Utils/Debug.h> #include <Utils/Timeline.h> #include <cassert> #include <cmath> #include <cstring> namespace libsplit { void Scheduler::SubKernelSchedInfo::updateTimers() { for (unsigned d=0; d<nbDevices; d++) { H2DTimes[d] = 0; D2HTimes[d] = 0; kernelTimes[d] = 0; // H2D timers for (auto IT : src2H2DEvents[d]) { for (unsigned i=0; i<IT.second.size(); ++i) { cl_ulong start, end; cl_int err; IT.second[i]->wait(); err = real_clGetEventProfilingInfo(IT.second[i]->event, CL_PROFILING_COMMAND_START, sizeof(start), &start, NULL); clCheck(err, __FILE__, __LINE__); err = real_clGetEventProfilingInfo(IT.second[i]->event, CL_PROFILING_COMMAND_END, sizeof(end), &end, NULL); clCheck(err, __FILE__, __LINE__); // IT.second[i]->release(); double t = (end - start) * 1e-6; unsigned cb = src2H2DEventsCB[d][IT.first][i]; sched->pushH2DTroughputPoint(d, cb, t); H2DTimes[d] += t; int src = IT.first; if (src2H2DTimes[d].find(src) == src2H2DTimes[d].end()) src2H2DTimes[d][src] = t; else src2H2DTimes[d][src] += t; } } src2H2DEvents[d].clear(); src2H2DEventsCB[d].clear(); // D2H timers for (auto IT : src2D2HEvents[d]) { for (unsigned i=0; i<IT.second.size(); ++i) { cl_ulong start, end; cl_int err; IT.second[i]->wait(); err = real_clGetEventProfilingInfo(IT.second[i]->event, CL_PROFILING_COMMAND_START, sizeof(start), &start, NULL); clCheck(err, __FILE__, __LINE__); err = real_clGetEventProfilingInfo(IT.second[i]->event, CL_PROFILING_COMMAND_END, sizeof(end), &end, NULL); clCheck(err, __FILE__, __LINE__); // IT.second[i]->release(); double t = (end - start) * 1e-6; unsigned cb = src2D2HEventsCB[d][IT.first][i]; sched->pushD2HTroughputPoint(d, cb, t); D2HTimes[d] += t; int src = IT.first; if (src2D2HTimes[d].find(src) == src2D2HTimes[d].end()) src2D2HTimes[d][src] = t; else src2D2HTimes[d][src] += t; } } src2D2HEvents[d].clear(); src2D2HEventsCB[d].clear(); } // Subkernels timers for (unsigned i=0; i<subkernels.size(); i++) { cl_ulong start, end; cl_int err; unsigned dev = subkernels[i]->device; subkernels[i]->event->wait(); err = real_clGetEventProfilingInfo(subkernels[i]->event->event, CL_PROFILING_COMMAND_START, sizeof(start), &start, NULL); clCheck(err, __FILE__, __LINE__); err = real_clGetEventProfilingInfo(subkernels[i]->event->event, CL_PROFILING_COMMAND_END, sizeof(end), &end, NULL); clCheck(err, __FILE__, __LINE__); // subkernels[i]->event->release(); kernelTimes[dev] += (end - start) * 1e-6; } } void Scheduler::SubKernelSchedInfo::clearEvents() { for (unsigned d=0; d<nbDevices; d++) { // TODO: release events src2H2DEvents[d].clear(); src2D2HEvents[d].clear(); src2H2DEventsCB[d].clear(); src2D2HEventsCB[d].clear(); } } void Scheduler::SubKernelSchedInfo::clearTimers() { for (unsigned d=0; d<nbDevices; d++) { src2H2DTimes[d].clear(); src2D2HTimes[d].clear(); } } void Scheduler::SubKernelSchedInfo::updatePerfDescr() { size_perf_dscr = real_size_gr; int nbSplits = real_size_gr / 3; for (int i=0; i<nbSplits; i++) { unsigned dev = real_granu_dscr[i*3]; kernel_perf_dscr[i*3] = dev; kernel_perf_dscr[i*3+1] = real_granu_dscr[i*3+2]; kernel_perf_dscr[i*3+2] = kernelTimes[dev]; } } void Scheduler::SubKernelSchedInfo::printTimers(int kerId) const { double totalPerDevice[nbDevices] = {0}; for (unsigned d=0; d<nbDevices; d++) { std::cerr << "ker " << kerId << " dev " << d << " H2D=" << H2DTimes[d] << " D2H=" << D2HTimes[d] << " kernel=" << kernelTimes[d] << "\n"; // for (auto IT : src2H2DTimes[d]) // std::cerr << "H2D" << d << " from k" << IT.first // << ": " << IT.second << "\n"; // for (auto IT : src2D2HTimes[d]) // std::cerr << "D" << d << "2H from k" << IT.first // << ": " << IT.second << "\n"; // totalPerDevice[d] = H2DTimes[d] + D2HTimes[d] + kernelTimes[d]; // std::cerr << "total on device " << d << " " << totalPerDevice[d] << "\n"; } // for (unsigned d=1; d<nbDevices; d++) // totalPerDevice[0] = totalPerDevice[d] > totalPerDevice[0] ? // totalPerDevice[d] : totalPerDevice[0]; // std::cerr << "total for kernel: " << totalPerDevice[0] << "\n"; } Scheduler::Scheduler(BufferManager *buffManager, unsigned nbDevices) : buffManager(buffManager), nbDevices(nbDevices), count(0) {} Scheduler::~Scheduler() {} void Scheduler::getShiftedPartition(std::vector<NDRange> *shiftedPartition, const NDRange &origNDRange, const NDRange &ndRange, unsigned splitDim, unsigned requiredShift, unsigned *shiftedDeviceIdInPartition) { unsigned work_dim = ndRange.get_work_dim(); size_t global_work_size[work_dim]; size_t global_work_offset[work_dim]; size_t local_work_size[work_dim]; for (unsigned i=0; i<work_dim; i++) { global_work_size[i] = ndRange.get_global_size(i); global_work_offset[i] = ndRange.getOffset(i); local_work_size[i] = ndRange.get_local_size(i); } int NDRangeLB = origNDRange.getOffset(splitDim); int NDRangeHB = NDRangeLB + origNDRange.get_global_size(splitDim) - 1; int oldLB = ndRange.getOffset(splitDim); int oldHB = oldLB + ndRange.get_global_size(splitDim) - 1; int lsize = origNDRange.get_local_size(splitDim); int newLB = oldLB - requiredShift * lsize; int newHB = oldHB + requiredShift * lsize; newLB = newLB < NDRangeLB ? NDRangeLB : newLB; newHB = newHB > NDRangeHB ? NDRangeHB : newHB; *shiftedDeviceIdInPartition = 0; ssize_t offset; ssize_t size; if (newLB > NDRangeLB) { *shiftedDeviceIdInPartition = 1; offset = NDRangeLB; size = newLB -1 - NDRangeLB + 1; assert(offset >= 0); assert(offset % lsize == 0); assert(size > 0); global_work_offset[splitDim] = offset; global_work_size[splitDim] = size; shiftedPartition->push_back(NDRange(work_dim, global_work_size, global_work_offset, local_work_size)); } offset = newLB; size= newHB -newLB + 1; assert(offset >= 0); assert(offset % lsize == 0); assert(size > 0); global_work_offset[splitDim] = offset; global_work_size[splitDim] = size; shiftedPartition->push_back(NDRange(work_dim, global_work_size, global_work_offset, local_work_size)); if (newHB < NDRangeHB) { offset = newHB+1; size= newHB -newLB; assert(offset >= 0); assert(offset % lsize == 0); assert(size > 0); global_work_offset[splitDim] = offset; global_work_size[splitDim] = size; shiftedPartition->push_back(NDRange(work_dim, global_work_size, global_work_offset, local_work_size)); } for (unsigned i=1; i<shiftedPartition->size(); i++) { assert((*shiftedPartition)[i].getOffset(splitDim) == (*shiftedPartition)[i-1].getOffset(splitDim) + (*shiftedPartition)[i-1].get_global_size(splitDim)); } } bool Scheduler::paramHaveChanged(const SubKernelSchedInfo *SI, const KernelHandle *k) { for (unsigned i=0; i<k->getArgsValues().size(); i++) { if (SI->argsValues[i]) { switch(SI->argsValues[i]->type) { case IndexExpr::LONG: if (SI->argsValues[i]->getLongValue() != k->getArgsValues()[i]->getLongValue()) return true; break; case IndexExpr::FLOAT: if (SI->argsValues[i]->getFloatValue() != k->getArgsValues()[i]->getFloatValue()) return true; break; case IndexExpr::DOUBLE: if (SI->argsValues[i]->getDoubleValue() != k->getArgsValues()[i]->getDoubleValue()) return true; break; }; } else { if (k->getArgsValues()[i]) return true; } } return false; } void Scheduler::updateParamValues(SubKernelSchedInfo *SI, const KernelHandle *k) { for (unsigned i=0; i< SI->argsValues.size(); i++) delete SI->argsValues[i]; SI->argsValues.clear(); for (unsigned i=0; i<k->getArgsValues().size(); i++) { if (k->getArgsValues()[i]) SI->argsValues. push_back(static_cast<IndexExprValue *> (k->getArgsValues()[i]->clone())); else SI->argsValues.push_back(nullptr); } } void Scheduler::getIndirectionRegions(KernelHandle *k, size_t work_dim, const size_t *global_work_offset, const size_t *global_work_size, const size_t *local_work_size, std::vector<BufferIndirectionRegion> & regions) { SubKernelSchedInfo *SI = NULL; // Get kernel id unsigned id = getKernelID(k); // Create schedinfo if it doesn't exists yet. if (kerID2InfoMap.find(id) == kerID2InfoMap.end()) { SI = new SubKernelSchedInfo(this, k, nbDevices); SI->last_work_dim = work_dim; for (cl_uint i=0; i<work_dim; i++) { SI->last_global_work_offset[i] = (global_work_offset ? global_work_offset[i] : 0); SI->last_global_work_size[i] = global_work_size[i]; SI->last_local_work_size[i] = local_work_size[i]; } updateParamValues(SI, k); kerID2InfoMap[id] = SI; } else { SI = kerID2InfoMap[id]; } // Get partition if needed (first call to getIndirectionRegions for the // current iteration. if (!SI->hasPartition) { SI->hasPartition = true; if (!SI->hasInitPartition) { getInitialPartition(SI, id, &SI->needOtherExecToComplete); SI->hasInitPartition = true; // Analysis needs to be instantiated SI->needToInstantiateAnalysis = true; } else { // Increment iteration counter. SI->iterno++; // Get next partition. getNextPartition(SI, id, &SI->needOtherExecToComplete, &SI->needToInstantiateAnalysis); } // Check if scalar parameters or buffer parameters have changed. // For buffers we consider its address as a long value. if (paramHaveChanged(SI, k)) { SI->needToInstantiateAnalysis = true; updateParamValues(SI, k); } // Check if original NDRange has changed. if (SI->last_work_dim != work_dim) { SI->needToInstantiateAnalysis = true; } else { for (cl_uint i=0; i<work_dim; i++) { if (SI->last_global_work_offset[i] != (global_work_offset ? global_work_offset[i] : 0) || SI->last_global_work_size[i] != global_work_size[i] || SI->last_local_work_size[i] != local_work_size[i]) { SI->needToInstantiateAnalysis = true; break; } } } SI->last_work_dim = work_dim; for (cl_uint i=0; i<work_dim; i++) { SI->last_global_work_offset[i] = (global_work_offset ? global_work_offset[i] : 0); SI->last_global_work_size[i] = global_work_size[i]; SI->last_local_work_size[i] = local_work_size[i]; } // Sort the NDRange dimensions if analysis needs to be instantiated. getSortedDim(work_dim, global_work_size, local_work_size, SI->dimOrder); // Hack to split the second dimension for clHeat if (!strcmp(k->getName(), "getMaxDerivIntel")) { SI->dimOrder[0] = 1; SI->dimOrder[1] = 0; } SI->currentDim = 0; } // Analysis needs to be instantiated every time if the kernel has indirections. if (k->getAnalysis()->hasIndirection() && optEnableIndirections) { SI->needToInstantiateAnalysis = true; } if (SI->needToInstantiateAnalysis && !SI->partitionUnchanged) { // Copy requested granularity to real granularity. std::copy(SI->req_granu_dscr, SI->req_granu_dscr+SI->req_size_gr, SI->real_granu_dscr); SI->real_size_gr = SI->req_size_gr; } if (!SI->needToInstantiateAnalysis) return; // Fail case if (SI->currentDim >= work_dim) { std::cerr << "Cannot split kernel " << k->getName() << "\n"; SI->real_size_gr = 3; SI->real_granu_dscr[0] = 0; SI->real_granu_dscr[1] = 1.0; SI->real_granu_dscr[2] = 1.0; SI->currentDim = 0; } // Shifting if (!SI->partitionUnchanged && SI->shiftingPartition) { SI->partitionUnchanged = true; // Shift sub ndranges unsigned shiftingDevice = SI->shiftingDevice; NDRange *origNDRange = SI->origNDRange; std::vector<NDRange> shiftedPartition; unsigned shiftedDeviceIdInPartition; getShiftedPartition(&shiftedPartition, *origNDRange, SI->requiredSubNDRanges[shiftingDevice], SI->dimOrder[SI->currentDim], SI->shiftingWgs, &shiftedDeviceIdInPartition); // Save current device ID in shifted partition SI->shiftedDeviceIdInPartition = shiftedDeviceIdInPartition; // Save current device shifted NDRange SI->shiftedSubNDRanges[shiftingDevice] = shiftedPartition[shiftedDeviceIdInPartition]; // Set partition k->getAnalysis()->setPartition(*origNDRange, shiftedPartition, k->getArgsValues()); } // New scheduler partition if (!SI->partitionUnchanged && !SI->shiftingPartition) { // Adapt partition. unsigned nbSplits = SI->real_size_gr / 3; unsigned currentDim = SI->currentDim; unsigned nbWgs = global_work_size[SI->dimOrder[currentDim]] / local_work_size[SI->dimOrder[currentDim]]; if (nbWgs < nbSplits) { SI->real_size_gr = nbWgs * 3; for (unsigned w=0; w<nbWgs; w++) SI->real_granu_dscr[w*3+2] = 1.0 / nbWgs; DEBUG("granu", std::cerr << "kernel " << k->getName() << ": insufficient number of workgroups !" << " (" << nbWgs << ")\n"; std::cerr << "requested partition : "; for (int ii=0; ii<SI->req_size_gr; ii++) std::cerr << SI->req_granu_dscr[ii] << " "; std::cerr << "\n"; std::cerr << "adapted partition : "; for (int ii=0; ii<SI->real_size_gr; ii++) std::cerr << SI->real_granu_dscr[ii] << " "; std::cerr << "\n";); } adaptGranudscr(SI->real_granu_dscr, &SI->real_size_gr, global_work_size[SI->dimOrder[currentDim]], local_work_size[SI->dimOrder[currentDim]]); nbSplits = SI->real_size_gr / 3; // Create original and sub NDRanges. delete SI->origNDRange; SI->origNDRange = new NDRange(work_dim, global_work_size, global_work_offset, local_work_size); std::vector<NDRange> subNDRanges; SI->origNDRange->splitDim(SI->dimOrder[currentDim], SI->real_size_gr, SI->real_granu_dscr, &subNDRanges); SI->requiredSubNDRanges = subNDRanges; // Set partition to analysis k->getAnalysis()->setPartition(*SI->origNDRange, subNDRanges, k->getArgsValues()); } // Get indirection regions. if (!optEnableIndirections) return; k->getAnalysis()->computeIndirections(); unsigned nbSplits = SI->real_size_gr / 3; for (unsigned s=0; s<nbSplits; s++) { const std::vector<ArgIndirectionRegion *> argRegions = k->getAnalysis()->getSubkernelIndirectionsRegions(s); for (unsigned i=0; i<argRegions.size(); i++) { unsigned argGlobalId = k->getAnalysis()->getGlobalArgId(argRegions[i]->pos); MemoryHandle *m = k->getGlobalArgHandle(argGlobalId); regions.push_back(BufferIndirectionRegion(s, argRegions[i]->id, m, argRegions[i]->ty, argRegions[i]->cb, argRegions[i]->lb, argRegions[i]->hb)); } } } bool Scheduler::setIndirectionValues(KernelHandle *k, const std::vector<BufferIndirectionRegion> & regions) { // Get kernel id unsigned id = getKernelID(k); // Get schedinfo SubKernelSchedInfo *SI = kerID2InfoMap[id]; // Instantiate analysis if needed. if (SI->needToInstantiateAnalysis) { // Set indirections values to analysis. unsigned nbSplit = SI->real_size_gr / 3; if (regions.size() > 0) { std::vector<IndirectionValue> regionValues[nbSplit]; for (unsigned i=0; i<regions.size(); i++) { unsigned subkernelId = regions[i].subkernelId; unsigned indirectionId = regions[i].indirectionId; IndexExprValue *lbValue = (IndexExprValue *) regions[i].lbValue->clone(); IndexExprValue *hbValue = (IndexExprValue *) regions[i].hbValue->clone(); regionValues[subkernelId].push_back(IndirectionValue(indirectionId, lbValue, hbValue)); } for (unsigned i=0; i<nbSplit; i++) { k->getAnalysis()->setSubkernelIndirectionsValues(i, regionValues[i]); } } // Check if there is missing indirection values. if (optEnableIndirections) { if (k->getAnalysis()->indirectionMissing()) { SI->partitionUnchanged = true; return false; } else { SI->partitionUnchanged = false; } } // Perform analysis with current partition ArgumentAnalysis::status st = k->getAnalysis()->performAnalysis(); DEBUG("dynanalysis", k->getAnalysis()->debug();); // Single device, we don't care about the analysis status. if (nbSplit == 1 && ! SI->shiftingPartition) { fillSubkernelInfoSingle(k, SI->real_granu_dscr, &SI->real_size_gr, SI->dimOrder[SI->currentDim], SI->subkernels, SI->dataRequired, SI->dataWritten, SI->dataWrittenMerge, SI->dataWrittenOr, SI->dataWrittenAtomicSum, SI->dataWrittenAtomicMin, SI->dataWrittenAtomicMax); return true; } switch(st) { case ArgumentAnalysis::SUCCESS: DEBUG("status", std::cerr << k->getName() << " success\n"); break; case ArgumentAnalysis::MERGE: DEBUG("status", std::cerr << k->getName() << " merge\n";); break; case ArgumentAnalysis::FAIL: DEBUG("status", std::cerr << k->getName() << " fail\n";); break; } // Multi device Shifting if (SI->shiftingPartition) { // Save shifted device analyse unsigned shiftingDevice = SI->shiftingDevice; unsigned shiftingID = SI->shiftedDeviceIdInPartition; KernelAnalysis *analysis = k->getAnalysis(); unsigned nbGlobals = analysis->getNbGlobalArguments(); for (unsigned a=0; a<nbGlobals; a++) { SI->shiftDataRequired[shiftingDevice][a] = analysis->getArgReadSubkernelRegion(a, shiftingID); if (!analysis->argReadBoundsComputed(a)) SI->shiftDataRequired[shiftingDevice][a].setUndefined(); SI->shiftDataWritten[shiftingDevice][a].myUnion( analysis->getArgWrittenSubkernelRegion(a, shiftingID)); SI->shiftDataWrittenOr[shiftingDevice][a] = analysis->getArgWrittenOrSubkernelRegion(a, shiftingID); SI->shiftDataWrittenAtomicSum[shiftingDevice][a] = analysis->getArgWrittenAtomicSumSubkernelRegion(a, shiftingID); if (!analysis->argWrittenAtomicSumBoundsComputed(a)) { SI->shiftDataRequired[shiftingDevice][a].setUndefined(); SI->shiftDataWrittenAtomicSum[shiftingDevice][a].setUndefined(); } SI->shiftDataWrittenAtomicMin[shiftingDevice][a] = analysis->getArgWrittenAtomicMinSubkernelRegion(a, shiftingID); SI->shiftDataWrittenAtomicMax[shiftingDevice][a] = analysis->getArgWrittenAtomicMaxSubkernelRegion(a, shiftingID); } unsigned nbDevices = SI->real_size_gr / 3; // If the device shifted is the last one, test if the union of the // the for each merge argument if the union of the single written // region in included in the full written region. if (SI->shiftingDevice == nbDevices - 1) { bool shiftDone = true; DEBUG("shifted", std::cerr << "shifted workgroups = " << SI->shiftingWgs << " shifted ids " << SI->shiftingWgs * SI->origNDRange->get_local_size(SI->dimOrder[SI->currentDim]) << "\n"; for (unsigned i=0; i<nbDevices; i++) { std::cerr << "shift ndRange dev " << i << ": "; SI->shiftedSubNDRanges[i].dump(); }); for (unsigned a=0; a<SI->nbMergeArgs; a++) { ListInterval fullSingleWrittenRegion; unsigned globalPos = SI->mergeArg2GlobalPos[a]; for (unsigned i=0; i<nbDevices; i++) { fullSingleWrittenRegion.myUnion(SI->shiftDataWritten[i][globalPos]); DEBUG("shift", std::cerr << "single written region global " << globalPos << " dev " << i << ": "; SI->shiftDataWritten[i][globalPos].debug(); std::cerr << "\n";); } DEBUG("shift", std::cerr << "full written region global " << globalPos << ": "; SI->fullWrittenRegion[globalPos]->debug(); std::cerr << "\n";); ListInterval *difference = ListInterval::difference(*SI->fullWrittenRegion[globalPos], fullSingleWrittenRegion); if (difference->total() > 0) shiftDone = false; delete difference; } /* Fix a bug in SOTL when shifting. * * The valid data written cannot overlap between devices. */ if (shiftDone && !strcmp(k->getName(), "box_sort")) { for (unsigned a=0; a<SI->nbMergeArgs; a++) { unsigned globalPos = SI->mergeArg2GlobalPos[a]; for (unsigned i=0; i<nbDevices; i++) { for (unsigned j=i+1; j<nbDevices; j++) { if (i == j) continue; ListInterval *intersection = ListInterval::intersection(SI->shiftDataWritten[i][globalPos], SI->shiftDataWritten[j][globalPos]); if (intersection->total() > 0) SI->shiftDataWritten[i][globalPos].difference(*intersection); delete intersection; } } } } if (shiftDone) { DEBUG("shiftingpercent", int splitDim = SI->dimOrder[SI->currentDim]; int nbWgs = SI->origNDRange->get_global_size(splitDim) / SI->origNDRange->get_local_size(splitDim); std::cerr << "shifting percent : " << (((double) SI->shiftingWgs) / nbWgs) * 100 << "\n"; ); SI->partitionUnchanged = false; SI->shiftingPartition = false; fillSubkernelInfoShift(k, SI, *SI->origNDRange, SI->shiftedSubNDRanges, SI->real_granu_dscr, &SI->real_size_gr, SI->dimOrder[SI->currentDim], SI->subkernels, k->getAnalysis()->getNbGlobalArguments(), SI->dataRequired, SI->dataWritten, SI->dataWrittenMerge, SI->dataWrittenOr, SI->dataWrittenAtomicSum, SI->dataWrittenAtomicMin, SI->dataWrittenAtomicMax); DEBUG("shiftmax", static unsigned shiftingMax = 0; shiftingMax = shiftingMax > SI->shiftingWgs ? shiftingMax : SI->shiftingWgs; std::cerr << "shiftingMax = " << shiftingMax << "\n"; ); DEBUG("currentshift", std::cerr << "shift: " << SI->shiftingWgs << "\n";); return true; } else { SI->shiftingDevice = 0; if (optShiftStep > 0) { SI->shiftingWgs += optShiftStep; } else { SI->shiftingWgs *= 2; } SI->needToInstantiateAnalysis = true; SI->shiftDataRequired.clear(); SI->shiftDataRequired.resize(nbDevices); SI->shiftDataWrittenOr.clear(); SI->shiftDataWrittenOr.resize(nbDevices); SI->shiftDataWrittenAtomicSum.clear(); SI->shiftDataWrittenAtomicSum.resize(nbDevices); SI->shiftDataWrittenAtomicMin.clear(); SI->shiftDataWrittenAtomicMin.resize(nbDevices); SI->shiftDataWrittenAtomicMax.clear(); SI->shiftDataWrittenAtomicMax.resize(nbDevices); unsigned nbGlobals = analysis->getNbGlobalArguments(); for (unsigned i=0; i<nbDevices; i++) { SI->shiftDataRequired[i].resize(nbGlobals); SI->shiftDataWrittenOr[i].resize(nbGlobals); SI->shiftDataWrittenAtomicSum[i].resize(nbGlobals); SI->shiftDataWrittenAtomicMin[i].resize(nbGlobals); SI->shiftDataWrittenAtomicMax[i].resize(nbGlobals); } return false; } } else { SI->shiftingDevice++; SI->needToInstantiateAnalysis = true; return false; } } // Multi device switch (st) { case ArgumentAnalysis::FAIL: std::cerr << "cannot split dim " << SI->dimOrder[SI->currentDim] << "\n"; SI->currentDim++; SI->needToInstantiateAnalysis = true; return false; case ArgumentAnalysis::MERGE: { assert(!SI->shiftingPartition); SI->shiftingPartition = true; SI->shiftingDevice = 0; unsigned splitDim = SI->dimOrder[SI->currentDim]; if (optShiftInit > 0) { SI->shiftingWgs = optShiftInit; } else { unsigned nbWgs = SI->origNDRange->get_global_size(splitDim) / SI->origNDRange->get_local_size(splitDim); SI->shiftingWgs = nbWgs / 100; SI->shiftingWgs = SI->shiftingWgs > 0 ? SI->shiftingWgs : 1; assert(SI->shiftingWgs > 0); } SI->shiftedSubNDRanges = SI->requiredSubNDRanges; SI->nbMergeArgs = k->getAnalysis()->getNbMergeArguments(); SI->mergeArg2GlobalPos.clear(); SI->shiftDataRequired.clear(); SI->shiftDataRequired.resize(nbDevices); SI->shiftDataWritten.clear(); SI->shiftDataWritten.resize(nbDevices); SI->shiftDataWrittenOr.clear(); SI->shiftDataWrittenOr.resize(nbDevices); SI->shiftDataWrittenAtomicSum.clear(); SI->shiftDataWrittenAtomicSum.resize(nbDevices); SI->shiftDataWrittenAtomicMin.clear(); SI->shiftDataWrittenAtomicMin.resize(nbDevices); SI->shiftDataWrittenAtomicMax.clear(); SI->shiftDataWrittenAtomicMax.resize(nbDevices); unsigned nbGlobals = k->getAnalysis()->getNbGlobalArguments(); for (unsigned i=0; i<nbDevices; i++) { SI->shiftDataRequired[i].resize(nbGlobals); SI->shiftDataWritten[i].resize(nbGlobals); SI->shiftDataWrittenOr[i].resize(nbGlobals); SI->shiftDataWrittenAtomicSum[i].resize(nbGlobals); SI->shiftDataWrittenAtomicMin[i].resize(nbGlobals); SI->shiftDataWrittenAtomicMax[i].resize(nbGlobals); } // Save full written region for merge arguments. for (unsigned a=0; a<SI->nbMergeArgs; a++) { unsigned globalPos = k->getAnalysis()->getMergeArgGlobalPos(a); SI->mergeArg2GlobalPos[a] = globalPos; SI->fullWrittenRegion[globalPos] = k->getAnalysis()->getArgFullWrittenRegion(globalPos); } SI->needToInstantiateAnalysis = true; return false; } case ArgumentAnalysis::SUCCESS: SI->partitionUnchanged = false; fillSubkernelInfoMulti(k, SI->real_granu_dscr, &SI->real_size_gr, SI->dimOrder[SI->currentDim], SI->subkernels, SI->dataRequired, SI->dataWritten, SI->dataWrittenMerge, SI->dataWrittenOr, SI->dataWrittenAtomicSum, SI->dataWrittenAtomicMin, SI->dataWrittenAtomicMax); return true; }; } SI->partitionUnchanged = false; return true; } void Scheduler::getPartition(KernelHandle *k, /* IN */ bool *needOtherExecutionToComplete, /* OUT */ std::vector<SubKernelExecInfo *> &subkernels, /* OUT */ std::vector<DeviceBufferRegion> &dataRequired, /* OUT */ std::vector<DeviceBufferRegion> &dataWritten, /* OUT */ std::vector<DeviceBufferRegion> &dataWrittenMerge, /* OUT */ std::vector<DeviceBufferRegion> &dataWrittenOr, /* OUT */ std::vector<DeviceBufferRegion> &dataWrittenAtomicSum, /* OUT */ std::vector<DeviceBufferRegion> &dataWrittenAtomicMin, /* OUT */ std::vector<DeviceBufferRegion> &dataWrittenAtomicMax, /* OUT */ unsigned *id) /* OUT */ { // Get kernel id *id = getKernelID(k); // Get schedinfo SubKernelSchedInfo *SI = kerID2InfoMap[*id]; SI->hasPartition = false; // Set output. for (unsigned i=0; i<SI->subkernels.size(); i++) subkernels.push_back(SI->subkernels[i]); dataRequired = SI->dataRequired; dataWritten = SI->dataWritten; dataWrittenMerge = SI->dataWrittenMerge; dataWrittenOr = SI->dataWrittenOr; dataWrittenAtomicSum = SI->dataWrittenAtomicSum; dataWrittenAtomicMin = SI->dataWrittenAtomicMin; dataWrittenAtomicMax = SI->dataWrittenAtomicMax; *needOtherExecutionToComplete = SI->needOtherExecToComplete; // Compute granu intervals for (unsigned d=0; d<SI->nbDevices; d++) { SI->granu_intervals[d].clear(); } unsigned splitDim = SI->dimOrder[SI->currentDim]; size_t origNDRange = SI->origNDRange->get_global_size(splitDim); for (SubKernelExecInfo *SE : subkernels) { double granu_cb = (double) SE->global_work_size[splitDim] / origNDRange; double granu_offset = (double) SE->global_work_offset[splitDim] / origNDRange; size_t cb = granu_cb * GRANU2INTFACTOR; size_t offset = granu_offset * GRANU2INTFACTOR; if (cb > 0) { SI->granu_intervals[SE->device].add(Interval(offset, offset+cb-1)); assert(offset+cb-1 < (unsigned) GRANU2INTFACTOR); } } double partition[nbDevices+1] = {0}; partition[0] = *id; for (int i=0; i<SI->real_size_gr/3; i++) partition[(int) SI->real_granu_dscr[i*3]+1] = SI->real_granu_dscr[i*3+2]; timeline->pushPartition(partition); double reqpartition[nbDevices+1] = {0}; reqpartition[0] = *id; for (int i=0; i<SI->req_size_gr/3; i++) reqpartition[(int) SI->req_granu_dscr[i*3]+1] = SI->req_granu_dscr[i*3+2]; timeline->pushReqPartition(reqpartition); // Increment call count. count++; } void Scheduler::setH2DEvent(unsigned srcId, unsigned dstId, unsigned devId, unsigned cb, Event *event) { assert(kerID2InfoMap.find(dstId) != kerID2InfoMap.end()); SubKernelSchedInfo *SI = kerID2InfoMap[dstId]; SI->src2H2DEvents[devId][srcId].push_back(event); SI->src2H2DEventsCB[devId][srcId].push_back(cb); } void Scheduler::setD2HEvent(unsigned srcId, unsigned dstId, unsigned devId, unsigned cb, Event *event) { assert(kerID2InfoMap.find(dstId) != kerID2InfoMap.end()); SubKernelSchedInfo *SI = kerID2InfoMap[dstId]; SI->src2D2HEvents[devId][srcId].push_back(event); SI->src2D2HEventsCB[devId][srcId].push_back(cb); } void Scheduler::setBufferRequired(unsigned kerId, MemoryHandle *buffer) { assert(kerID2InfoMap.find(kerId) != kerID2InfoMap.end()); SubKernelSchedInfo *SI = kerID2InfoMap[kerId]; SI->buffersRequired.insert(buffer); } void Scheduler::printPartition(SubKernelSchedInfo *SI) { std::cerr << "<"; for (int i=0; i<SI->real_size_gr-1; i++) std::cerr << SI->real_granu_dscr[i] << ","; std::cerr << SI->real_granu_dscr[SI->real_size_gr-1] << ">\n"; } // Compute the array of dimension id from the one with // the maximum number of splits. void Scheduler::getSortedDim(cl_uint work_dim, const size_t *global_work_size, const size_t *local_work_size, unsigned order[3]) { unsigned dimSplitMax[work_dim]; for (unsigned i=0; i<work_dim; i++) { dimSplitMax[i] = global_work_size[i] / local_work_size[i]; order[i] = i; } bool changed; do { changed = false; for (unsigned i=0; i<work_dim-1; i++) { if (dimSplitMax[i+1] > dimSplitMax[i]) { unsigned tmpMax = dimSplitMax[i+1]; dimSplitMax[i+1] = dimSplitMax[i]; dimSplitMax[i] = tmpMax; unsigned tmpId = order[i+1]; order[i+1] = order[i]; order[i] = tmpId; changed = true; } } } while (changed); } bool Scheduler::fillSubkernelInfoMulti(KernelHandle *k, double *granu_dscr, int *size_gr, unsigned splitDim, std::vector<SubKernelExecInfo *> &subkernels, std::vector<DeviceBufferRegion> &dataRequired, std::vector<DeviceBufferRegion> &dataWritten, std::vector<DeviceBufferRegion> &dataWrittenMerge, std::vector<DeviceBufferRegion> &dataWrittenOr, std::vector<DeviceBufferRegion> &dataWrittenAtomicSum, std::vector<DeviceBufferRegion> &dataWrittenAtomicMin, std::vector<DeviceBufferRegion> &dataWrittenAtomicMax) { dataRequired.clear(); dataWritten.clear(); dataWrittenMerge.clear(); dataWrittenOr.clear(); dataWrittenAtomicSum.clear(); dataWrittenAtomicMin.clear(); dataWrittenAtomicMax.clear(); dataWrittenMerge.clear(); for (unsigned i=0; i<subkernels.size(); i++) delete subkernels[i]; subkernels.clear(); KernelAnalysis *analysis = k->getAnalysis(); const NDRange &origNDRange = analysis->getKernelNDRange(); const std::vector<NDRange> &subNDRanges = analysis->getSubNDRanges(); int nbSplits = *size_gr / 3; unsigned work_dim = origNDRange.get_work_dim(); unsigned num_groups = origNDRange.get_global_size(splitDim) / origNDRange.get_local_size(splitDim); // Fill subkernels vector for (int i=0; i<nbSplits; i++) { unsigned devId = granu_dscr[i*3]; SubKernelExecInfo *subkernel = new SubKernelExecInfo(); subkernel->device = devId; subkernel->work_dim = work_dim; for (unsigned dim=0; dim < work_dim; dim++) { subkernel->global_work_offset[dim] = subNDRanges[i].getOffset(dim); subkernel->global_work_size[dim] = subNDRanges[i].get_global_size(dim); subkernel->local_work_size[dim] = subNDRanges[i].get_local_size(dim); } subkernel->numgroups = num_groups; subkernel->splitdim = splitDim; subkernels.push_back(subkernel); } // CHECK CODE unsigned totalGsize = origNDRange.getOffset(splitDim); for (unsigned i=0; i<subkernels.size(); i++) { assert(subkernels[i]->global_work_offset[splitDim] == totalGsize); totalGsize += subkernels[i]->global_work_size[splitDim]; } totalGsize -= origNDRange.getOffset(splitDim); // END CHECK CODE // Fill dataRequired and dataWritten vectors unsigned nbGlobals = analysis->getNbGlobalArguments(); for (unsigned a=0; a<nbGlobals; a++) { MemoryHandle *m = k->getGlobalArgHandle(a); assert(m); // Compute written merge region ListInterval writtenMergeRegion; writtenMergeRegion.myUnion(analysis->getArgWrittenMergeRegion(a)); for (int i=0; i<nbSplits; i++) { ListInterval readRegion, writtenRegion, writtenOrRegion, writtenAtomicSumRegion, writtenAtomicMinRegion, writtenAtomicMaxRegion; unsigned devId = granu_dscr[i*3]; // Compute read region if (!analysis->argReadBoundsComputed(a)) { readRegion.setUndefined(); } if (!analysis->argWrittenAtomicSumBoundsComputed(a)) { readRegion.setUndefined(); writtenAtomicSumRegion.setUndefined(); } if (analysis->argIsReadBySubkernel(a, i)) { readRegion.myUnion(analysis->getArgReadSubkernelRegion(a, i)); } // Compute written region if (analysis->argIsWrittenBySubkernel(a, i)) writtenRegion.myUnion(analysis->getArgWrittenSubkernelRegion(a, i)); // Compute written_or region if (analysis->argIsWrittenOrBySubkernel(a, i)) writtenOrRegion.myUnion(analysis-> getArgWrittenOrSubkernelRegion(a, i)); // Compute written_atomic_sum region if (analysis->argIsWrittenAtomicSumBySubkernel(a, i)) writtenAtomicSumRegion. myUnion(analysis->getArgWrittenAtomicSumSubkernelRegion(a, i)); // Compute written_atomic_min region if (analysis->argIsWrittenAtomicMinBySubkernel(a, i)) writtenAtomicMinRegion. myUnion(analysis->getArgWrittenAtomicMinSubkernelRegion(a, i)); // Compute written_atomic_max region if (analysis->argIsWrittenAtomicMaxBySubkernel(a, i)) writtenAtomicMaxRegion. myUnion(analysis->getArgWrittenAtomicMaxSubkernelRegion(a, i)); // The data written have to be send to the device. readRegion.myUnion(analysis->getArgWrittenSubkernelRegion(a, i)); readRegion.myUnion(analysis->getArgWrittenOrSubkernelRegion(a, i)); readRegion.myUnion(analysis-> getArgWrittenAtomicSumSubkernelRegion(a, i)); readRegion.myUnion(analysis-> getArgWrittenAtomicMinSubkernelRegion(a, i)); readRegion.myUnion(analysis-> getArgWrittenAtomicMaxSubkernelRegion(a, i)); readRegion.myUnion(writtenMergeRegion); if (readRegion.total() > 0 || readRegion.isUndefined()) dataRequired.push_back(DeviceBufferRegion(m, devId, readRegion)); if (writtenRegion.total() > 0) dataWritten.push_back(DeviceBufferRegion(m, devId, writtenRegion)); if (writtenOrRegion.total() > 0) dataWrittenOr. push_back(DeviceBufferRegion(m, devId, writtenOrRegion)); if (writtenAtomicSumRegion.total() > 0 || writtenAtomicSumRegion.isUndefined()) dataWrittenAtomicSum. push_back(DeviceBufferRegion(m, devId, writtenAtomicSumRegion)); if (writtenAtomicMinRegion.total() > 0) dataWrittenAtomicMin. push_back(DeviceBufferRegion(m, devId, writtenAtomicMinRegion)); if (writtenAtomicMaxRegion.total() > 0) dataWrittenAtomicMax. push_back(DeviceBufferRegion(m, devId, writtenAtomicMaxRegion)); if (writtenMergeRegion.total() > 0) dataWrittenMerge. push_back(DeviceBufferRegion(m, devId, writtenMergeRegion)); } } return true; } bool Scheduler::fillSubkernelInfoShift(KernelHandle *k, SubKernelSchedInfo *SI, const NDRange &origNDRange, const std::vector<NDRange> &subNDRanges, double *granu_dscr, int *size_gr, unsigned splitDim, std::vector<SubKernelExecInfo *> &subkernels, unsigned nbGlobals, std::vector<DeviceBufferRegion> &dataRequired, std::vector<DeviceBufferRegion> &dataWritten, std::vector<DeviceBufferRegion> &dataWrittenMerge, std::vector<DeviceBufferRegion> &dataWrittenOr, std::vector<DeviceBufferRegion> &dataWrittenAtomicSum, std::vector<DeviceBufferRegion> &dataWrittenAtomicMin, std::vector<DeviceBufferRegion> &dataWrittenAtomicMax) { dataRequired.clear(); dataWritten.clear(); dataWrittenMerge.clear(); dataWrittenOr.clear(); dataWrittenAtomicSum.clear(); dataWrittenAtomicMin.clear(); dataWrittenAtomicMax.clear(); dataWrittenMerge.clear(); for (unsigned i=0; i<subkernels.size(); i++) delete subkernels[i]; subkernels.clear(); int nbSplits = *size_gr / 3; unsigned work_dim = origNDRange.get_work_dim(); unsigned num_groups = origNDRange.get_global_size(splitDim) / origNDRange.get_local_size(splitDim); // Fill subkernels vector for (int i=0; i<nbSplits; i++) { unsigned devId = granu_dscr[i*3]; SubKernelExecInfo *subkernel = new SubKernelExecInfo(); subkernel->device = devId; subkernel->work_dim = work_dim; for (unsigned dim=0; dim < work_dim; dim++) { subkernel->global_work_offset[dim] = subNDRanges[i].getOffset(dim); subkernel->global_work_size[dim] = subNDRanges[i].get_global_size(dim); subkernel->local_work_size[dim] = subNDRanges[i].get_local_size(dim); } subkernel->numgroups = num_groups; subkernel->splitdim = splitDim; subkernels.push_back(subkernel); // Update granu dscr double updatedGranu = ((double) subkernel->global_work_size[splitDim]) / origNDRange.get_global_size(splitDim); granu_dscr[i*3+2] = updatedGranu; } // Fill dataRequired and dataWritten vectors for (unsigned a=0; a<nbGlobals; a++) { MemoryHandle *m = k->getGlobalArgHandle(a); assert(m); for (int i=0; i<nbSplits; i++) { unsigned devId = granu_dscr[i*3]; // The data written have to be send to the device. SI->shiftDataRequired[i][a].myUnion(SI->shiftDataWritten[i][a]); SI->shiftDataRequired[i][a].myUnion(SI->shiftDataWrittenOr[i][a]); SI->shiftDataRequired[i][a].myUnion(SI->shiftDataWrittenAtomicSum[i][a]); SI->shiftDataRequired[i][a].myUnion(SI->shiftDataWrittenAtomicMin[i][a]); SI->shiftDataRequired[i][a].myUnion(SI->shiftDataWrittenAtomicMax[i][a]); if (SI->shiftDataRequired[i][a].total() > 0 || SI->shiftDataRequired[i][a].isUndefined()) dataRequired.push_back(DeviceBufferRegion(m, devId, SI->shiftDataRequired[i][a])); if (SI->shiftDataWritten[i][a].total() > 0) dataWritten.push_back(DeviceBufferRegion(m, devId, SI->shiftDataWritten[i][a])); if (SI->shiftDataWrittenOr[i][a].total() > 0) dataWrittenOr. push_back(DeviceBufferRegion(m, devId, SI->shiftDataWrittenOr[i][a])); if (SI->shiftDataWrittenAtomicSum[i][a].total() > 0 || SI->shiftDataWrittenAtomicSum[i][a].isUndefined()) dataWrittenAtomicSum. push_back(DeviceBufferRegion(m, devId, SI->shiftDataWrittenAtomicSum[i][a])); if (SI->shiftDataWrittenAtomicMin[i][a].total() > 0) dataWrittenAtomicMin. push_back(DeviceBufferRegion(m, devId, SI->shiftDataWrittenAtomicMin[i][a])); if (SI->shiftDataWrittenAtomicMax[i][a].total() > 0) dataWrittenAtomicMax. push_back(DeviceBufferRegion(m, devId, SI->shiftDataWrittenAtomicMax[i][a])); } } return true; } bool Scheduler::fillSubkernelInfoSingle(KernelHandle *k, double *granu_dscr, int *size_gr, unsigned splitDim, std::vector<SubKernelExecInfo *> &subkernels, std::vector<DeviceBufferRegion> &dataRequired, std::vector<DeviceBufferRegion> &dataWritten, std::vector<DeviceBufferRegion> &dataWrittenMerge, std::vector<DeviceBufferRegion> &dataWrittenOr, std::vector<DeviceBufferRegion> &dataWrittenAtomicSum, std::vector<DeviceBufferRegion> &dataWrittenAtomicMin, std::vector<DeviceBufferRegion> &dataWrittenAtomicMax) { dataRequired.clear(); dataWritten.clear(); dataWrittenMerge.clear(); dataWrittenOr.clear(); dataWrittenAtomicSum.clear(); dataWrittenAtomicMin.clear(); dataWrittenAtomicMax.clear(); for (unsigned i=0; i<subkernels.size(); i++) delete subkernels[i]; subkernels.clear(); KernelAnalysis *analysis = k->getAnalysis(); const NDRange &origNDRange = analysis->getKernelNDRange(); const std::vector<NDRange> &subNDRanges = analysis->getSubNDRanges(); int nbSplits = *size_gr / 3; assert(nbSplits == 1); unsigned work_dim = origNDRange.get_work_dim(); unsigned num_groups = origNDRange.get_global_size(splitDim) / origNDRange.get_local_size(splitDim); // Fill subkernels vector for (int i=0; i<nbSplits; i++) { unsigned devId = granu_dscr[i*3]; SubKernelExecInfo *subkernel = new SubKernelExecInfo(); subkernel->device = devId; subkernel->work_dim = work_dim; for (unsigned dim=0; dim < work_dim; dim++) { subkernel->global_work_offset[dim] = subNDRanges[i].getOffset(dim); subkernel->global_work_size[dim] = subNDRanges[i].get_global_size(dim); subkernel->local_work_size[dim] = subNDRanges[i].get_local_size(dim); } subkernel->numgroups = num_groups; subkernel->splitdim = splitDim; subkernels.push_back(subkernel); } // CHECK CODE unsigned totalGsize = origNDRange.getOffset(splitDim); for (unsigned i=0; i<subkernels.size(); i++) { assert(subkernels[i]->global_work_offset[splitDim] == totalGsize); totalGsize += subkernels[i]->global_work_size[splitDim]; } totalGsize -= origNDRange.getOffset(splitDim); // END CHECK CODE // Fill dataRequired and dataWritten vectors unsigned nbGlobals = analysis->getNbGlobalArguments(); for (unsigned a=0; a<nbGlobals; a++) { MemoryHandle *m = k->getGlobalArgHandle(a); assert(m); for (int i=0; i<nbSplits; i++) { ListInterval readRegion, writtenRegion; unsigned devId = granu_dscr[i*3]; // Case where written region is unknown if (!analysis->argWrittenBoundsComputed(a) || !analysis->argWrittenOrBoundsComputed(a) || !analysis->argWrittenAtomicSumBoundsComputed(a) || !analysis->argWrittenAtomicMinBoundsComputed(a) || !analysis->argWrittenAtomicMaxBoundsComputed(a)) { writtenRegion.setUndefined(); readRegion.setUndefined(); } // Case where writtenRegion is known. else { // Read Region if (!analysis->argReadBoundsComputed(a)) { readRegion.setUndefined(); } else { readRegion.myUnion(analysis->getArgReadSubkernelRegion(a, i)); } // Written Region writtenRegion.myUnion(analysis->getArgWrittenSubkernelRegion(a, i)); writtenRegion.myUnion(analysis->getArgWrittenOrSubkernelRegion(a, i)); writtenRegion.myUnion(analysis->getArgWrittenAtomicSumSubkernelRegion(a, i)); writtenRegion.myUnion(analysis->getArgWrittenAtomicMinSubkernelRegion(a, i)); writtenRegion.myUnion(analysis->getArgWrittenAtomicMaxSubkernelRegion(a, i)); readRegion.myUnion(writtenRegion); } if (readRegion.total() > 0 || readRegion.isUndefined()) dataRequired.push_back(DeviceBufferRegion(m, devId, readRegion)); if (writtenRegion.total() > 0 || writtenRegion.isUndefined()) { dataWritten.push_back(DeviceBufferRegion(m, devId, writtenRegion)); } } } return true; } void Scheduler::adaptGranudscr(double *granu_dscr, int *size_gr, size_t global_work_size, size_t local_work_size) { int nbSplits = *size_gr / 3; // Compact granus (only one kernel per device) for (int i=0; i<nbSplits; i++) { granu_dscr[i*3+2] = granu_dscr[i*3+1] * granu_dscr[i*3+2]; granu_dscr[i*3+1] = 1; } // Adapt granularity depending on the minimum granularity (global/local). for (int i=0; i<nbSplits; i++) { int nbWgs = global_work_size / local_work_size; granu_dscr[i*3+2] *= nbWgs; granu_dscr[i*3+2] = round(granu_dscr[i*3+2]); granu_dscr[i*3+2] /= nbWgs; } // Adapt granularity depending on the number of work groups. // The total granularity has to be equal to 1.0 and granu_dscr cannot // contain a kernel with a null granularity. int idx = 0; double totalGranu = 0; for (int i=0; i<nbSplits; i++) { granu_dscr[idx*3] = granu_dscr[i*3]; // device granu_dscr[idx*3+2] = granu_dscr[i*3+2]; // granu totalGranu += granu_dscr[i*3+2]; if (granu_dscr[i*3+2] > 0) idx++; if (totalGranu >= 1) { granu_dscr[i*3+2] = 1 - (totalGranu - granu_dscr[i*3+2]); totalGranu = 1; break; } } if (totalGranu < 1) granu_dscr[(idx-1)*3+2] += 1.0 - totalGranu; *size_gr = idx*3; } void Scheduler::pushH2DTroughputPoint(unsigned device, unsigned nbBytes, double time) { H2DThroughputSamplingPerDevice[device]. push_back(std::make_pair(nbBytes, time)); } void Scheduler::pushD2HTroughputPoint(unsigned device, unsigned nbBytes, double time) { D2HThroughputSamplingPerDevice[device]. push_back(std::make_pair(nbBytes, time)); } };
33.307138
92
0.663008
[ "vector" ]
26eab5c88eb5e2624ff01a1f08a4dc522f885214
790
cpp
C++
convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
2
2021-08-29T12:51:09.000Z
2021-10-18T23:24:41.000Z
convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
null
null
null
convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.cpp
itzpankajpanwar/Leetcode
bf933bc8a16f4b9d7a0e8b82f01684e60b544bed
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* solver(vector<int>& nums,int s,int e) { if(s>e) return nullptr; int d=(e-s)/2; TreeNode* root = new TreeNode(nums[s+d]); root->left = solver(nums,s,s+d-1); root->right = solver(nums,s+d+1,e); return root; } TreeNode* sortedArrayToBST(vector<int>& nums) { int n=nums.size(); return solver(nums,0,n-1); } };
27.241379
93
0.551899
[ "vector" ]
26eb2b297e1920a1be16c88060d04c860364ec61
1,149
cpp
C++
libs/source/Clock.cpp
chriskarlsson/1dv534
0980613941079b22dedc64326ea455575d42147b
[ "MIT" ]
null
null
null
libs/source/Clock.cpp
chriskarlsson/1dv534
0980613941079b22dedc64326ea455575d42147b
[ "MIT" ]
null
null
null
libs/source/Clock.cpp
chriskarlsson/1dv534
0980613941079b22dedc64326ea455575d42147b
[ "MIT" ]
1
2022-01-07T21:33:14.000Z
2022-01-07T21:33:14.000Z
/**********************************************************************/ // File: Clock.cpp // Summary: This class represents a clock, that can be used to // read the correct time. The clock gets its time from // your computer's system clock, and returns it in the // form of a MyTime-object. // Version: Version 1.2 - 2013-03-17 // Owner: Christer Lundberg // ------------------------------------------- // Log: 1998-06-23 Created the file. Christer // 2003-08-11 Uppdate Version 1.1 by Christer. The class was // suited to the newer naming standard for header files. // (Previously named time.h is now ctime.) // 2013-03-17 Uppdate Version 1.2 by Anne. Converted to English and VS 2012 // 2015-03-05 Revised by Anne. Converted to VS 2013 /**********************************************************************/ #include <ctime> #include <MyTime.h> #include <Clock.h> MyTime Clock::give_me_the_time() { time_t t = time(0); struct tm *p = localtime(&t); return MyTime(p->tm_hour, p->tm_min, p->tm_sec); } Clock::operator MyTime() { return give_me_the_time(); }
31.054054
79
0.543081
[ "object" ]
26fd4a5ab7d7fcd6c11377367f0e353c9d0d2837
15,244
cpp
C++
src/core/pybing.cpp
yangfly/mtcnn
bff22f5f417424aa45339510eb1b27f31c3eefe0
[ "MIT" ]
5
2018-06-07T02:46:18.000Z
2020-02-18T19:48:40.000Z
src/core/pybing.cpp
qaz734913414/mtcnn-3
bff22f5f417424aa45339510eb1b27f31c3eefe0
[ "MIT" ]
null
null
null
src/core/pybing.cpp
qaz734913414/mtcnn-3
bff22f5f417424aa45339510eb1b27f31c3eefe0
[ "MIT" ]
1
2019-05-26T13:10:04.000Z
2019-05-26T13:10:04.000Z
#include <Python.h> #include <sstream> // Produce deprecation warnings (needs to come before arrayobject.h inclusion). #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <boost/python.hpp> #include <numpy/ndarrayobject.h> #include "mtcnn.h" #if CV_VERSION_MAJOR == 3 namespace py = boost::python; //=================== MACROS ================================================================= static PyObject* opencv_error = 0; #define ERRWRAP2(expr) \ try \ { \ PyAllowThreads allowThreads; \ expr; \ } \ catch (const cv::Exception &e) \ { \ PyErr_SetString(opencv_error, e.what()); \ return 0; \ } //=================== ERROR HANDLING ========================================================= static int failmsg(const char *fmt, ...) { char str[1000]; va_list ap; va_start(ap, fmt); vsnprintf(str, sizeof(str), fmt, ap); va_end(ap); throw std::runtime_error(str); return 0; } //=================== THREADING ============================================================== class PyAllowThreads { public: PyAllowThreads() : _state(PyEval_SaveThread()) { } ~PyAllowThreads() { PyEval_RestoreThread(_state); } private: PyThreadState* _state; }; class PyEnsureGIL { public: PyEnsureGIL() : _state(PyGILState_Ensure()) { } ~PyEnsureGIL() { PyGILState_Release(_state); } private: PyGILState_STATE _state; }; enum { ARG_NONE = 0, ARG_MAT = 1, ARG_SCALAR = 2 }; static size_t REFCOUNT_OFFSET = (size_t)&(((PyObject*)0)->ob_refcnt) + (0x12345678 != *(const size_t*)"\x78\x56\x34\x12\0\0\0\0\0")*sizeof(int); static inline PyObject* pyObjectFromRefcount(const int* refcount) { return (PyObject*)((size_t)refcount - REFCOUNT_OFFSET); } static inline int* refcountFromPyObject(const PyObject* obj) { return (int*)((size_t)obj + REFCOUNT_OFFSET); } //=================== NUMPY ALLOCATOR FOR OPENCV ============================================= class NumpyAllocator: public cv::MatAllocator { public: NumpyAllocator() { stdAllocator = cv::Mat::getStdAllocator(); } ~NumpyAllocator() { } cv::UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const { cv::UMatData* u = new cv::UMatData(this); u->data = u->origdata = (uchar*) PyArray_DATA((PyArrayObject*) o); npy_intp* _strides = PyArray_STRIDES((PyArrayObject*) o); for (int i = 0; i < dims - 1; i++) step[i] = (size_t) _strides[i]; step[dims - 1] = CV_ELEM_SIZE(type); u->size = sizes[0] * step[0]; u->userdata = o; return u; } cv::UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, cv::UMatUsageFlags usageFlags) const { if (data != 0) { CV_Error(cv::Error::StsAssert, "The data should normally be NULL!"); // probably this is safe to do in such extreme case return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags); } PyEnsureGIL gil; int depth = CV_MAT_DEPTH(type); int cn = CV_MAT_CN(type); const int f = (int) (sizeof(size_t) / 8); int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE : depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT : depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT : depth == CV_64F ? NPY_DOUBLE : f * NPY_ULONGLONG + (f ^ 1) * NPY_UINT; int i, dims = dims0; cv::AutoBuffer<npy_intp> _sizes(dims + 1); for (i = 0; i < dims; i++) _sizes[i] = sizes[i]; if (cn > 1) _sizes[dims++] = cn; PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum); if (!o) CV_Error_(cv::Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims)); return allocate(o, dims0, sizes, type, step); } bool allocate(cv::UMatData* u, int accessFlags, cv::UMatUsageFlags usageFlags) const { return stdAllocator->allocate(u, accessFlags, usageFlags); } void deallocate(cv::UMatData* u) const { if (u) { PyEnsureGIL gil; PyObject* o = (PyObject*) u->userdata; Py_XDECREF(o); delete u; } } const MatAllocator* stdAllocator; }; //=================== ALLOCATOR INITIALIZTION ================================================== NumpyAllocator g_numpyAllocator; //=================== STANDALONE CONVERTER FUNCTIONS ========================================= PyObject* fromMatToNDArray(const cv::Mat& m) { if (!m.data) Py_RETURN_NONE; cv::Mat temp, *p = (cv::Mat*) &m; if (!p->u || p->allocator != &g_numpyAllocator) { temp.allocator = &g_numpyAllocator; ERRWRAP2(m.copyTo(temp)); p = &temp; } PyObject* o = (PyObject*) p->u->userdata; Py_INCREF(o); return o; } cv::Mat fromNDArrayToMat(PyObject* o) { cv::Mat m; bool allowND = true; if (!PyArray_Check(o)) { std::runtime_error("argument is not a numpy array"); if (!m.data) m.allocator = &g_numpyAllocator; } else { PyArrayObject* oarr = (PyArrayObject*) o; bool needcopy = false, needcast = false; int typenum = PyArray_TYPE(oarr), new_typenum = typenum; int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S : typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S : typenum == NPY_INT ? CV_32S : typenum == NPY_INT32 ? CV_32S : typenum == NPY_FLOAT ? CV_32F : typenum == NPY_DOUBLE ? CV_64F : -1; if (type < 0) { if (typenum == NPY_INT64 || typenum == NPY_UINT64 || type == NPY_LONG) { needcopy = needcast = true; new_typenum = NPY_INT; type = CV_32S; } else { std::runtime_error("Argument data type is not supported"); m.allocator = &g_numpyAllocator; return m; } } #ifndef CV_MAX_DIM const int CV_MAX_DIM = 32; #endif int ndims = PyArray_NDIM(oarr); if (ndims >= CV_MAX_DIM) { std::runtime_error("Dimensionality of argument is too high"); if (!m.data) m.allocator = &g_numpyAllocator; return m; } int size[CV_MAX_DIM + 1]; size_t step[CV_MAX_DIM + 1]; size_t elemsize = CV_ELEM_SIZE1(type); const npy_intp* _sizes = PyArray_DIMS(oarr); const npy_intp* _strides = PyArray_STRIDES(oarr); bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX; for (int i = ndims - 1; i >= 0 && !needcopy; i--) { // these checks handle cases of // a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases // b) transposed arrays, where _strides[] elements go in non-descending order // c) flipped arrays, where some of _strides[] elements are negative if ((i == ndims - 1 && (size_t) _strides[i] != elemsize) || (i < ndims - 1 && _strides[i] < _strides[i + 1])) needcopy = true; } if (ismultichannel && _strides[1] != (npy_intp) elemsize * _sizes[2]) needcopy = true; if (needcopy) { if (needcast) { o = PyArray_Cast(oarr, new_typenum); oarr = (PyArrayObject*) o; } else { oarr = PyArray_GETCONTIGUOUS(oarr); o = (PyObject*) oarr; } _strides = PyArray_STRIDES(oarr); } for (int i = 0; i < ndims; i++) { size[i] = (int) _sizes[i]; step[i] = (size_t) _strides[i]; } // handle degenerate case if (ndims == 0) { size[ndims] = 1; step[ndims] = elemsize; ndims++; } if (ismultichannel) { ndims--; type |= CV_MAKETYPE(0, size[2]); } if (ndims > 2 && !allowND) { std::runtime_error("%s has more than 2 dimensions"); } else { m = cv::Mat(ndims, size, type, PyArray_DATA(oarr), step); m.u = g_numpyAllocator.allocate(o, ndims, size, type, step); m.addref(); if (!needcopy) { Py_INCREF(o); } } m.allocator = &g_numpyAllocator; } return m; } void showInfo(const cv::Mat image) { int b = image.at<cv::Vec3b>(50,50)[0]; int g = image.at<cv::Vec3b>(50,50)[1]; int r = image.at<cv::Vec3b>(50,50)[2]; std::cout << "pixel at <50,50>: " << b << " " << g << " " << r << std::endl; std::cout << "image shape: " << image.rows << " " << image.cols << std::endl; } //=================== MTCNN WRAPPER FOR PYTHON BINGING ============================================= using namespace std; using namespace cv; using namespace face; using namespace caffe; class MTcnn : private Mtcnn { public: MTcnn(const string model_dir, bool preciseLandmark) : Mtcnn(model_dir, preciseLandmark) {} void setFactor(const float factor) { if (factor <= 0 || factor >= 1) failmsg("Invalid factor to set: %f.", factor); else this->scale_factor = factor; } double getFactor() const { return this->scale_factor; } void setMinSize(const int minSize) { if (minSize <= 0) failmsg("Invalid minSize to set: %d.", minSize); else this->face_min_size = minSize; } int getMinSize() const { return this->face_min_size; } void setMaxSize(const int maxSize) { if (maxSize <= 0) failmsg("Invalid maxSize to set: %d.", maxSize); else this->face_max_size = maxSize; } int getMaxSize() const { return this->face_max_size; } void setPreciseLandmark(const bool preciseLandmark) { // empty pass // this->enable_precise_landmark = this->enable_precise_landmark && preciseLandmark; } int getPreciseLandmark() const { return this->enable_precise_landmark; } void setThresholds(const py::list& thresholds) { if (len(thresholds) != 3) failmsg("Invalid thresholds to set: len = %d.", len(thresholds)); else { for (int i = 0; i < 3; ++i) this->thresholds[i] = py::extract<float>(thresholds[i]); } } py::list getThresholds() const { py::list thres; for (int i = 0; i < 3; ++i) thres.append(this->thresholds[i]); return thres; } py::list detect(PyObject* np, bool preciseLandmark) { cv::Mat img = fromNDArrayToMat(np); vector<FaceInfo> infos = Detect(img, preciseLandmark); py::list pyinfos; for (const auto & info : infos) { pyinfos.append(info.score); // score pyinfos.append(info.bbox.x1); // x1 pyinfos.append(info.bbox.y1); // y1 pyinfos.append(info.bbox.x2); // x2 pyinfos.append(info.bbox.y2); // y2 // l&r eye, nose, l&r mouth for (const auto & pt : info.fpts) { pyinfos.append(pt.x); // x pyinfos.append(pt.y); // y } } return pyinfos; } py::list detect_again(PyObject* np, const py::list& py_bbox, bool preciseLandmark) { cv::Mat img = fromNDArrayToMat(np); //! Todo Debug why? // Wrok wll BBox bbox = BBox(py::extract<float>(py_bbox[0]), py::extract<float>(py_bbox[1]), py::extract<float>(py_bbox[2]), py::extract<float>(py_bbox[3])); // Report Error /* BBox bbox(py::extract<float>(py_bbox[0]), */ /* py::extract<float>(py_bbox[1]), */ /* py::extract<float>(py_bbox[2]), */ /* py::extract<float>(py_bbox[3])); */ vector<FaceInfo> infos = DetectAgain(img, bbox, preciseLandmark); py::list pyinfos; for (const auto & info : infos) { pyinfos.append(info.score); // score pyinfos.append(info.bbox.x1); // x1 pyinfos.append(info.bbox.y1); // y1 pyinfos.append(info.bbox.x2); // x2 pyinfos.append(info.bbox.y2); // y2 // l&r eye, nose, l&r mouth for (const auto & pt : info.fpts) { pyinfos.append(pt.x); // x pyinfos.append(pt.y); // y } } return pyinfos; } PyObject* align(PyObject* np, const py::list& py_fpts, int width=112) { Mat img = fromNDArrayToMat(np); FPoints fpts; fpts.reserve(5); fpts.emplace_back(py::extract<float>(py_fpts[0]), py::extract<float>(py_fpts[1])); fpts.emplace_back(py::extract<float>(py_fpts[2]), py::extract<float>(py_fpts[3])); fpts.emplace_back(py::extract<float>(py_fpts[4]), py::extract<float>(py_fpts[5])); fpts.emplace_back(py::extract<float>(py_fpts[6]), py::extract<float>(py_fpts[7])); fpts.emplace_back(py::extract<float>(py_fpts[8]), py::extract<float>(py_fpts[9])); Mat face = Align(img, fpts, width); PyObject* py_face = fromMatToNDArray(face); return py_face; } PyObject* draw_infos(PyObject* np, const py::list& py_infos) { Mat img = fromNDArrayToMat(np); int num = py::len(py_infos); std::vector<FaceInfo> infos; for (int i = 0; i < num; i += 15) { float score = py::extract<float>(py_infos[i]); BBox bbox(py::extract<float>(py_infos[i+1]), py::extract<float>(py_infos[i+2]), py::extract<float>(py_infos[i+3]), py::extract<float>(py_infos[i+4])); FPoints fpts; fpts.reserve(5); fpts.emplace_back(py::extract<float>(py_infos[i+5]), py::extract<float>(py_infos[i+6])); fpts.emplace_back(py::extract<float>(py_infos[i+7]), py::extract<float>(py_infos[i+8])); fpts.emplace_back(py::extract<float>(py_infos[i+9]), py::extract<float>(py_infos[i+10])); fpts.emplace_back(py::extract<float>(py_infos[i+11]), py::extract<float>(py_infos[i+12])); fpts.emplace_back(py::extract<float>(py_infos[i+13]), py::extract<float>(py_infos[i+14])); infos.emplace_back(move(bbox), score, move(fpts)); } Mat canvas = DrawInfos(img, infos); PyObject* py_canvas = fromMatToNDArray(canvas); return py_canvas; } }; //================== Useful Setting Functions //======================================================= // Selecting mode. void InitLog(int level) { FLAGS_logtostderr = 1; FLAGS_minloglevel = level; ::google::InitGoogleLogging(""); ::google::InstallFailureSignalHandler(); } void InitLogInfo() { InitLog(google::INFO); } void Log(const string& s) { LOG(INFO) << s; } //=================== Expose Python Module ============================================= #if (PY_VERSION_HEX >= 0x03000000) static void *init_ar() { #else static void init_ar(){ #endif Py_Initialize(); import_array(); return NUMPY_IMPORT_ARRAY_RETVAL; } BOOST_PYTHON_MODULE(_mtcnn) { init_ar(); py::def("init_log", &InitLog); py::def("init_log", &InitLogInfo); py::def("log", &Log); py::def("close_log", &::google::ShutdownGoogleLogging); py::def("set_device", &Caffe::SetDevice); py::class_<MTcnn>("MTcnn", py::init<std::string, bool>()) .add_property("factor", &MTcnn::getFactor, &MTcnn::setFactor) .add_property("minSize", &MTcnn::getMinSize, &MTcnn::setMinSize) .add_property("maxSize", &MTcnn::getMaxSize, &MTcnn::setMaxSize) .add_property("thresholds", &MTcnn::getThresholds, &MTcnn::setThresholds) .add_property("preciseLandmark", &MTcnn::getPreciseLandmark, &MTcnn::setPreciseLandmark) .def("detect", &MTcnn::detect) .def("detect_again", &MTcnn::detect_again) .def("align", &MTcnn::align) .def("draw_infos", &MTcnn::draw_infos); } #endif
30.067061
106
0.584033
[ "shape", "vector" ]
26fee802536af9079d505d5a8b770f6c01db246b
972
cpp
C++
uva.onlinejudge.org/AllinAll.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
6
2016-09-10T03:16:34.000Z
2020-04-07T14:45:32.000Z
uva.onlinejudge.org/AllinAll.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
null
null
null
uva.onlinejudge.org/AllinAll.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
2
2018-08-11T20:55:35.000Z
2020-01-15T23:23:11.000Z
/* By: facug91 From: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1281 Name: All in All Date: 06/04/2015 */ #include <bits/stdc++.h> #define EPS 1e-9 #define DEBUG(x) cerr << "#" << (#x) << ": " << (x) << endl const double PI = 2.0*acos(0.0); #define INF 1000000000 //#define MOD 1000000 //#define MAXN 1000005 using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<ii> vii; string s, t; int main () { ios_base::sync_with_stdio(0); cin.tie(0); //cout<<fixed<<setprecision(10); cerr<<fixed<<setprecision(10); int i, j; while (cin>>s>>t) { i = j = 0; while (i<s.length() && j < t.length()) { while (j<t.length() && s[i] != t[j]) j++; if (s[i] == t[j]) i++; j++; } if (i == s.length()) cout<<"Yes\n"; else cout<<"No\n"; } return 0; }
23.142857
114
0.5607
[ "vector" ]
f800c2bf9e66b9c87f8f530bc808496f18e4a93b
8,186
cpp
C++
steerlib/src/CommandLineParser.cpp
x-y-z/SteerSuite-CUDA
7b76c4e2cd2ddf216f4befa80ea9c91c71678719
[ "BSD-3-Clause" ]
1
2019-08-29T09:30:27.000Z
2019-08-29T09:30:27.000Z
steerlib/src/CommandLineParser.cpp
x-y-z/SteerSuite-CUDA
7b76c4e2cd2ddf216f4befa80ea9c91c71678719
[ "BSD-3-Clause" ]
null
null
null
steerlib/src/CommandLineParser.cpp
x-y-z/SteerSuite-CUDA
7b76c4e2cd2ddf216f4befa80ea9c91c71678719
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2009-2010 Shawn Singh, Mubbasir Kapadia, Petros Faloutsos, Glenn Reinman // See license.txt for complete license. // /// @file CommandLineParser.cpp /// @brief Implements the Util::CommandLineParser class #include <assert.h> #include <string.h> #include <stdlib.h> #include "util/CommandLineParser.h" #include "util/GenericException.h" using namespace Util; // // constructor // CommandLineParser::CommandLineParser() { _nonOptionArgs.clear(); _options.clear(); } void CommandLineParser::addOption(const std::string & option, void * target, CommandLineOptionTypeEnum optionDataType, unsigned int numArgs, bool * flagTarget, bool flagIfOptionSpecified) { CommandLineParser::OptionInfo op; op.dataType = optionDataType; op.target = target; op.numArgs = numArgs; op.flagTarget = flagTarget; op.flagIfOptionSpecified = flagIfOptionSpecified; _options[option] = op; } // // parse(): the real guts of the CommandLineParser is here. // void CommandLineParser::parse( int argc, char** argv, bool skipFirstArg, std::vector<char*> &leftoverArgs ) { // // some declarations and initialization // CommandLineParser::OptionInfo optionToParse; std::map<std::string, CommandLineParser::OptionInfo>::iterator op; int i = 0; if (skipFirstArg) i = 1; leftoverArgs.clear(); // iterate over every option; internally this loop will increment 'i' as needed up to the next option. while (i < argc) { op = _options.find(argv[i]); if (op == _options.end()) { // // in this case, we did not find the option, so add it to the leftoverArgs (and check for errors later). // leftoverArgs.push_back(argv[i]); } else { // // in this case, we did find the option, so parse it. // optionToParse = (*op).second; char * indicator; switch (optionToParse.dataType) { case OPTION_DATA_TYPE_SIGNED_INT: for (unsigned int n=0; n<optionToParse.numArgs; n++) { i++; // make sure another arg exists if (i >= argc) { throw GenericException("expected a value for the " + (*op).first + " option."); } // convert it with error checking into a signed integer int integerValue = strtol(argv[i],&indicator,0); if ((indicator==argv[i]) || (indicator != argv[i] + strlen(argv[i]))) { // TODO: this still doesnt reliably detect extremely large integer values as an error. throw GenericException("value for the " + (*op).first + " option is not a valid integer."); } // then initialize the target with this value. if (optionToParse.target != NULL) ((int*)(optionToParse.target))[n] = integerValue; } if (optionToParse.flagTarget != NULL) *(optionToParse.flagTarget) = optionToParse.flagIfOptionSpecified; break; case OPTION_DATA_TYPE_UNSIGNED_INT: for (unsigned int n=0; n<optionToParse.numArgs; n++) { i++; // make sure another arg exists if (i >= argc) { throw GenericException("expected a value for the " + (*op).first + " option."); } // convert it with error checking into a signed integer unsigned int unsignedValue = strtoul(argv[i],&indicator,0); if ((indicator==argv[i]) || (indicator != argv[i] + strlen(argv[i]))) { // TODO: this still doesnt reliably detect extremely large integer values as an error. throw GenericException("ERROR: value for the " + (*op).first + " option is not a valid unsigned integer."); } if (argv[i][0] == '-') { // if conversion was successful, but the arg was originally negative, don't allow it throw GenericException("ERROR: value for the " + (*op).first + " option cannot be negative."); } // then initialize the target with this value. if (optionToParse.target != NULL) ((unsigned int*)(optionToParse.target))[n] = unsignedValue; } if (optionToParse.flagTarget != NULL) *(optionToParse.flagTarget) = optionToParse.flagIfOptionSpecified; break; case OPTION_DATA_TYPE_FLOAT: for (unsigned int n=0; n<optionToParse.numArgs; n++) { i++; // make sure another arg exists if (i >= argc) { throw GenericException("expected a value for the " + (*op).first + " option."); } // convert it with error checking into a signed integer double floatValue = strtod(argv[i],&indicator); // will be cast to a float if ((indicator==argv[i]) || (indicator != argv[i] + strlen(argv[i]))) { // TODO: this still doesnt reliably detect extremely large integer values as an error. throw GenericException("ERROR: value for the " + (*op).first + " option is not a valid floating-point number."); } // then initialize the target with this value. if (optionToParse.target != NULL) ((float*)(optionToParse.target))[n] = (float)floatValue; } if (optionToParse.flagTarget != NULL) *(optionToParse.flagTarget) = optionToParse.flagIfOptionSpecified; break; case OPTION_DATA_TYPE_DOUBLE: for (unsigned int n=0; n<optionToParse.numArgs; n++) { i++; // make sure another arg exists if (i >= argc) { throw GenericException("expected a value for the " + (*op).first + " option."); } // convert it with error checking into a signed integer double doubleValue = strtod(argv[i],&indicator); // will be cast to a float if ((indicator==argv[i]) || (indicator != argv[i] + strlen(argv[i]))) { // TODO: this still doesnt reliably detect extremely large integer values as an error. throw GenericException("ERROR: value for the " + (*op).first + " option is not a valid double-precision floating-point number."); } // then initialize the target with this value. if (optionToParse.target != NULL) ((double*)(optionToParse.target))[n] = doubleValue; } if (optionToParse.flagTarget != NULL) *(optionToParse.flagTarget) = optionToParse.flagIfOptionSpecified; break; case OPTION_DATA_TYPE_STRING: for (unsigned int n=0; n<optionToParse.numArgs; n++) { i++; // make sure another arg exists if (i >= argc) { throw GenericException("expected a value for the " + (*op).first + " option."); } // then initialize the target with this value. if (optionToParse.target != NULL) ((std::string*)(optionToParse.target))[n] = std::string(argv[i]); } if (optionToParse.flagTarget != NULL) *(optionToParse.flagTarget) = optionToParse.flagIfOptionSpecified; break; case OPTION_DATA_TYPE_MULTI_INSTANCE_STRING: if (optionToParse.numArgs != 1) { throw GenericException("multi-instance options with multiple args are not supported by this version of CommandLineParser."); } // even though numArgs is constrained to 1, just keeping the for-loop for uniformity and convenience anyway, // to minimize chances of creating bugs when changing this code later. for (unsigned int n=0; n<optionToParse.numArgs; n++) { i++; // make sure another arg exists if (i >= argc) { throw GenericException("expected a value for the " + (*op).first + " option."); } // then initialize the target with this value. if (optionToParse.target != NULL) (*((std::vector<std::string>*)(optionToParse.target))).push_back(std::string(argv[i])); } if (optionToParse.flagTarget != NULL) *(optionToParse.flagTarget) = optionToParse.flagIfOptionSpecified; break; case OPTION_DATA_TYPE_NO_DATA: if (optionToParse.flagTarget != NULL) *(optionToParse.flagTarget) = optionToParse.flagIfOptionSpecified; break; default: std::cerr << "CommandLineParser::parse(): Never expected to reach here. There is probably a simple control-flow bug.\n"; assert(false); break; } } i++; } } void CommandLineParser::parse( int argc, char** argv, bool skipFirstArg, bool throwExceptionIfUnrecognizedArgs) { std::vector<char*> ignoredLeftoverArgs; parse(argc, argv, skipFirstArg, ignoredLeftoverArgs); if (throwExceptionIfUnrecognizedArgs && (ignoredLeftoverArgs.size() > 0)) { throw GenericException("Unrecognized option: " + std::string(ignoredLeftoverArgs[0])); } }
40.127451
136
0.667115
[ "vector" ]
f80799329a9da38e33c7e7ae450607dbbacb86e9
798
cpp
C++
source/tvision/scheckbo.cpp
gpaulsen/tvision
638f963fe4f6c84854f60f1e9c5772bf6603e4b2
[ "MIT" ]
1,202
2020-05-10T18:43:45.000Z
2022-03-31T18:23:27.000Z
source/tvision/scheckbo.cpp
skywind3000/tvision
7ab5f195c572de0d496e92f4e3f7b3b0771ac699
[ "MIT" ]
54
2020-05-10T17:36:55.000Z
2022-03-15T12:22:07.000Z
source/tvision/scheckbo.cpp
skywind3000/tvision
7ab5f195c572de0d496e92f4e3f7b3b0771ac699
[ "MIT" ]
90
2020-06-28T13:51:47.000Z
2022-03-26T21:00:17.000Z
/*------------------------------------------------------------*/ /* filename - scheckbo.cpp */ /* */ /* Registeration object for the class TCheckBoxes */ /*------------------------------------------------------------*/ /* * Turbo Vision - Version 2.0 * * Copyright (c) 1994 by Borland International * All Rights Reserved. * */ #if !defined(NO_STREAMABLE) #define Uses_TCheckBoxes #define Uses_TStreamableClass #include <tvision/tv.h> __link( RCluster ) TStreamableClass RCheckBoxes( TCheckBoxes::name, TCheckBoxes::build, __DELTA(TCheckBoxes) ); #endif
29.555556
65
0.39599
[ "object" ]
f80a9fdd05ed468c018e2b0950a12d0926f5a415
4,333
cpp
C++
caffe/src/caffe/test/test_st_layer_hard.cpp
shaoxiaohu/Face-Alignment-with-Two-Stage-Re-initialization-
ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b
[ "MIT" ]
92
2017-07-19T05:12:05.000Z
2021-11-09T07:59:07.000Z
caffe/src/caffe/test/test_st_layer_hard.cpp
mornydew/Face_Alignment_Two_Stage_Re-initialization
ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b
[ "MIT" ]
11
2017-10-18T05:11:20.000Z
2020-04-03T21:28:20.000Z
caffe/src/caffe/test/test_st_layer_hard.cpp
mornydew/Face_Alignment_Two_Stage_Re-initialization
ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b
[ "MIT" ]
31
2017-07-20T11:37:39.000Z
2021-03-08T09:01:26.000Z
// #include <cstring> // #include <vector> // #include "gtest/gtest.h" // #include "caffe/blob.hpp" // #include "caffe/common.hpp" // #include "caffe/layers/st_layer.hpp" // #include "caffe/filler.hpp" // // #include "caffe/vision_layers.hpp" // #include "caffe/layers/concat_layer.hpp" // #include "caffe/layers/flatten_layer.hpp" // #include "caffe/layers/pooling_layer.hpp" // #include "caffe/layers/split_layer.hpp" // #include "caffe/layers/spp_layer.hpp" // #include "caffe/test/test_caffe_main.hpp" // #include "caffe/test/test_gradient_check_util.hpp" // #include "fstream" // namespace caffe { // #ifndef CPU_ONLY // extern cudaDeviceProp CAFFE_TEST_CUDA_PROP; // #endif // template <typename TypeParam> // class HardSpatialTransformerLayerTest : public MultiDeviceTest<TypeParam> { // typedef typename TypeParam::Dtype Dtype; // protected: // HardSpatialTransformerLayerTest() // : blob_U_(new Blob<Dtype>(2, 3, 10, 10)), // blob_theta_(new Blob<Dtype>(2, 2, 3, 1)), // blob_V_(new Blob<Dtype>(2, 3, 7, 7)) { // FillerParameter filler_param; // GaussianFiller<Dtype> filler(filler_param); // filler.Fill(this->blob_U_); // filler.Fill(this->blob_theta_); // vector<int> shape_theta(2); // shape_theta[0] = 2; shape_theta[1] = 6; // blob_theta_->Reshape(shape_theta); // blob_bottom_vec_.push_back(blob_U_); // blob_bottom_vec_.push_back(blob_theta_); // blob_top_vec_.push_back(blob_V_); // } // virtual ~HardSpatialTransformerLayerTest() { delete blob_V_; delete blob_theta_; delete blob_U_; } // Blob<Dtype>* blob_U_; // Blob<Dtype>* blob_theta_; // Blob<Dtype>* blob_V_; // vector<Blob<Dtype>*> blob_bottom_vec_; // vector<Blob<Dtype>*> blob_top_vec_; // }; // // TYPED_TEST_CASE(HardSpatialTransformerLayerTest, TestGPUAndDouble); // TYPED_TEST(HardSpatialTransformerLayerTest, TestGradient) { // typedef typename TypeParam::Dtype Dtype; // bool IS_VALID_CUDA = false; // #ifndef CPU_ONLY // IS_VALID_CUDA = CAFFE_TEST_CUDA_PROP.major >= 2; // #endif // if (Caffe::mode() == Caffe::CPU || // sizeof(Dtype) == 4 || IS_VALID_CUDA) { // // reshape theta to have full 6 dimension // vector<int> shape_theta(2); // shape_theta[0] = 2; shape_theta[1] = 6; // this->blob_theta_->Reshape(shape_theta); // // fill random variables for theta // FillerParameter filler_param; // GaussianFiller<Dtype> filler(filler_param); // filler.Fill(this->blob_theta_); // // set layer_param // LayerParameter layer_param; // SpatialTransformerParameter *st_param = layer_param.mutable_st_param(); // st_param->set_output_h(7); // st_param->set_output_w(7); // // begin to check // SpatialTransformerLayer<Dtype> layer(layer_param); // GradientChecker<Dtype> checker(1e-6, 1e-6); // checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, // this->blob_top_vec_); // } else { // LOG(ERROR) << "Skipping test due to old architecture."; // } // } // TYPED_TEST(HardSpatialTransformerLayerTest, TestGradientWithPreDefinedTheta) { // typedef typename TypeParam::Dtype Dtype; // bool IS_VALID_CUDA = false; // #ifndef CPU_ONLY // IS_VALID_CUDA = CAFFE_TEST_CUDA_PROP.major >= 2; // #endif // if (Caffe::mode() == Caffe::CPU || // sizeof(Dtype) == 4 || IS_VALID_CUDA) { // // reshape theta to have only 2 dimensions // vector<int> shape_theta(2); // shape_theta[0] = 2; shape_theta[1] = 2; // this->blob_theta_->Reshape(shape_theta); // // fill random variables for theta // FillerParameter filler_param; // GaussianFiller<Dtype> filler(filler_param); // filler.Fill(this->blob_theta_); // // set layer_param // LayerParameter layer_param; // SpatialTransformerParameter *st_param = layer_param.mutable_st_param(); // st_param->set_output_h(7); // st_param->set_output_w(7); // st_param->set_theta_1_1(0.5); // st_param->set_theta_1_2(0); // st_param->set_theta_2_1(0); // st_param->set_theta_2_2(0.5); // // begin to check // SpatialTransformerLayer<Dtype> layer(layer_param); // GradientChecker<Dtype> checker(1e-6, 1e-6); // checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, // this->blob_top_vec_); // } else { // LOG(ERROR) << "Skipping test due to old architecture."; // } // } // } // namespace caffe
31.398551
103
0.684283
[ "vector" ]
f80d08201c903b9e454960ee46dbd7d6144b56c5
4,537
hpp
C++
iceoryx_posh/include/iceoryx_posh/version/version_info.hpp
bishibashiB/iceoryx
a626ed05504b098da9bbc063f652f2ab463e9250
[ "Apache-2.0" ]
null
null
null
iceoryx_posh/include/iceoryx_posh/version/version_info.hpp
bishibashiB/iceoryx
a626ed05504b098da9bbc063f652f2ab463e9250
[ "Apache-2.0" ]
null
null
null
iceoryx_posh/include/iceoryx_posh/version/version_info.hpp
bishibashiB/iceoryx
a626ed05504b098da9bbc063f652f2ab463e9250
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IOX_POSH_VERSION_VERSION_INFO_HPP #define IOX_POSH_VERSION_VERSION_INFO_HPP #include "iceoryx_posh/version/compatibility_check_level.hpp" #include "iceoryx_utils/cxx/helplets.hpp" #include "iceoryx_utils/cxx/serialization.hpp" #include "iceoryx_utils/cxx/string.hpp" #include "iceoryx_versions.hpp" #include <cstdint> namespace iox { namespace version { /// @brief Is used to compare the RouDis and runtime's version information. class VersionInfo { public: static const uint64_t COMMIT_ID_STRING_SIZE = 12u; static const uint64_t BUILD_DATE_STRING_SIZE = 36u; static const uint64_t SERIALIZATION_STRING_SIZE = 100u; using BuildDateStringType = cxx::string<BUILD_DATE_STRING_SIZE>; using CommitIdStringType = cxx::string<COMMIT_ID_STRING_SIZE>; using SerializationStringType = cxx::string<SERIALIZATION_STRING_SIZE>; static_assert(COMMIT_ID_STRING_SIZE <= SERIALIZATION_STRING_SIZE, "CommitId needs to transfered completely."); static_assert(COMMIT_ID_STRING_SIZE <= BUILD_DATE_STRING_SIZE, "BuildDate needs to transfered completely."); static_assert(cxx::strlen2(ICEORYX_BUILDDATE) < BUILD_DATE_STRING_SIZE, "COMMIT_BUILD_DATE_STRING_SIZE needs to be bigger."); /// @brief Generates an VersionInfo initialized with the information given by the auto generated /// iceoryx_versions.hpp defines. /// @param{in] versionMajor The major version. /// @param{in] versionMinor The minor version. /// @param{in] versionPatch The patch version. /// @param{in] versionTweak The tweak/RC version. /// @param{in] buildDateString The date when the component was build as string with maximal 36 readable chars. /// @param{in] commitIdString The commit id is shortened internally to 12 readable chars. VersionInfo(const uint16_t versionMajor, const uint16_t versionMinor, const uint16_t versionPatch, const uint16_t versionTweak, const BuildDateStringType& buildDateString, const CommitIdStringType& commitIdString) noexcept; /// @brief Construction of the VersionInfo using serialized strings. /// @param[in] serial The serialization object from read from to initialize this object. VersionInfo(const cxx::Serialization& serial) noexcept; /// @brief Serialization of the VersionInfo. operator cxx::Serialization() const noexcept; /// @brief Checks if the to versions information are identical. /// @param[in] rhs The right side of the compare with equal. bool operator==(const VersionInfo& rhs) const noexcept; /// @brief Checks if the to versions information are not identical. /// @param[in] rhs The right side of the compare with unequal. bool operator!=(const VersionInfo& rhs) const noexcept; /// @brief Compares this version versus another with respect to the compatibility value give. /// @param[in] other The other version compared with this version. /// @param[in] compatibilityCheckLevel Gives the level how deep it should be compared. bool checkCompatibility(const VersionInfo& other, const CompatibilityCheckLevel compatibilityCheckLevel) const noexcept; /// @brief The serialization could fail, which cause an invalid object, else true. /// @return Returns if the object is valid. bool isValid() noexcept; /// @brief Creates a version object of the current iceoryx version. /// @return Returns the current version of iceoryx as an object. static VersionInfo getCurrentVersion() noexcept; protected: bool m_valid{true}; uint16_t m_versionMajor{0u}; uint16_t m_versionMinor{0u}; uint16_t m_versionPatch{0u}; uint16_t m_versionTweak{0u}; BuildDateStringType m_buildDateString; CommitIdStringType m_commitIdString; }; } // namespace version } // namespace iox #endif // IOX_POSH_VERSION_VERSION_INFO_HPP
44.480392
114
0.743002
[ "object" ]
f80e800165f13e27691de1ba6f5dcc41f50caf94
796
cpp
C++
.LHP/.Lop11/.HSG/.T.Van/QG01/GEMS/GEMS/GEMS.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop11/.HSG/.T.Van/QG01/GEMS/GEMS/GEMS.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop11/.HSG/.T.Van/QG01/GEMS/GEMS/GEMS.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <string> #include <vector> #define maxN 100001 #define maxAlp 27 #define num(x) ((x) - 'a') typedef long maxn; typedef int maxk, maxa; typedef long long maxr; typedef std::string str; maxn n; str s; maxr cnt[maxAlp], res; std::vector <maxa> ad[maxAlp]; void Prepare() { maxk K; std::cin >> n >> K >> s; while (K--) { char a, b; std::cin >> a >> b; ad[num(b)].push_back(num(a)); } } void Process() { for (maxn i = 0; i < n; i++) { for (maxk j = 0; j < ad[num(s[i])].size(); j++) res += cnt[ad[num(s[i])][j]]; ++cnt[num(s[i])]; } std::cout << res; } int main() { //freopen("gems.inp", "r", stdin); //freopen("gems.out", "w", stdout); std::ios_base::sync_with_stdio(0); std::cin.tie(0); Prepare(); Process(); }
15.307692
50
0.572864
[ "vector" ]
f80f103904873cc38b314e121c51d239955fcede
3,909
cpp
C++
tc 160+/StringInterspersal.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/StringInterspersal.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/StringInterspersal.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; bool sw(const string &a, const string &b) { if (a.size() < b.size()) { return false; } for (int i=0; i<(int)b.size(); ++i) { if (a[i] != b[i]) { return false; } } return true; } class StringInterspersal { public: string minimum(vector <string> W) { string sol; while (W.size() > 0) { sort(W.begin(), W.end()); int i = 1; while (i<(int)W.size() && sw(W[i], W[i-1])) { ++i; } --i; if (i != 0) { swap(W[0], W[i]); } sol += W[0][0]; if (W[0].size() == 1) { W.erase(W.begin(), W.begin()+1); } else { W[0] = W[0].substr(1); } } return sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"DESIGN","ALGORITHM","MARATHON"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "ADELGMAORARISIGNTHMTHON"; verify_case(0, Arg1, minimum(Arg0)); } void test_case_1() { string Arr0[] = {"TOMEK","PETR","ACRUSH","BURUNDUK","KRIJGERTJE"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "ABCKPERIJGERRTJETOMEKTRURUNDUKUSH"; verify_case(1, Arg1, minimum(Arg0)); } void test_case_2() { string Arr0[] = {"CCCA","CCCB","CCCD","CCCE"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "CCCACCCBCCCCCCDE"; verify_case(2, Arg1, minimum(Arg0)); } void test_case_3() { string Arr0[] = {"BKSDSOPTDD","DDODEVNKL","XX","PODEEE","LQQWRT"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "BDDKLODEPODEEEQQSDSOPTDDVNKLWRTXX"; verify_case(3, Arg1, minimum(Arg0)); } void test_case_4() { string Arr0[] = {"TOPCODER","BETFAIR","NSA","BT","LILLY"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "BBELILLNSATFAIRTOPCODERTY"; verify_case(4, Arg1, minimum(Arg0)); } void test_case_5() { string Arr0[] = {"QITHSQARQV","BYLHVGMLRY","LKMAQTJEAM","AQYICVNIKK","HKGZZFFEWC"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "ABHKGLKMAQIQQTHSQARQTJEAMVYICVNIKKYLHVGMLRYZZFFEWC"; verify_case(5, Arg1, minimum(Arg0)); } void test_case_6() { string Arr0[] = {"XHCYBTUQUW","EKBISADSSN","LOOISPOFAK","MIXBDHPJUQ","BNMNDHMOTC"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "BEKBILMINMNDHMOOIOSADSPOFAKSSNTCXBDHPJUQXHCYBTUQUW"; verify_case(6, Arg1, minimum(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { StringInterspersal ___test; ___test.run_test(-1); } // END CUT HERE
47.670732
365
0.568176
[ "vector" ]
f8128b354e334e8a03219f982020f3a04304821e
1,853
cpp
C++
src/test/ossim-tiff-info-test.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/test/ossim-tiff-info-test.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/test/ossim-tiff-info-test.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
1
2019-09-25T00:43:35.000Z
2019-09-25T00:43:35.000Z
//---------------------------------------------------------------------------- // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: David Burken // // Description: Test app for ossimTiffInfo class. // //---------------------------------------------------------------------------- // $Id: ossim-tiff-info-test.cpp 23664 2015-12-14 14:17:27Z dburken $ #include <iostream> using namespace std; #include <ossim/init/ossimInit.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/support_data/ossimTiffInfo.h> #include <ossim/support_data/ossimGeoTiff.h> int main(int argc, char *argv[]) { ossimInit::instance()->initialize(argc, argv); if (argc != 2) { cout << argv[0] << "<tiff_file>" << "\nPrint dump and geometry info for tiff_file." << endl; return 0; } cout << "ossimTiffInfo test:\n"; ossimTiffInfo* info = new ossimTiffInfo(); if ( info->open( ossimFilename(argv[1]) ) ) { cout << "ossimTiffInfo dump info:\n"; info->print(cout); ossimKeywordlist kwl; if ( info->getImageGeometry(kwl, 0) ) { cout << "ossimTiffInfo geometry info:\n" << kwl << endl; } else { cout << "ossimTiffInfo get image geometry failed..." << endl; } } else { cout << "Could not open: " << argv[1] << endl; } delete info; info = 0; cout << "ossimGeoTiff test:\n"; ossimGeoTiff* gtif = new ossimGeoTiff(); if ( gtif->readTags(argv[1], 0) ) { ossimKeywordlist kwl; if ( gtif->addImageGeometry(kwl, 0) ) { cout << "ossimGeoTiff geometry info:\n" << kwl << endl; } else { cout << "ossimGeoTiff get image geometry failed..." << endl; } } delete gtif; gtif = 0; return 0; }
22.059524
78
0.528872
[ "geometry" ]
f824527c0e9cfd649925be3733e591188f3d8e3a
16,133
cpp
C++
mnemonic.cpp
avislash/cpp-algorand-sdk
e7219a2cdfe25fb2e7f25649a17c677057ac3fbe
[ "MIT" ]
6
2021-07-06T08:34:48.000Z
2022-01-10T06:44:19.000Z
mnemonic.cpp
avislash/cpp-algorand-sdk
e7219a2cdfe25fb2e7f25649a17c677057ac3fbe
[ "MIT" ]
7
2021-04-17T19:32:05.000Z
2021-12-03T18:20:28.000Z
mnemonic.cpp
avislash/cpp-algorand-sdk
e7219a2cdfe25fb2e7f25649a17c677057ac3fbe
[ "MIT" ]
5
2021-01-29T08:23:27.000Z
2021-04-27T08:26:09.000Z
#include "mnemonic.h" #include <iostream> #include <string> #include <map> #include <sstream> #include <stdexcept> #include <cassert> #include <openssl/evp.h> #include "base.h" extern std::map<std::string, int> word_map; extern std::vector<std::string> word_vec; std::map<std::string, int> make_word_map(std::string s) { std::map<std::string, int> map; auto iss = std::istringstream{s}; std::string word; int i = 0; while (iss >> word) { map[word] = i; i++; } return map; } std::vector<std::string> make_word_vector(std::string s) { std::vector<std::string> vec; auto iss = std::istringstream{s}; std::string word; while (iss >> word) { vec.push_back(word); } return vec; } int word_lookup(std::string word) { auto entry = word_map.find(word); if (entry == word_map.end()) throw std::invalid_argument(word.c_str()); return entry->second; } uint16_t checksum(bytes b) { auto hash = sha512_256(b); auto ints = b2048_encode(bytes{hash.begin(), hash.begin()+2}); return ints[0]; } std::string mnemonic_from_seed(bytes seed) { std::string mnemonic; for (const int i : b2048_encode(seed)) { mnemonic.append(word_vec[i]+" "); } mnemonic.append(word_vec[checksum(seed)]); return mnemonic; } bytes seed_from_mnemonic(std::string mnemonic) { std::vector<std::string> words = make_word_vector(mnemonic); auto checkword = words.back(); words.pop_back(); if (words.size() != 24) throw std::invalid_argument(std::to_string(words.size()+1) + " words"); auto checkval = word_lookup(checkword); bytes seed; // this part is base conversion, 11 to 8. see base.cpp unsigned val = 0; int bits = 0; for (const auto& word : words) { val |= word_lookup(word) << bits; bits += 11; while (bits >= 8) { seed.push_back(val & 0xFF); val >>= 8; bits -= 8; } } if (bits > 0) seed.push_back(val & 0xFF); assert(!*(seed.end()-1)); // last byte is supposed to be zero seed.pop_back(); // and unneeded auto check = checksum(seed); if (check != checkval) { throw std::invalid_argument(word_vec[check] + " != " + word_vec[checkval]); } return seed; } // libsodium/nacl does not implement this truncated form of sha512, // which is NOT simply the first 256 bits of the sha512 hash. bytes sha512_256(bytes input) { unsigned char result[32]; EVP_MD_CTX *ctx = EVP_MD_CTX_new(); bool success = ctx != NULL && EVP_DigestInit_ex(ctx, EVP_sha512_256(), NULL) == 1 && EVP_DigestUpdate(ctx, input.data(), input.size()) == 1 && EVP_DigestFinal_ex(ctx, result, NULL) == 1; if (! success) throw std::runtime_error("openssl sha512_256 EVP_Digest runtime error"); EVP_MD_CTX_free(ctx); return bytes(result, result+sizeof(result)); } // This wordlist was taken from https://git.io/fhZUO const std::string english = R"( abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo )"; std::map<std::string, int> word_map = make_word_map(english); std::vector<std::string> word_vec = make_word_vector(english);
7.43799
89
0.808343
[ "mesh", "render", "object", "vector", "model", "solid" ]
f82812a860fd3df60a439b17056a4bf155399bca
16,313
cc
C++
cc/minigui_player.cc
efortuna/minigo
3104c098f1217796fe1469ac5dc9ed59c3d980c0
[ "Apache-2.0" ]
1
2020-02-28T13:08:16.000Z
2020-02-28T13:08:16.000Z
cc/minigui_player.cc
efortuna/minigo
3104c098f1217796fe1469ac5dc9ed59c3d980c0
[ "Apache-2.0" ]
null
null
null
cc/minigui_player.cc
efortuna/minigo
3104c098f1217796fe1469ac5dc9ed59c3d980c0
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "cc/minigui_player.h" #include <algorithm> #include <cctype> #include <cmath> #include <sstream> #include <utility> #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/str_replace.h" #include "absl/time/clock.h" #include "cc/constants.h" #include "cc/file/utils.h" #include "cc/logging.h" #include "cc/sgf.h" #include "nlohmann/json.hpp" namespace minigo { MiniguiPlayer::MiniguiPlayer(std::unique_ptr<DualNet> network, const Options& options) : GtpPlayer(std::move(network), options) { RegisterCmd("clear_board", &MiniguiPlayer::HandleClearBoard); RegisterCmd("echo", &MiniguiPlayer::HandleEcho); RegisterCmd("genmove", &MiniguiPlayer::HandleGenmove); RegisterCmd("info", &MiniguiPlayer::HandleInfo); RegisterCmd("loadsgf", &MiniguiPlayer::HandleLoadsgf); RegisterCmd("play", &MiniguiPlayer::HandlePlay); RegisterCmd("playsgf", &MiniguiPlayer::HandlePlaysgf); RegisterCmd("prune_nodes", &MiniguiPlayer::HandlePruneNodes); RegisterCmd("report_search_interval", &MiniguiPlayer::HandleReportSearchInterval); RegisterCmd("select_position", &MiniguiPlayer::HandleSelectPosition); RegisterCmd("variation", &MiniguiPlayer::HandleVariation); RegisterCmd("winrate_evals", &MiniguiPlayer::HandleWinrateEvals); } void MiniguiPlayer::NewGame() { node_to_info_.clear(); id_to_info_.clear(); to_eval_.clear(); MctsPlayer::NewGame(); RegisterNode(root()); } bool MiniguiPlayer::PlayMove(Coord c, Game* game) { if (!MctsPlayer::PlayMove(c, game)) { return false; } RefreshPendingWinRateEvals(); return true; } void MiniguiPlayer::Ponder() { // Decide whether to perform normal pondering or win rate evaluation. if (to_eval_.empty()) { // Nothing needs win rate evaluation. do_winrate_eval_reads_ = false; } else if (to_eval_[0]->num_eval_reads == 0) { // While there are still nodes in the win rate eval queue that haven't had // any reads, always perform win rate evaluation. do_winrate_eval_reads_ = true; } else { // While all nodes have been evaluated at least once, alternate between // performing win rate evaluation and normal pondering. do_winrate_eval_reads_ = !do_winrate_eval_reads_; } if (!do_winrate_eval_reads_) { GtpPlayer::Ponder(); return; } // Remember the number of reads at the root. int n = root()->N(); // First populate the batch with any nodes that require win rate evaluation. std::vector<TreePath> paths; for (int i = 0; i < options().virtual_losses; ++i) { if (to_eval_.empty()) { break; } SelectLeaves(to_eval_.front()->node, 1, &paths); to_eval_.pop_front(); } ProcessLeaves(absl::MakeSpan(paths), options().random_symmetry); // Send updated visit and Q data for all the nodes we performed win rate // evaluation on. This updates Minigui's win rate graph. for (const auto& path : paths) { auto* root = path.root; nlohmann::json j = { {"id", GetAuxInfo(root)->id}, {"n", root->N()}, {"q", root->Q()}, }; MG_LOG(INFO) << "mg-update:" << j.dump(); } // Increment the ponder count by difference new and old reads. ponder_read_count_ += root()->N() - n; // Increment the number of reads for all the nodes we performed win rate // evaluation on, pushing nodes that require more reads onto the back of the // queue. for (const auto& path : paths) { auto* info = GetAuxInfo(path.root); if (++info->num_eval_reads < num_eval_reads_) { to_eval_.push_back(info); } } } GtpPlayer::Response MiniguiPlayer::HandleCmd(const std::string& line) { auto response = GtpPlayer::HandleCmd(line); // Write __GTP_CMD_DONE__ to stderr to signify that handling a GTP command is // done. The Minigui Python server waits for this magic string before it // consumes the output of each GTP command. This keeps the outputs written to // stderr and stdout synchronized so that all data written to stderr while // processing a GTP command is consumed before the GTP result written to // stdout. MG_LOG(INFO) << "__GTP_CMD_DONE__"; return response; } void MiniguiPlayer::ProcessLeaves(absl::Span<TreePath> paths, bool random_symmetry) { MctsPlayer::ProcessLeaves(paths, random_symmetry); if (!paths.empty() && report_search_interval_ != absl::ZeroDuration()) { auto now = absl::Now(); if (now - last_report_time_ > report_search_interval_) { last_report_time_ = now; ReportSearchStatus(paths.back().root, paths.back().leaf); } } } GtpPlayer::Response MiniguiPlayer::HandleClearBoard(CmdArgs args) { auto response = GtpPlayer::HandleClearBoard(args); if (response.ok) { ReportPosition(root()); } return response; } GtpPlayer::Response MiniguiPlayer::HandleEcho(CmdArgs args) { return Response::Ok(absl::StrJoin(args, " ")); } GtpPlayer::Response MiniguiPlayer::HandleGenmove(CmdArgs args) { auto response = GtpPlayer::HandleGenmove(args); if (response.ok) { ReportPosition(root()); } return response; } GtpPlayer::Response MiniguiPlayer::HandleInfo(CmdArgs args) { auto response = CheckArgsExact(0, args); if (!response.ok) { return response; } std::ostringstream oss; oss << options(); oss << " report_search_interval:" << report_search_interval_; return Response::Ok(oss.str()); } GtpPlayer::Response MiniguiPlayer::HandleLoadsgf(CmdArgs args) { auto response = CheckArgsExact(1, args); if (!response.ok) { return response; } std::string contents; if (!file::ReadFile(std::string(args[0]), &contents)) { return Response::Error("cannot load file"); } std::vector<std::unique_ptr<sgf::Node>> trees; response = ParseSgf(contents, &trees); if (response.ok) { return response; } return ProcessSgf(trees); } GtpPlayer::Response MiniguiPlayer::HandlePlay(CmdArgs args) { auto response = GtpPlayer::HandlePlay(args); if (response.ok) { ReportPosition(root()); } return response; } GtpPlayer::Response MiniguiPlayer::HandlePlaysgf(CmdArgs args) { auto sgf_str = absl::StrReplaceAll(absl::StrJoin(args, " "), {{"\\n", "\n"}}); std::vector<std::unique_ptr<sgf::Node>> trees; auto response = ParseSgf(sgf_str, &trees); if (!response.ok) { return response; } return ProcessSgf(trees); } GtpPlayer::Response MiniguiPlayer::HandlePruneNodes(CmdArgs args) { auto response = CheckArgsExact(1, args); if (!response.ok) { return response; } int x; if (!absl::SimpleAtoi(args[0], &x)) { return Response::Error("couldn't parse ", args[0], " as an integer"); } mutable_options()->prune_orphaned_nodes = x != 0; return Response::Ok(); } GtpPlayer::Response MiniguiPlayer::HandleReportSearchInterval(CmdArgs args) { auto response = CheckArgsExact(1, args); if (!response.ok) { return response; } int x; if (!absl::SimpleAtoi(args[0], &x) || x < 0) { return Response::Error("couldn't parse ", args[0], " as an integer >= 0"); } report_search_interval_ = absl::Milliseconds(x); return Response::Ok(); } GtpPlayer::Response MiniguiPlayer::HandleSelectPosition(CmdArgs args) { auto response = CheckArgsExact(1, args); if (!response.ok) { return response; } if (args[0] == "root") { ResetRoot(); return Response::Ok(); } auto it = id_to_info_.find(args[0]); if (it == id_to_info_.end()) { return Response::Error("unknown position id"); } auto* node = it->second->node; // Build the sequence of moves the will end up at the requested position. std::vector<Coord> moves; while (node->parent != nullptr) { moves.push_back(node->move); node = node->parent; } std::reverse(moves.begin(), moves.end()); // Rewind to the start & play the sequence of moves. ResetRoot(); for (const auto& move : moves) { MG_CHECK(PlayMove(move, &game_)); } return Response::Ok(); } GtpPlayer::Response MiniguiPlayer::HandleVariation(CmdArgs args) { auto response = CheckArgsRange(0, 1, args); if (!response.ok) { return response; } if (args.size() == 0) { child_variation_ = Coord::kInvalid; } else { Coord c = Coord::FromGtp(args[0], true); if (c == Coord::kInvalid) { MG_LOG(ERROR) << "expected GTP coord for move, got " << args[0]; return Response::Error("illegal move"); } if (c != child_variation_) { child_variation_ = c; ReportSearchStatus(root(), nullptr); } } return Response::Ok(); } GtpPlayer::Response MiniguiPlayer::HandleWinrateEvals(CmdArgs args) { int num_reads; if (!absl::SimpleAtoi(args[1], &num_reads) || num_reads < 0) { return Response::Error("invalid num_reads"); } num_eval_reads_ = num_reads; RefreshPendingWinRateEvals(); return Response::Ok(); } GtpPlayer::Response MiniguiPlayer::ProcessSgf( const std::vector<std::unique_ptr<sgf::Node>>& trees) { // Clear the board before replaying sgf. NewGame(); // Traverse the SGF's game trees, loading them into the backend & running // inference on the positions in batches. std::function<Response(const sgf::Node&)> traverse = [&](const sgf::Node& node) { if (node.move.color != root()->position.to_play()) { // The move color is different than expected. Play a pass move to flip // the colors. if (root()->move == Coord::kPass) { auto expected = ColorToCode(root()->position.to_play()); auto actual = node.move.ToSgf(); MG_LOG(ERROR) << "expected move by " << expected << ", got " << actual << " but can't play an intermediate pass because the" << " previous move was also a pass"; return Response::Error("cannot load file"); } MG_LOG(WARNING) << "Inserting pass move"; MG_CHECK(PlayMove(Coord::kPass, &game_)); ReportPosition(root()); } if (!PlayMove(node.move.c, &game_)) { MG_LOG(ERROR) << "error playing " << node.move.ToSgf(); return Response::Error("cannot load file"); } if (!node.comment.empty()) { auto* info = GetAuxInfo(root()); info->comment = node.comment; } ReportPosition(root()); for (const auto& child : node.children) { auto response = traverse(*child); if (!response.ok) { return response; } } UndoMove(&game_); return Response::Ok(); }; for (const auto& tree : trees) { auto response = traverse(*tree); if (!response.ok) { return response; } } // Play the main line. ResetRoot(); if (!trees.empty()) { for (const auto& move : trees[0]->ExtractMainLine()) { // We already validated that all the moves could be played in traverse(), // so if PlayMove fails here, something has gone seriously awry. MG_CHECK(PlayMove(move.c, &game_)); } ReportPosition(root()); } return Response::Ok(); } void MiniguiPlayer::ReportSearchStatus(MctsNode* root, MctsNode* leaf) { nlohmann::json j = { {"id", GetAuxInfo(root)->id}, {"n", root->N()}, {"q", root->Q()}, }; // Pricipal variation. auto src_pv = root->MostVisitedPath(); if (!src_pv.empty()) { auto& dst_pv = j["variations"]["pv"]; for (Coord c : src_pv) { dst_pv.push_back(c.ToGtp()); } } // Current tree search variation. if (leaf != nullptr) { std::vector<const MctsNode*> src_search; for (const auto* node = leaf; node != root; node = node->parent) { src_search.push_back(node); } if (!src_search.empty()) { std::reverse(src_search.begin(), src_search.end()); auto& dst_search = j["variations"]["search"]; for (const auto* node : src_search) { dst_search.push_back(node->move.ToGtp()); } } } // Requested child variation, if any. if (child_variation_ != Coord::kInvalid) { auto& child_v = j["variations"][child_variation_.ToGtp()]; child_v.push_back(child_variation_.ToGtp()); auto it = root->children.find(child_variation_); if (it != root->children.end()) { for (Coord c : it->second->MostVisitedPath()) { child_v.push_back(c.ToGtp()); } } } // Child N. auto& childN = j["childN"]; for (const auto& edge : root->edges) { childN.push_back(static_cast<int>(edge.N)); } // Child Q. auto& childQ = j["childQ"]; for (int i = 0; i < kNumMoves; ++i) { childQ.push_back(static_cast<int>(std::round(root->child_Q(i) * 1000))); } MG_LOG(INFO) << "mg-update:" << j.dump(); } void MiniguiPlayer::ReportPosition(MctsNode* node) { const auto& position = node->position; std::ostringstream oss; for (const auto& stone : position.stones()) { char ch; if (stone.color() == Color::kBlack) { ch = 'X'; } else if (stone.color() == Color::kWhite) { ch = 'O'; } else { ch = '.'; } oss << ch; } auto* info = GetAuxInfo(node); nlohmann::json j = { {"id", info->id}, {"toPlay", position.to_play() == Color::kBlack ? "B" : "W"}, {"moveNum", position.n()}, {"stones", oss.str()}, {"gameOver", node->game_over()}, }; const auto& captures = node->position.num_captures(); if (captures[0] != 0 || captures[1] != 0) { j["caps"].push_back(captures[0]); j["caps"].push_back(captures[1]); } if (node->parent != nullptr) { j["parentId"] = GetAuxInfo(node->parent)->id; if (node->N() > 0) { // Only send Q if the node has been read at least once. j["q"] = node->Q(); } } if (node->move != Coord::kInvalid) { j["move"] = node->move.ToGtp(); } if (!info->comment.empty()) { j["comment"] = info->comment; } MG_LOG(INFO) << "mg-position: " << j.dump(); } MiniguiPlayer::AuxInfo* MiniguiPlayer::RegisterNode(MctsNode* node) { auto it = node_to_info_.find(node); if (it != node_to_info_.end()) { return it->second.get(); } auto* parent = node->parent != nullptr ? GetAuxInfo(node->parent) : nullptr; auto info = absl::make_unique<AuxInfo>(parent, node); auto raw_info = info.get(); id_to_info_.emplace(info->id, raw_info); node_to_info_.emplace(node, std::move(info)); return raw_info; } MiniguiPlayer::AuxInfo* MiniguiPlayer::GetAuxInfo(MctsNode* node) const { auto it = node_to_info_.find(node); MG_CHECK(it != node_to_info_.end()); return it->second.get(); } MiniguiPlayer::AuxInfo::AuxInfo(AuxInfo* parent, MctsNode* node) : parent(parent), node(node), id(absl::StrFormat("%p", node)) { if (parent != nullptr) { parent->children.push_back(this); } } void MiniguiPlayer::RefreshPendingWinRateEvals() { to_eval_.clear(); // Build a new list of nodes that require win rate evaluation. // First, traverse to the leaf node of the current position's main line. auto* info = RegisterNode(root()); while (!info->children.empty()) { info = info->children[0]; } // Walk back up the tree to the root, enqueing all nodes that have fewer than // the num_eval_reads_ win rate evaluations. while (info != nullptr) { if (info->num_eval_reads < num_eval_reads_) { to_eval_.push_back(info); } info = info->parent; } // Sort the nodes for eval by number of eval reads, breaking ties by the move // number. std::sort(to_eval_.begin(), to_eval_.end(), [](AuxInfo* a, AuxInfo* b) { if (a->num_eval_reads != b->num_eval_reads) { return a->num_eval_reads < b->num_eval_reads; } return a->node->position.n() < b->node->position.n(); }); } } // namespace minigo
29.66
80
0.643291
[ "vector" ]
f8286408d90e98dec13d194cbc27ed6b7a1ea120
32,410
cpp
C++
map/world.cpp
Andrettin/Metternich
513a7d3cddacad5d5efd2fa5faeed03bc55a190c
[ "MIT" ]
12
2019-08-03T05:58:12.000Z
2022-01-20T20:46:41.000Z
map/world.cpp
Andrettin/Metternich
513a7d3cddacad5d5efd2fa5faeed03bc55a190c
[ "MIT" ]
6
2019-08-03T11:46:49.000Z
2022-01-22T10:20:32.000Z
map/world.cpp
Andrettin/Metternich
513a7d3cddacad5d5efd2fa5faeed03bc55a190c
[ "MIT" ]
null
null
null
#include "map/world.h" #include "database/gsml_data.h" #include "economy/trade_node.h" #include "economy/trade_route.h" #include "game/engine_interface.h" #include "holding/holding.h" #include "holding/holding_slot.h" #include "landed_title/landed_title.h" #include "map/map.h" #include "map/pathfinder.h" #include "map/province.h" #include "map/star_system.h" #include "map/terrain_type.h" #include "map/world_type.h" #include "util/container_util.h" #include "util/geocoordinate_util.h" #include "util/image_util.h" #include "util/point_util.h" #include "util/random.h" #include "util/translator.h" #include "util/vector_util.h" namespace metternich { std::set<std::string> world::get_database_dependencies() { return { //so that baronies will be ensured to exist when worlds (and thus holding slots) are processed landed_title::class_identifier, }; } world::world(const std::string &identifier) : territory(identifier) { } world::~world() { } void world::initialize() { if (this->terrain_image.size() != this->province_image.size()) { throw std::runtime_error("The terrain image of world \"" + this->get_identifier() + "\" has a different size (" + std::to_string(this->terrain_image.width()) + "x" + std::to_string(this->terrain_image.height()) + ") than its province image (" + std::to_string(this->province_image.width()) + "x" + std::to_string(this->province_image.height()) + ")."); } //clear the terrain and province images, as there is no need to keep them in memory this->terrain_image = QImage(); this->province_image = QImage(); this->pathfinder = std::make_unique<metternich::pathfinder>(this->provinces); if (this->get_star_system() == nullptr) { const world *orbit_center = this->get_orbit_center(); while (orbit_center != nullptr) { if (orbit_center->get_star_system() != nullptr) { this->set_star_system(orbit_center->get_star_system()); break; } orbit_center = orbit_center->get_orbit_center(); } } if (this->get_orbit_center() != nullptr) { this->set_orbit_angle(random::generate_degree_angle()); } this->calculate_cosmic_size(); this->set_rotation(random::generate_degree_angle()); for (world *satellite : this->satellites) { if (!satellite->is_initialized()) { satellite->initialize(); } } const auto satellite_sort_func = [](const world *a, const world *b) { if (a->get_distance_from_orbit_center() == 0 || b->get_distance_from_orbit_center() == 0) { return a->get_distance_from_orbit_center() != 0; //place satellites without a predefined distance from orbit center last } return a->get_distance_from_orbit_center() < b->get_distance_from_orbit_center(); }; std::sort(this->satellites.begin(), this->satellites.end(), satellite_sort_func); //update the satellite distances from this world so that orbits are within a minimum and maximum distance of each other const world *previous_satellite = nullptr; for (world *satellite : this->satellites) { double base_distance = 0; if (previous_satellite != nullptr) { base_distance += previous_satellite->get_distance_from_orbit_center(); base_distance += previous_satellite->get_cosmic_size_with_satellites() / 2; } else { base_distance += this->get_cosmic_size() / 2; } base_distance += satellite->get_cosmic_size_with_satellites() / 2; const double min_distance = base_distance + world::min_orbit_distance; const double max_distance = base_distance + world::max_orbit_distance; double distance = sqrt(satellite->get_distance_from_orbit_center()) * 10; distance = std::max(distance, min_distance); distance = std::min(distance, max_distance); satellite->set_distance_from_orbit_center(distance); previous_satellite = satellite; } std::sort(this->satellites.begin(), this->satellites.end(), satellite_sort_func); connect(this, &world::owner_changed, this, &identifiable_data_entry_base::name_changed); //if the owner changes, whether the world uses its own tag list suffix or that of its system can change if (this->get_star_system() != nullptr) { connect(this->get_star_system(), &star_system::name_changed, this, &identifiable_data_entry_base::name_changed); //if the tag suffix list of the star system changes, the world's can, too } territory::initialize(); } void world::do_day() { if constexpr (world::revolution_enabled) { //move the world along its orbit if (this->get_orbit_center() != nullptr) { this->increment_orbit_angle(); } } //rotate the world on its axis if (!this->is_star()) { //stars don't need to rotate, as it makes no difference for them graphically this->rotate(); } territory::do_day(); } std::string world::get_name() const { std::vector<std::vector<std::string>> tag_list_with_fallbacks; if (this->get_owner() != nullptr) { tag_list_with_fallbacks = this->get_tag_suffix_list_with_fallbacks(); } else if (this->get_star_system() != nullptr) { tag_list_with_fallbacks = this->get_star_system()->get_tag_suffix_list_with_fallbacks(); } if (this->get_county() != nullptr) { return translator::get()->translate(this->get_county()->get_identifier_with_aliases(), tag_list_with_fallbacks); } return translator::get()->translate(this->get_identifier_with_aliases(), tag_list_with_fallbacks); //world without a cosmic landed title } void world::set_county(landed_title *county) { if (county == this->get_county()) { return; } territory::set_county(county); county->set_world(this); } void world::set_star_system(metternich::star_system *system) { if (system == this->get_star_system()) { return; } if (this->get_star_system() != nullptr) { this->get_star_system()->remove_world(this); } this->star_system = system; if (this->get_star_system() != nullptr) { this->get_star_system()->add_world(this); } emit star_system_changed(); } const std::filesystem::path &world::get_texture_path() const { //returns a random texture for the world return database::get()->get_tagged_texture_path(this->get_type()->get_texture_tag(), {{this->get_identifier()}}); } void world::set_orbit_angle(const double angle) { if (angle == this->orbit_angle) { return; } this->orbit_angle = angle; this->set_orbit_position(point::get_degree_angle_direction(this->orbit_angle)); } void world::remove_satellite(world *satellite) { vector::remove(this->satellites, satellite); } bool world::is_star() const { return this->get_type()->is_star(); } void world::set_map(const bool map) { if (map == this->has_map()) { return; } if (this->has_map()) { vector::remove(world::map_worlds, this); this->map_active = false; } this->map = map; if (this->has_map()) { world::map_worlds.push_back(this); this->map_active = true; } } void world::calculate_cosmic_map_pos() { if (this->get_astrocoordinate().isValid()) { if (this->get_astrocoordinate() == QGeoCoordinate(0, 0)) { this->set_cosmic_map_pos(QPointF(0, 0)); return; } QPointF direction_pos = geocoordinate::to_circle_edge_point(this->get_astrocoordinate()); double astrodistance = this->get_astrodistance(); astrodistance /= 100.; astrodistance = cbrt(astrodistance); astrodistance *= world::astrodistance_multiplier; const double x = direction_pos.x() * astrodistance; const double y = direction_pos.y() * astrodistance; const QPointF pos(x, y); if (this->get_orbit_center() == nullptr || point::distance_to(pos, this->get_orbit_center()->get_cosmic_map_pos()) >= ((this->get_cosmic_size() / 2) + world::min_orbit_distance)) { this->set_cosmic_map_pos(pos); return; } } if (this->get_orbit_center() != nullptr) { this->set_cosmic_map_pos(this->get_orbit_center()->get_cosmic_map_pos() + QPointF(this->get_orbit_position().x() * this->get_distance_from_orbit_center(), this->get_orbit_position().y() * this->get_distance_from_orbit_center())); return; } this->set_cosmic_map_pos(QPointF(0, 0)); } void world::calculate_cosmic_size() { double cosmic_size = 0; if (this->get_diameter() > 0) { cosmic_size = cbrt(this->get_diameter()); } if (cosmic_size == 0.) { cosmic_size = this->get_default_cosmic_size(); } if (this->is_star()) { if (cosmic_size < world::min_star_size && this->get_orbit_center() == nullptr) { cosmic_size = world::min_star_size; //only apply the star minimum size to system primary stars } else if (cosmic_size > world::max_star_size) { cosmic_size = world::max_star_size; } } else if (this->is_planet()) { if (cosmic_size < world::min_planet_size) { cosmic_size = world::min_planet_size; } } else if (this->is_moon()) { if (cosmic_size < world::min_moon_size) { cosmic_size = world::min_moon_size; } } this->set_cosmic_size(cosmic_size); } void world::add_holding_slot(holding_slot *holding_slot) { holding_slot->set_world(this); territory::add_holding_slot(holding_slot); } bool world::is_system_capital() const { return this->get_star_system() != nullptr && this->get_star_system()->get_capital_world() == this; } QVariantList world::get_provinces_qvariant_list() const { return container::to_qvariant_list(this->get_provinces()); } QVariantList world::get_trade_nodes_qvariant_list() const { return container::to_qvariant_list(this->trade_nodes); } QVariantList world::get_trade_routes_qvariant_list() const { return container::to_qvariant_list(this->trade_routes); } QPoint world::get_pixel_pos(const int index) const { return point::from_index(index, this->get_map_size()); } QPoint world::get_coordinate_pos(const QGeoCoordinate &coordinate) const { return geocoordinate::to_point(coordinate, this->get_lon_per_pixel(), this->get_lat_per_pixel()); } QPointF world::get_coordinate_posf(const QGeoCoordinate &coordinate) const { return geocoordinate::to_pointf(coordinate, this->get_lon_per_pixel(), this->get_lat_per_pixel()); } QGeoCoordinate world::get_pixel_pos_coordinate(const QPoint &pixel_pos) const { return point::to_geocoordinate(pixel_pos, this->get_map_size()); } terrain_type *world::get_coordinate_terrain(const QGeoCoordinate &coordinate) const { if (this->terrain_image.isNull()) { throw std::runtime_error("Cannot get coordinate terrain after clearing the terrain image from memory."); } QPoint pos = this->get_coordinate_pos(coordinate); QRgb rgb = this->terrain_image.pixel(pos); return terrain_type::get_by_rgb(rgb); } std::vector<QVariantList> world::parse_geojson_folder(const std::string_view &folder) const { std::vector<QVariantList> geojson_data_list; for (const std::filesystem::path &path : database::get()->get_map_paths()) { const std::filesystem::path map_path = path / this->get_identifier() / folder; if (!std::filesystem::exists(map_path)) { continue; } std::vector<QVariantList> folder_geojson_data_list = map::parse_geojson_folder(map_path); vector::merge(geojson_data_list, std::move(folder_geojson_data_list)); } return geojson_data_list; } void world::process_province_map_database() { if (std::string(province::database_folder).empty()) { return; } std::vector<gsml_data> gsml_map_data_to_process = this->parse_data_type_map_database<province>(); for (gsml_data &data : gsml_map_data_to_process) { province *province = province::get(data.get_tag()); this->add_province(province); database::process_gsml_data<metternich::province>(province, data); } } void world::process_terrain_map_database() { for (const std::filesystem::path &path : database::get()->get_map_paths()) { std::filesystem::path map_path = path / this->get_identifier() / "terrain"; if (!std::filesystem::exists(map_path)) { continue; } std::filesystem::directory_iterator dir_iterator(map_path); for (const std::filesystem::directory_entry &dir_entry : dir_iterator) { terrain_type *terrain = terrain_type::get(dir_entry.path().stem().string()); if (dir_entry.is_directory()) { std::filesystem::recursive_directory_iterator subdir_iterator(dir_entry); for (const std::filesystem::directory_entry &subdir_entry : subdir_iterator) { if (!subdir_entry.is_regular_file() || subdir_entry.path().extension() != ".txt") { continue; } gsml_parser parser(subdir_entry.path()); this->process_terrain_gsml_data(terrain, parser.parse()); } } else if (dir_entry.is_regular_file() && dir_entry.path().extension() == ".txt") { gsml_parser parser(dir_entry.path()); this->process_terrain_gsml_data(terrain, parser.parse()); } } } } void world::process_terrain_gsml_data(const terrain_type *terrain, const gsml_data &data) { data.for_each_child([&](const gsml_data &child_data) { this->process_terrain_gsml_scope(terrain, child_data); }); } void world::process_terrain_gsml_scope(const terrain_type *terrain, const gsml_data &scope) { const std::string &tag = scope.get_tag(); if (tag == "geopolygons") { scope.for_each_child([&](const gsml_data &polygon_data) { this->terrain_geopolygons[terrain].push_back(polygon_data.to_geopolygon()); }); } else if (tag == "geopaths") { scope.for_each_child([&](const gsml_data &path_data) { QGeoPath geopath = path_data.to_geopath(); geopath.setWidth(terrain->get_path_width()); this->terrain_geopaths[terrain].push_back(geopath); }); } else { throw std::runtime_error("Invalid scope for terrain map data: \"" + tag + "\"."); } } void world::load_province_map() { const std::filesystem::path province_image_path = this->get_cache_path() / "provinces.png"; if (!std::filesystem::exists(province_image_path)) { return; } engine_interface::get()->set_loading_message("Loading " + this->get_loading_message_name() + " Provinces... (0%)"); this->province_image = QImage(QString::fromStdString(province_image_path.string())); if (this->province_image.isNull()) { throw std::runtime_error("Failed to load province map image."); } const int pixel_count = this->province_image.width() * this->province_image.height(); std::map<province *, std::map<terrain_type *, int>> province_terrain_counts; const QRgb *rgb_data = reinterpret_cast<const QRgb *>(this->province_image.constBits()); const QRgb *terrain_rgb_data = reinterpret_cast<const QRgb *>(this->terrain_image.constBits()); province *previous_pixel_province = nullptr; //used to see which provinces border which horizontally for (int i = 0; i < pixel_count; ++i) { const bool line_start = ((i % this->province_image.width()) == 0); if (line_start) { //new line, set the previous pixel province to null previous_pixel_province = nullptr; //update the progress in the loading message const long long int progress_percent = static_cast<long long int>(i) * 100 / pixel_count; engine_interface::get()->set_loading_message("Loading " + this->get_loading_message_name() + " Provinces... (" + QString::number(progress_percent) + "%)"); } const QRgb &pixel_rgb = rgb_data[i]; province *pixel_province = province::get_by_rgb(pixel_rgb, false); if (pixel_province != nullptr) { if (previous_pixel_province != pixel_province && previous_pixel_province != nullptr) { pixel_province->add_border_province(previous_pixel_province); previous_pixel_province->add_border_province(pixel_province); } if (i > this->province_image.width()) { //second line or below //the pixel just above this one const int adjacent_pixel_index = i - this->province_image.width(); const QRgb &previous_vertical_pixel_rgb = rgb_data[adjacent_pixel_index]; province *previous_vertical_pixel_province = province::get_by_rgb(previous_vertical_pixel_rgb, false); if (previous_vertical_pixel_province != pixel_province && previous_vertical_pixel_province != nullptr) { pixel_province->add_border_province(previous_vertical_pixel_province); previous_vertical_pixel_province->add_border_province(pixel_province); } } const QRgb &terrain_pixel_rgb = terrain_rgb_data[i]; terrain_type *pixel_terrain = terrain_type::get_by_rgb(terrain_pixel_rgb); std::map<terrain_type *, int> &province_terrain_count = province_terrain_counts[pixel_province]; province_terrain_count[pixel_terrain]++; } previous_pixel_province = pixel_province; } for (const auto &province_terrain_count : province_terrain_counts) { province *province = province_terrain_count.first; bool inner_river = false; for (const auto &kv_pair : province_terrain_count.second) { terrain_type *terrain = kv_pair.first; if (terrain != nullptr && terrain->is_river() && !inner_river) { inner_river = true; } } province->set_inner_river(inner_river); } for (province *world_province : this->get_provinces()) { //add river crossings if (world_province->is_river()) { //add all of this province's border provinces to each other for (province *border_province : world_province->get_border_provinces()) { if (border_province->is_water()) { continue; } for (province *other_border_province : world_province->get_border_provinces()) { if (other_border_province->is_water()) { continue; } if (border_province->borders_province(other_border_province)) { continue; //already borders the other province directly } border_province->add_river_crossing(other_border_province); other_border_province->add_river_crossing(border_province); } } } } for (province *province : this->get_provinces()) { province->calculate_rect(); province->calculate_center_pos(); if (province->get_terrain() == nullptr) { province->calculate_terrain(); } } } void world::load_terrain_map() { const std::filesystem::path terrain_image_path = this->get_cache_path() / "terrain.png"; if (!std::filesystem::exists(terrain_image_path)) { return; } engine_interface::get()->set_loading_message("Loading " + this->get_loading_message_name() + " Terrain..."); this->terrain_image = QImage(QString::fromStdString(terrain_image_path.string())); if (this->terrain_image.isNull()) { throw std::runtime_error("Failed to load terrain map image."); } this->map_size = this->terrain_image.size(); //set the world's pixel size to that of its terrain map } void world::write_geodata_to_image() { if (!std::filesystem::exists(this->get_cache_path())) { std::filesystem::create_directories(this->get_cache_path()); } QImage terrain_image; for (const std::filesystem::path &path : database::get()->get_map_paths()) { const std::filesystem::path map_path = path / this->get_identifier(); if (!std::filesystem::exists(map_path)) { continue; } const std::filesystem::path terrain_image_path = map_path / "terrain.png"; if (!std::filesystem::exists(terrain_image_path)) { continue; } terrain_image = QImage(terrain_image_path.string().c_str()); this->write_terrain_geodata_to_image(terrain_image); break; } for (const std::filesystem::path &path : database::get()->get_map_paths()) { const std::filesystem::path map_path = path / this->get_identifier(); if (!std::filesystem::exists(map_path)) { continue; } const std::filesystem::path province_image_path = map_path / "provinces.png"; if (!std::filesystem::exists(province_image_path)) { continue; } QImage province_image(province_image_path.string().c_str()); this->write_province_geodata_to_image(province_image, terrain_image); province_image.save(QString::fromStdString((this->get_cache_path() / "provinces.png").string())); break; } if (!terrain_image.isNull()) { //the terrain image has to be saved after the province image has been written, because provinces can also write to it terrain_image.save(QString::fromStdString((this->get_cache_path() / "terrain.png").string())); } } void world::write_terrain_geodata_to_image(QImage &terrain_image) { int progress = 0; int max_progress = 0; for (const auto &kv_pair : this->terrain_geopolygons) { max_progress += static_cast<int>(kv_pair.second.size()); } for (const auto &kv_pair : this->terrain_geopaths) { max_progress += static_cast<int>(kv_pair.second.size()); } for (const auto &kv_pair : this->terrain_geopolygons) { const terrain_type *terrain = kv_pair.first; for (const QGeoPolygon &geopolygon : kv_pair.second) { const int progress_percent = progress * 100 / max_progress; engine_interface::get()->set_loading_message("Writing " + this->get_loading_message_name() + " Terrain to Image... (" + QString::number(progress_percent) + "%)"); this->write_terrain_geoshape_to_image(terrain, terrain_image, geopolygon); progress++; } } for (const auto &kv_pair : this->terrain_geopaths) { const terrain_type *terrain = kv_pair.first; for (const QGeoPath &geopath : kv_pair.second) { const int progress_percent = progress * 100 / max_progress; engine_interface::get()->set_loading_message("Writing " + this->get_loading_message_name() + " Terrain to Image... (" + QString::number(progress_percent) + "%)"); this->write_terrain_geoshape_to_image(terrain, terrain_image, geopath); progress++; } } this->write_terrain_geopath_endpoints_to_image(terrain_image); } void world::write_terrain_geopath_endpoints_to_image(QImage &image) { for (const auto &kv_pair : this->terrain_geopaths) { const terrain_type *terrain = kv_pair.first; const int circle_radius = terrain->get_path_width() / 2; for (const QGeoPath &geopath : kv_pair.second) { QGeoCircle front_geocircle(geopath.path().front(), circle_radius); this->write_terrain_geoshape_to_image(terrain, image, front_geocircle); QGeoCircle back_geocircle(geopath.path().back(), circle_radius); this->write_terrain_geoshape_to_image(terrain, image, back_geocircle); } } } void world::write_terrain_geoshape_to_image(const terrain_type *terrain, QImage &image, const QGeoShape &geoshape) { const QString terrain_loading_message = engine_interface::get()->get_loading_message(); QRgb rgb = terrain->get_color().rgb(); QRgb *rgb_data = reinterpret_cast<QRgb *>(image.bits()); const double lon_per_pixel = 360.0 / static_cast<double>(image.size().width()); const double lat_per_pixel = 180.0 / static_cast<double>(image.size().height()); QGeoRectangle georectangle = geoshape.boundingGeoRectangle(); QGeoCoordinate bottom_left = georectangle.bottomLeft(); QGeoCoordinate top_right = georectangle.topRight(); if (geoshape.type() == QGeoShape::ShapeType::PathType) { //increase the bounding rectangle of paths slightly, as otherwise a part of the path's width is cut off bottom_left.setLatitude(bottom_left.latitude() - 0.1); bottom_left.setLongitude(bottom_left.longitude() - 0.1); top_right.setLatitude(top_right.latitude() + 0.1); top_right.setLongitude(top_right.longitude() + 0.1); } double lon = bottom_left.longitude(); lon = geocoordinate::longitude_to_pixel_longitude(lon, lon_per_pixel); const int start_x = geocoordinate::longitude_to_x(lon, lon_per_pixel); double start_lat = bottom_left.latitude(); start_lat = geocoordinate::latitude_to_pixel_latitude(start_lat, lat_per_pixel); const int pixel_width = static_cast<int>(std::round((std::abs(top_right.longitude() - bottom_left.longitude())) / lon_per_pixel)); const bool show_progress = pixel_width >= 512; for (; lon <= top_right.longitude(); lon += lon_per_pixel) { const int x = geocoordinate::longitude_to_x(lon, lon_per_pixel); for (double lat = start_lat; lat <= top_right.latitude(); lat += lat_per_pixel) { QGeoCoordinate coordinate(lat, lon); const int y = geocoordinate::latitude_to_y(lat, lat_per_pixel); const int pixel_index = point::to_index(x, y, image.size()); //only write the province to the pixel if it is empty, or if this is a river province and the province to overwrite is not an ocean province if (rgb_data[pixel_index] != terrain_type::empty_rgb && (!terrain->is_river() || terrain_type::get_by_rgb(rgb_data[pixel_index])->is_ocean())) { continue; } if (!geoshape.contains(coordinate)) { continue; } rgb_data[pixel_index] = rgb; } if (show_progress) { const int progress_percent = (x - start_x) * 100 / pixel_width; engine_interface::get()->set_loading_message(terrain_loading_message + "\nWriting Geoshape to Image... (" + QString::number(progress_percent) + "%)"); } } engine_interface::get()->set_loading_message(terrain_loading_message); } void world::write_province_geodata_to_image(QImage &province_image, QImage &terrain_image) { std::vector<province *> provinces = container::to_vector(this->get_provinces()); std::sort(provinces.begin(), provinces.end(), [](const province *a, const province *b) { if (a->is_ocean() != b->is_ocean()) { return a->is_ocean(); } return a < b; }); int processed_provinces = 0; std::set<QRgb> province_image_rgbs = image::get_rgbs(province_image); std::vector<province *> geopath_provinces; for (province *province : provinces) { const int progress_percent = processed_provinces * 100 / static_cast<int>(province::get_all().size()); engine_interface::get()->set_loading_message("Writing " + this->get_loading_message_name() + " Provinces to Image... (" + QString::number(progress_percent) + "%)"); if (!province_image_rgbs.contains(province->get_color().rgb()) || province->always_writes_geodata()) { province->write_geodata_to_image(province_image, terrain_image); } processed_provinces++; if (province->is_river()) { geopath_provinces.push_back(province); } } //write geopath endpoints, but only after everything else, as they should have lower priority than the geopaths themselves for (province *province : geopath_provinces) { if (!province_image_rgbs.contains(province->get_color().rgb()) || province->always_writes_geodata()) { province->write_geopath_endpoints_to_image(province_image, terrain_image); } } } void world::add_province(province *province) { this->provinces.insert(province); province->set_world(this); } void world::amalgamate() { std::map<landed_title *, int> realm_counts; std::map<holding_type *, int> fort_holding_type_counts; std::map<holding_type *, int> university_holding_type_counts; std::map<holding_type *, int> hospital_holding_type_counts; std::map<landed_title *, int> trading_post_realm_counts; std::map<holding_type *, int> trading_post_holding_type_counts; std::map<holding_type *, int> factory_holding_type_counts; for (province *province : this->get_provinces()) { //add any technology present in one of its provinces to the world itself for (technology *technology : province->get_technologies()) { if (!this->has_technology(technology)) { this->add_technology(technology); } } for (holding *settlement_holding : province->get_settlement_holdings()) { realm_counts[settlement_holding->get_barony()->get_realm()]++; } if (province->get_fort_holding() != nullptr) { fort_holding_type_counts[province->get_fort_holding()->get_type()]++; } if (province->get_university_holding() != nullptr) { university_holding_type_counts[province->get_university_holding()->get_type()]++; } if (province->get_hospital_holding() != nullptr) { hospital_holding_type_counts[province->get_hospital_holding()->get_type()]++; } if (province->get_trading_post_holding() != nullptr) { trading_post_realm_counts[province->get_trading_post_holding()->get_realm()]++; trading_post_holding_type_counts[province->get_trading_post_holding()->get_type()]++; } if (province->get_factory_holding() != nullptr) { factory_holding_type_counts[province->get_factory_holding()->get_type()]++; } } std::set<landed_title *> holding_realms; //amalgamate the world's map elements into ones for the cosmic map for (holding_slot *settlement_slot : this->get_settlement_holding_slots()) { settlement_slot->amalgamate_megalopolis(); if (settlement_slot->get_holding() != nullptr) { holding_realms.insert(settlement_slot->get_holding()->get_barony()->get_realm()); } } holding_type *best_type = nullptr; int best_count = 0; for (const auto &kv_pair : fort_holding_type_counts) { holding_type *type = kv_pair.first; const int count = kv_pair.second; if (count > best_count) { best_type = type; best_count = count; } } if (best_type != nullptr) { this->create_holding(this->get_fort_holding_slot(), best_type); } best_type = nullptr; best_count = 0; for (const auto &kv_pair : university_holding_type_counts) { holding_type *type = kv_pair.first; const int count = kv_pair.second; if (count > best_count) { best_type = type; best_count = count; } } if (best_type != nullptr) { this->create_holding(this->get_university_holding_slot(), best_type); } best_type = nullptr; best_count = 0; for (const auto &kv_pair : hospital_holding_type_counts) { holding_type *type = kv_pair.first; const int count = kv_pair.second; if (count > best_count) { best_type = type; best_count = count; } } if (best_type != nullptr) { this->create_holding(this->get_hospital_holding_slot(), best_type); } best_type = nullptr; best_count = 0; for (const auto &kv_pair : trading_post_holding_type_counts) { holding_type *type = kv_pair.first; const int count = kv_pair.second; if (count > best_count) { best_type = type; best_count = count; } } if (best_type != nullptr) { this->create_holding(this->get_trading_post_holding_slot(), best_type); } landed_title *best_realm = nullptr; best_count = 0; for (landed_title *realm : holding_realms) { const auto find_iterator = trading_post_realm_counts.find(realm); if (find_iterator == trading_post_realm_counts.end()) { continue; } const int count = find_iterator->second; if (count > best_count) { best_realm = realm; best_count = count; } } if (best_realm != nullptr) { this->get_trading_post_holding()->set_owner(best_realm->get_holder()); } best_type = nullptr; best_count = 0; for (const auto &kv_pair : factory_holding_type_counts) { holding_type *type = kv_pair.first; const int count = kv_pair.second; if (count > best_count) { best_type = type; best_count = count; } } if (best_type != nullptr) { this->create_holding(this->get_factory_holding_slot(), best_type); } best_realm = nullptr; best_count = 0; for (landed_title *realm : holding_realms) { const auto find_iterator = realm_counts.find(realm); if (find_iterator == realm_counts.end()) { continue; } const int count = find_iterator->second; if (count > best_count) { best_realm = realm; best_count = count; } } if (best_realm != nullptr) { //set this world's capital holding to a megalopolis holding owned by the world county's new owner, preferentially the one which is the megalopolis of the new owner's current capital if (best_realm->get_capital_province() != nullptr && best_realm->get_capital_province()->get_megalopolis() != nullptr && best_realm->get_capital_province()->get_megalopolis()->get_holding() != nullptr && best_realm->get_capital_province()->get_megalopolis()->get_holding()->get_owner() == best_realm->get_holder()) { this->set_capital_holding_slot(best_realm->get_capital_province()->get_megalopolis()); } else { for (holding *megalopolis: this->get_settlement_holdings()) { if (megalopolis->get_owner() == best_realm->get_holder()) { this->set_capital_holding_slot(megalopolis->get_slot()); break; } } } this->get_county()->set_holder(best_realm->get_holder()); //set ownership of the star system as well, if it is not owned by anyone yet if (this->get_de_jure_duchy()->get_holder() == nullptr) { this->get_de_jure_duchy()->set_holder(best_realm->get_holder()); } } for (province *province : this->get_provinces()) { province->destroy_settlement_holdings(); //will also cause the destruction of extra holdings } for (landed_title *title : landed_title::get_all()) { if (title->get_capital_province() == nullptr || title->get_capital_province()->get_world() != this) { continue; } if (title->is_active_post_amalgamation()) { title->set_capital_world(title->get_capital_province()->get_world()); title->set_capital_province(nullptr); continue; } if (title->get_holder() != nullptr) { //destroy landed titles which should only exist in the world map title->set_holder(nullptr); } } //calculate population groups for the world, so that e.g. its plurality culture will have been calculated this->calculate_population_groups(); } }
32.870183
354
0.728294
[ "vector" ]
f82da91d6265a37275baad2846ecd46b2b77610f
11,886
cc
C++
src/base/b3FFT.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/base/b3FFT.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/base/b3FFT.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
1
2022-01-07T15:58:38.000Z
2022-01-07T15:58:38.000Z
/* ** ** $Filename: b3FFT.cc $ ** $Release: Dortmund 2006, 2016 $ ** $Revision$ ** $Date$ ** $Author$ ** $Developer: Steffen A. Mork $ ** ** Blizzard III - Fourier transform ** ** (C) Copyright 2006 Steffen A. Mork ** All Rights Reserved ** ** */ /************************************************************************* ** ** ** Blizzard III includes ** ** ** *************************************************************************/ #include "blz3/system/b3Runtime.h" #include "blz3/system/b3TimeStop.h" #include "blz3/base/b3FFT.h" #include "blz3/base/b3Color.h" #include "blz3/base/b3Math.h" #include "blz3/base/b3Random.h" #define B3_FFT_MAX_THREADS 16 using namespace std::complex_literals; /************************************************************************* ** ** ** b3SimpleFourier ** ** ** *************************************************************************/ b3Fourier::b3Fourier() { // Dimension m_xOrig = m_yOrig = 0; m_xSize = m_ySize = 0; m_xStart = m_yStart = 0; m_xDim = m_yDim = 0; m_Buffer = nullptr; m_Lines = nullptr; m_Aux = nullptr; m_CPUs = std::min<b3_count>(B3_FFT_MAX_THREADS, b3Runtime::b3GetNumCPUs()); } b3Fourier::~b3Fourier() { b3FreeBuffer(); } void b3Fourier::b3FreeBuffer() { b3Free(); if (m_Buffer != nullptr) { delete [] m_Buffer; m_Buffer = nullptr; } if (m_Lines != nullptr) { delete [] m_Lines; m_Lines = nullptr; } if (m_Aux != nullptr) { delete [] m_Aux; m_Aux = nullptr; } } bool b3Fourier::b3AllocBuffer(const b3_res new_size) { b3_res size = b3Math::b3PowOf2(new_size); b3PrintF(B3LOG_FULL, ">b3Fourier::b3AllocBuffer(%d)\n", size); m_xOrig = m_yOrig = new_size; m_xStart = (size - m_xOrig) >> 1; m_yStart = (size - m_yOrig) >> 1; if ((m_xSize == size) && (m_ySize == size)) { // New buffer has same size. b3PrintF(B3LOG_FULL, "<b3Fourier::b3AllocBuffer(%d) [unchanged]\n", size); return true; } b3FreeBuffer(); m_xSize = m_ySize = size; if (!b3ReallocBuffer()) { b3FreeBuffer(); B3_THROW(b3FFTException, B3_FFT_NO_MEMORY); } b3PrintF(B3LOG_FULL, "<b3Fourier::b3AllocBuffer(%d)\n", size); return true; } bool b3Fourier::b3AllocBuffer(b3Tx * tx) { b3_loop x, y, index, max; b3_u08 * cPtr; b3PrintF(B3LOG_FULL, ">b3Fourier::b3AllocBuffer(%dx%d, ...)\n", tx->xSize, tx->ySize); if (!tx->b3IsLoaded()) { B3_THROW(b3FFTException, B3_FFT_SRC_TX_EMPTY); } b3FreeBuffer(); m_xOrig = tx->xSize; m_yOrig = tx->ySize; m_xSize = b3Math::b3PowOf2(m_xOrig); m_ySize = b3Math::b3PowOf2(m_yOrig); max = std::max(m_xSize, m_ySize); m_xSize = max; m_ySize = max; m_xStart = (m_xSize - m_xOrig) >> 1; m_yStart = (m_ySize - m_yOrig) >> 1; index = m_yStart * m_xSize + m_xStart; if (!tx->b3IsPalette()) { B3_THROW(b3FFTException, B3_FFT_NO_PALETTE); } b3PrintF(B3LOG_FULL, " Grey (%dx%d)\n", m_xSize, m_ySize); if (!b3ReallocBuffer()) { B3_THROW(b3FFTException, B3_FFT_NO_MEMORY); } cPtr = tx->b3GetIndexData(); for (y = 0; y < m_yOrig; y++) { for (x = 0; x < m_xOrig; x++) { m_Lines[y + m_yStart][x + m_xStart] = (b3_f64) * cPtr++ / 127.5 - 1.0; } index += m_xSize; } b3PrintF(B3LOG_FULL, "<b3Fourier::b3AllocBuffer(%dx%d, ...)\n", tx->xSize, tx->ySize); return true; } bool b3Fourier::b3ReallocBuffer() { B3_METHOD; m_xDim = b3Math::b3Log2(m_xSize); m_yDim = b3Math::b3Log2(m_ySize); m_Buffer = new (std::nothrow) b3Complex64[m_xSize * m_ySize]; m_Lines = new (std::nothrow) b3Complex64 *[m_ySize]; m_Aux = new (std::nothrow) b3Complex64[m_ySize * m_CPUs]; if ((m_Buffer == nullptr) || (m_Lines == nullptr) || (m_Aux == nullptr)) { return false; } for (b3_loop y = 0; y < m_ySize; y++) { m_Lines[y] = &m_Buffer[y * m_xSize]; } return true; } void b3Fourier::b3Sample(b3FilterInfo * info, b3SampleFunc sample_func) { b3_loop x, xHalf = m_xSize >> 1, xMask = m_xSize - 1; b3_loop y, yHalf = m_ySize >> 1, yMask = m_ySize - 1; b3_f64 fx, fxHalf = 1.0 / xHalf; b3_f64 fy, fyHalf = 1.0 / yHalf; b3_index index = 0, pos; b3PrintF(B3LOG_FULL, ">b3Fourier::b3Sample(...)\n"); info->m_Fourier = this; index = 0; for (y = -yHalf; y < yHalf; y++) { fy = fyHalf * y; index = (y & yMask) << m_xDim; for (x = -xHalf; x < xHalf; x++) { fx = fxHalf * x; pos = index + (x & xMask); sample_func(fx, fy, pos, info); } } b3PrintF(B3LOG_FULL, "<b3Fourier::b3Sample(...)\n"); } /*------------------------------------------------------------------------- This computes an in-place complex-to-complex FFT x and y are the real and imaginary arrays of 2^m points. dir = 1 gives forward transform dir = -1 gives reverse transform Formula: forward N-1 --- 1 \ - j k 2 pi n / N X(n) = --- > x(k) e = forward transform N / n=0..N-1 --- k=0 Formula: reverse N-1 --- \ j k 2 pi n / N X(n) = > x(k) e = forward transform / n=0..N-1 --- k=0 */ bool b3Fourier::b3FFT(const int dir, const b3_res m, b3Complex64 * line) { const b3Complex64 one( 1.0 + 1.0i); const b3Complex64 half(0.5 + 0.5i); const b3Complex64 dMult(1.0, dir == 1 ? -1.0 : 1.0); b3Complex64 c, u; b3_loop nn, i, i1, j, k, i2, l, l1, l2; /* Calculate the number of points */ nn = 1; for (i = 0; i < m; i++) { nn *= 2; } /* Do the bit reversal */ i2 = nn >> 1; j = 0; for (i = 0; i < nn - 1; i++) { if (i < j) { b3Complex64::b3Swap(line[i], line[j]); } k = i2; while (k <= j) { j -= k; k >>= 1; } j += k; } /* Compute the FFT */ c = -1.0; l2 = 1; for (l = 0; l < m; l++) { u = 1; l1 = l2; l2 <<= 1; for (j = 0; j < l1; j++) { for (i = j; i < nn; i += l2) { i1 = i + l1; const b3Complex64 t = u * line[i1]; line[i1] = line[i] - t; line[i] += t; } u *= c; } const b3_f64 cr = c.b3Real(); b3Complex64 q = one + b3Complex64(cr, -cr); q.b3Scale(half); c = b3Complex64::b3Sqrt(q); c.b3Scale(dMult); } /* Scaling for forward transform */ if (dir == 1) { const b3Complex64 denom(1.0 / nn, 1.0 / nn); for (i = 0; i < nn; i++) { line[i].b3Scale(denom); } } return true; } /** * Perform a 2D FFT inplace given a complex 2D array * The direction dir, 1 for forward, -1 for reverse * The size of the array (nx,ny) * Return false if there are memory problems or * the dimensions are not powers of 2 * * @param dir 1 for forward FFT, -1 for inverse FFT. * @return True on success. */ bool b3Fourier::b3FFT2D(const int dir) { b3TimeStop stop("2D FFT"); b3PrintF(B3LOG_FULL, ">b3Fourier::b3FFT2D(<%s>);\n", dir == 1 ? "forward" : "inverse"); b3Thread threads[B3_FFT_MAX_THREADS]; b3_fft_info info[B3_FFT_MAX_THREADS]; b3_loop i; for (i = 0; i < m_CPUs; i++) { info[i].m_Lines = m_Lines; info[i].m_Aux = &m_Aux[m_ySize * i]; info[i].m_xDim = m_xDim; info[i].m_yDim = m_yDim; info[i].m_Dir = dir; } if (m_CPUs > 1) { for (i = 0; i < m_CPUs; i++) { info[i].m_xMin = 0; info[i].m_xMax = m_xSize; info[i].m_yMin = m_ySize * i / m_CPUs; info[i].m_yMax = m_ySize * (i + 1) / m_CPUs; threads[i].b3Name("b3FFT - row computation"); threads[i].b3Start(b3RowFFT, &info[i]); } for (i = 0; i < m_CPUs; i++) { threads[i].b3Wait(); } stop.b3TimePos(); for (i = 0; i < m_CPUs; i++) { info[i].m_xMin = m_xSize * i / m_CPUs; info[i].m_xMax = m_xSize * (i + 1) / m_CPUs; info[i].m_yMin = 0; info[i].m_yMax = m_ySize; threads[i].b3Name("b3FFT - column computation"); threads[i].b3Start(b3ColumnFFT, &info[i]); } for (i = 0; i < m_CPUs; i++) { threads[i].b3Wait(); } } else { info[0].m_xMin = 0; info[0].m_xMax = m_xSize; info[0].m_yMin = 0; info[0].m_yMax = m_ySize; b3RowFFT(&info); b3ColumnFFT(&info); } return true; } bool b3Fourier::b3RowFFT(void * ptr) { b3_fft_info * info = static_cast<b3_fft_info *>(ptr); b3Complex64 ** lines = info->m_Lines; /* Transform the rows */ for (b3_loop j = info->m_yMin; j < info->m_yMax; j++) { b3FFT(info->m_Dir, info->m_xDim, lines[j]); } return false; } bool b3Fourier::b3ColumnFFT(void * ptr) { b3_fft_info * info = static_cast<b3_fft_info *>(ptr); b3Complex64 ** lines = info->m_Lines; b3Complex64 * aux = info->m_Aux; b3_loop i, j; /* Transform the columns */ for (i = info->m_xMin; i < info->m_xMax; i++) { for (j = info->m_yMin; j < info->m_yMax; j++) { #ifdef BLZ3_USE_SSE _mm_prefetch(reinterpret_cast<const char *>(&lines[j][i]), _MM_HINT_NTA); #endif aux[j] = lines[j][i]; } b3FFT(info->m_Dir, info->m_yDim, aux); for (j = info->m_yMin; j < info->m_yMax; j++) { #ifdef BLZ3_USE_SSE2 b3Complex64::b3CopyUncached(lines[j][i], aux[j]); #else lines[j][i] = aux[j]; #endif } } return false; } bool b3Fourier::b3GetBuffer(b3Tx * tx, b3_f64 amp) const { b3_u08 * cPtr; b3_loop x, y; b3_f64 cMin = 0, c, cMax = 0; b3PrintF(B3LOG_FULL, ">b3Fourier::b3GetBuffer(..., %1.3f)\n", amp); if (!tx->b3AllocTx(m_xOrig, m_yOrig, 8)) { B3_THROW(b3FFTException, B3_FFT_NO_MEMORY); } cPtr = tx->b3GetIndexData(); for (y = 0; y < m_yOrig; y++) { for (x = 0; x < m_xOrig; x++) { c = m_Lines[y + m_yStart][x + m_xStart].b3Real() * amp; if (c < cMin) { cMin = c; } if (c > cMax) { cMax = c; } *cPtr++ = (b3_u08)floor(b3Math::b3Clamp(c * 0.5 + 0.5, 0.0, 1.0) * 255); } } b3PrintF(B3LOG_FULL, "<b3Fourier::b3GetBuffer(...) [%1.4f - %1.4f]\n", cMin, cMax); return true; } bool b3Fourier::b3GetSpectrum(b3Tx * tx, b3_f64 amp) const { b3_u08 * cPtr; b3_f64 result; b3_f64 cMax = 0; b3_loop x, xHalf = m_xSize >> 1, xMask = m_xSize - 1; b3_loop y, yHalf = m_ySize >> 1, yMask = m_ySize - 1; b3_index index; b3PrintF(B3LOG_FULL, ">b3Fourier::b3GetSpectrum(..., %1.3f)\n", amp); if (!tx->b3AllocTx(m_xSize, m_ySize, 8)) { B3_THROW(b3FFTException, B3_FFT_NO_MEMORY); } cPtr = tx->b3GetIndexData(); for (y = -yHalf; y < yHalf; y++) { index = (y & yMask) << m_xDim; for (x = -xHalf; x < xHalf; x++) { result = m_Buffer[index + (x & xMask)].b3Length() * amp * 127; if (result > cMax) { cMax = result; } if (result > 255) { result = 255; } *cPtr++ = (b3_u08)result; } } b3PrintF(B3LOG_FULL, "<b3Fourier::b3GetSpectrum(...)\n"); return true; } bool b3Fourier::b3SelfTest() { b3Rand48<b3_f64> random; b3_loop x, y; b3_f64 err = 0, e; b3PrintF(B3LOG_FULL, ">b3Fourier::b3SelfTest() %dx%d\n", m_xSize, m_ySize); random.b3SetSeed(); for (y = 0; y < m_ySize; y++) { for (x = 0; x < m_xSize; x++) { m_Lines[y][x].b3Real() = random.b3Rand(); } } if (!b3FFT2D()) { return false; } if (!b3IFFT2D()) { return false; } random.b3SetSeed(); for (y = 0; y < m_ySize; y++) { for (x = 0; x < m_xSize; x++) { e = fabs(random.b3Rand() - m_Lines[y][x].b3Real()); err = std::max(err, fabs(e)); } } b3PrintF(B3LOG_NORMAL, "### CLASS: b3Four # error diff %g\n", err); b3PrintF(B3LOG_FULL, "<b3Fourier::b3SelfTest()\n"); return err < 0.001; }
22.134078
88
0.534158
[ "transform" ]
f835a39a07e83e5a0de92a657792b2327d2e4a44
81,889
cpp
C++
trafficGen.cpp
konstantinmiller/tcp_traffic_gen
88b4612352e27351cbec5a35c8aed9a5edeb658c
[ "MIT" ]
2
2017-07-18T08:19:11.000Z
2019-08-21T18:15:19.000Z
trafficGen.cpp
konstantinmiller/tcp_traffic_gen
88b4612352e27351cbec5a35c8aed9a5edeb658c
[ "MIT" ]
null
null
null
trafficGen.cpp
konstantinmiller/tcp_traffic_gen
88b4612352e27351cbec5a35c8aed9a5edeb658c
[ "MIT" ]
1
2019-08-21T18:15:25.000Z
2019-08-21T18:15:25.000Z
/**************************************************************************** * trafficGen.cpp * **************************************************************************** * Copyright (C) 2013 Technische Universitaet Berlin * * * * Created on: Aug 30, 2013 * * Authors: Konstantin Miller <konstantin.miller@tu-berlin.de> * * * * 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 <sys/types.h> #include <sys/time.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/select.h> #include <netinet/tcp.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <string.h> #include <stdio.h> #include <cstdlib> #define __STDC_FORMAT_MACROS #include <inttypes.h> #include <getopt.h> #include <cassert> #include <pthread.h> #ifndef __SENDER # include <pcap.h> #endif #include <errno.h> #include <ifaddrs.h> #include <sys/ioctl.h> #include <net/if.h> #include <map> #include <set> #include <string> #include <list> #include <mutex> #include <sstream> #include <iostream> #include <algorithm> #include <random> #include <boost/circular_buffer.hpp> using std::map; using std::set; using std::string; using std::list; using std::pair; //#include "VectorList.h" struct { enum {UNDEF, SENDER, RECEIVER} senderReceiver = UNDEF; bool ifActive = false; uint16_t psvPort = 0; string psvIp; string actIp; int64_t tcp_info_log_interval = 100000; // [us] } global_info; struct { int fd = -1; FILE* logFile = NULL; struct tcp_info lastTcpInfo; } tcp_logger_info; struct { FILE* f_sender_log = NULL; bool hang_up = false; bool permanent = false; } sender_info; struct { /* types */ enum RequestPatternType {DETERMINISTIC, NORMAL}; struct RequestPatternDeterministic { int64_t on_duration; int64_t off_duration; }; struct RequestPatternNormal { int64_t mean; int64_t std; int64_t min; int64_t max; int64_t tau; // segment duration, [ms] }; /* request pattern stuff */ string request_pattern; RequestPatternType request_pattern_type; union { RequestPatternDeterministic request_pattern_deterministic; RequestPatternNormal request_pattern_normal; }; string dev_name; int64_t dev_wait_max = -1; // [us] string dev_name_mon; FILE* file_request_log; int64_t request_sent = 0; int64_t first_data_received = 0; // [us] int64_t last_data_received = 0; int64_t request_size = 0; int64_t scheduled_on_duration = 0; double max_thrpt = -1; // [bps] int64_t max_thrpt_duration = -1; // [us] } rcv_info; struct rcv_log_info_t { //std::mutex mutex; rcv_log_info_t(): pcap_tcp_data(65536), pcap_rdtap_data(65536) {} #ifndef __SENDER static const int pcap_snaplen = 96; static const int radiotap_snaplen = 512; pcap_t* pcap_tcp = NULL; pcap_t* pcap_rdtap = NULL; pcap_dumper_t* pcap_dumper_tcp = NULL; pcap_dumper_t* pcap_dumper_rdtap = NULL; #endif struct pcap_element { pcap_element(const struct pcap_pkthdr* _pkthdr, const u_char* _pktdata) { pkthdr = *_pkthdr; assert(pkthdr.caplen <= sizeof(pktdata)); std::memcpy(pktdata, _pktdata, pkthdr.caplen * sizeof(u_char)); } struct pcap_pkthdr pkthdr; u_char pktdata[(pcap_snaplen < radiotap_snaplen) ? radiotap_snaplen : pcap_snaplen]; }; boost::circular_buffer<pcap_element> pcap_tcp_data; boost::circular_buffer<pcap_element> pcap_rdtap_data; std::mutex pcap_tcp_data_mutex; std::mutex pcap_rdtap_data_mutex; //FILE* f = NULL; //int64_t dt = 0; // [us] //int64_t ts_first_packet = 0; // [us] //int64_t tcp_ts_first_packet = 0; // [us] //int64_t index = -1; // [us] //int64_t num_bytes = 0; //vector<int64_t> delay_vec; // [us] //vector<int> missing_vec; //int64_t off1; //int64_t off2; //void reset() { // num_bytes = 0; // delay_vec.resize(0); // missing_vec.resize(0); // off1 = 0; // off2 = 0; //} } rcv_log_info; #pragma pack(push, 1) struct Rcv2Snd_Params { uint8_t limitType = 0; // 0 for time, 1 for volume uint32_t limitValue = 0; // if time: [ms], if volume: [byte] uint8_t hang_up = 0; // 1 for disconnect after request completed, otherwise 0 }; #pragma pack(pop) void printUsageAndExit(int line); void parseInputArguments(int argc, char** argv); void signalHandler(int sig); void* runSender(void* args); void* runReceiver(void* args); void* runTcpStateLogger(void* args); void* runSniffer(void* _args); void* runRadiotap(void* _args); int64_t now(); void recordTcpState(int fd, const char* reason, FILE* f); void recordTcpState(FILE* f, const struct tcp_info& tcpInfo, const int64_t t, const char* reason); string tcpState2String(int tcpState); string tcpCAState2String(int tcpCAState); //void rcv_log_output(); string getTimeString(int64_t t, bool showDate); string get_dev_for_ip(string ip); string get_ip_for_dev(string dev); bool wait_for_dev(string dev, int64_t max_wait); void parse_request_pattern(const char* request_pattern); //void* run_flusher(void* _args); char buf[1048576]; // for various string manipulations const int sndbufsize = 1048576; // 8192; //const int rcvbufsize = 2 * 1048576; string config; string traceDir("."); int64_t Tmax = -1; int64_t t_start_sender = 0; int64_t t_start_receiver = 0; bool terminate_tcp_logger = false; bool globalTerminationFlag = false; std::default_random_engine generator(std::chrono::system_clock::now().time_since_epoch().count()); int main(int argc, char** argv) { printf("Up and running...\n"); sprintf(buf, "main_enter %" PRId64 "\n", now()); config.append(buf); parseInputArguments(argc, argv); /* install signal handler */ struct sigaction sigAction; sigAction.sa_handler = signalHandler; sigemptyset(&sigAction.sa_mask); sigAction.sa_flags = 0; assert(0 == sigaction(SIGINT, &sigAction, NULL)); assert(0 == sigaction(SIGTERM, &sigAction, NULL)); assert(0 == sigaction(SIGALRM, &sigAction, NULL)); /* start flusher thread */ //pthread_t flusher_thread; //assert(0 == pthread_create(&flusher_thread, NULL, &run_flusher, NULL)); if(global_info.senderReceiver == global_info.SENDER) { /* open log file */ char fn_sender_log[4096]; sprintf(fn_sender_log, "%s/sender_log_%016" PRId64 ".txt", traceDir.c_str(), now()); sender_info.f_sender_log = fopen(fn_sender_log, "w"); assert(sender_info.f_sender_log); setlinebuf(sender_info.f_sender_log); pthread_t senderThread; while(!globalTerminationFlag) { assert(0 == pthread_create(&senderThread, NULL, &runSender, NULL)); assert(0 == pthread_join(senderThread, NULL)); if(!sender_info.permanent) { globalTerminationFlag = true; printf("Terminating sender.\n"); } } /* close log file */ assert(0 == fclose(sender_info.f_sender_log)); } else if(global_info.senderReceiver == global_info.RECEIVER) { pthread_t receiverThread; assert(0 == pthread_create(&receiverThread, NULL, &runReceiver, NULL)); assert(0 == pthread_join(receiverThread, NULL)); } else { abort(); } /* wait for the flusher thread */ //assert(0 == pthread_join(flusher_thread, NULL)); sprintf(buf, "main_terminate %" PRId64 "\n", now()); config.append(buf); /* write parameters to file */ if(global_info.senderReceiver == global_info.RECEIVER) { sprintf(buf, "%s/rcv_config_%016" PRId64 ".txt", traceDir.c_str(), t_start_receiver); FILE* f = fopen(buf, "w"); fprintf(f, "%s", config.c_str()); fclose(f); } return 0; } void printUsageAndExit(int line) { printf("Error parsing command line arguments in line %d.\n", line); printf("OPTIONS\n"); printf("\n"); printf("--role=( sender | receiver )\n"); printf(" Mandatory.\n"); printf("\n"); printf("--active\n"); printf(" Optional. If set, the peer actively connects to the remote peer.\n"); printf("\n"); printf("--permanent\n"); printf(" Optional. Only valid for the passive peer. If set, does not terminate after the active peer disconnects.\n"); printf("\n"); printf("--passive-ip=xxx.xxx.xxx.xxx\n"); printf(" Mandatory. IP of the passive peer.\n"); printf("\n"); printf("--passive-port=<integer>\n"); printf(" Mandatory. Port of the passive peer.\n"); printf("\n"); printf("--active-ip=xxx.xxx.xxx.xxx\n"); printf(" Optional. If present, specifies the IP of the active peer. Otherwise,\n"); printf(" the default is used.\n"); printf("\n"); printf("--dev-name=<string>\n"); printf(" Optional, only valid if --active is set and --active-ip is not set. Uses\n"); printf(" the default IP of the specified network interface as source IP.\n"); printf("\n"); printf("--dev-wait-max=<double, [s]>\n"); printf(" Optional, only valid if --dev-name is set. Waits for device to become\n"); printf(" available for up to the specified number of seconds.\n"); printf("\n"); printf("--dev-name-mon=<string>\n"); printf(" Device for radiotap recording. If not specified, no readiotap headers are\n"); printf(" recorded.\n"); printf("\n"); printf("--trace-duration=<integer, [s]>\n"); printf(" Mandatory for active peer, invalid for passive peer. Specifies the\n"); printf(" duration of the trace.\n"); printf("\n"); printf("--max-thrpt=<double, [Mbps]>\n"); printf(" Optional. Throughput upper bound. If the throughput exceeds upper bound,\n"); printf(" terminate experiment. If set, --max-thrpt-duration must be set too.\n"); printf("\n"); printf("--max-thrpt-duration=<double, [s]>\n"); printf(" Optional. Specifies duration over which throughput upper bound must not\n"); printf(" be exceeded. If set, --max-thrpt must be set.\n"); printf("\n"); printf("--log-dir=<string>\n"); printf(" Optional. Directory for file output. If not set, current directory is used.\n"); printf("\n"); printf("--tcp-info-log-interval=<integer, [ms]>\n"); printf(" Optional, between 0 and 1000 ms. Specifies the sampling rate for struct\n"); printf(" tcp_info. If not set, the default value of 100 ms is used. If set to 0,\n"); printf(" logging takes place before and after every socket operation.\n"); printf("\n"); printf("--request-pattern=<string>\n"); printf(" Optional, only valid for receiver. If not set, a continuous TCP flow of\n"); printf(" duration specified in --trace-duration is requested. Possible values are:\n"); printf(" deterministic:AAA:BBB\n"); printf(" AAA, BBB: integer, [ms]\n"); printf(" Generates an ON/OFF pattern with deterministic duration of ON and OFF\n"); printf(" phases. AAA specifies the duration of the request (ON phase), while BBB\n"); printf(" specifies the duration of the inter-request gap (OFF phase).\n"); printf(" normal:AAA:BBB:CCC:DDD:EEE\n"); printf(" AAA, BBB, CCC, DDD, EEE: integer, [ms]\n"); printf(" Generates a random ON/OFF pattern with normally distributed duration of\n"); printf(" of the ON phase, with mean AAA and standard deviation BBB. In order to\n"); printf(" avoid negative or very long values, only values with the interval\n"); printf(" [CCC, DDD] are accepted. The duration of the OFF phase is determined\n"); printf(" EEE and the duration of the ON phase. If ON phase is longer than EEE,\n"); printf(" there is no OFF phase. Otherwise, the duration of the OFF phase is\n"); printf(" EEE - duration of the ON phase.\n"); printf("\n"); #if 0 printf("EXAMPLES\n"); printf("sudo ./trafficGen --role=receiver --active --passive-ip=130.149.49.253 --passive-port=54321 --dev-name=wlan0 --trace-duration=60 --log-dir=. --tcp-info-log-interval=1000\n"); printf(" Generates a continuous TCP flow with duration 60 seconds.\n"); printf("\n"); printf("sudo ./trafficGen --role=receiver --active --passive-ip=130.149.49.253 --passive-port=54321 --dev-name=wlan0 --trace-duration=60 --log-dir=. --tcp-info-log-interval=1000 --request-pattern=normal:1600:400:1200:2400:2000\n"); printf(" Generates a TCP flow with deterministic ON/OFF pattern, with total duration of 60 seconds.\n"); printf("\n"); printf("sudo ./trafficGen --role=receiver --active --passive-ip=130.149.49.253 --passive-port=54321 --dev-name=wlan0 --trace-duration=60 --log-dir=. --tcp-info-log-interval=1000 --request-pattern=deterministic:1600:400\n"); printf(" Generates a TCP flow with normally distributed ON duration, with total duration of 60 seconds.\n"); printf("\n"); #endif exit(1); } void parseInputArguments(int argc, char** argv) { enum {HELP='0', ROLE='a', IS_ACTIVE='b', IS_PERMANENT='c', PASSIVE_IP='d', PASSIVE_PORT='e', ACTIVE_IP='f', DEV_NAME='g', TRACE_DURATION='h', LOG_DIR='i', TCP_INFO_LOG_INTERVAL='j', REQUEST_PATTERN='k', DEV_NAME_MON='l', MAX_THRPT='m', MAX_THRPT_DURATION='n', DEV_WAIT_MAX='o'}; while(true) { static struct option long_options[] = { {"help", no_argument, 0, HELP}, {"role", required_argument, 0, ROLE}, {"active", no_argument, 0, IS_ACTIVE}, {"permanent", no_argument, 0, IS_PERMANENT}, {"passive-ip", required_argument, 0, PASSIVE_IP}, {"passive-port", required_argument, 0, PASSIVE_PORT}, {"active-ip", required_argument, 0, ACTIVE_IP}, {"dev-name", required_argument, 0, DEV_NAME}, {"dev-wait-max", required_argument, 0, DEV_WAIT_MAX}, {"dev-name-mon", required_argument, 0, DEV_NAME_MON}, {"trace-duration", required_argument, 0, TRACE_DURATION}, {"max-thrpt", required_argument, 0, MAX_THRPT}, {"max-thrpt-duration", required_argument, 0, MAX_THRPT_DURATION}, {"log-dir", required_argument, 0, LOG_DIR}, {"tcp-info-log-interval", required_argument, 0, TCP_INFO_LOG_INTERVAL}, {"request-pattern", required_argument, 0, REQUEST_PATTERN}, {0, 0, 0, 0} }; int c = getopt_long (argc, argv, "", long_options, NULL); if (c == -1) break; switch(c) { case HELP: printUsageAndExit(__LINE__); break; case ROLE: if(global_info.senderReceiver != global_info.UNDEF) printUsageAndExit(__LINE__); if(strcmp(optarg, "sender") == 0) global_info.senderReceiver = global_info.SENDER; else if(strcmp(optarg, "receiver") == 0) global_info.senderReceiver = global_info.RECEIVER; else printUsageAndExit(__LINE__); sprintf(buf, "role %s\n", optarg); config.append(buf); break; case IS_ACTIVE: global_info.ifActive = true; sprintf(buf, "active 1\n"); config.append(buf); break; case IS_PERMANENT: sender_info.permanent = true; sprintf(buf, "permanent 1\n"); config.append(buf); break; case PASSIVE_IP: if(!global_info.psvIp.empty()) printUsageAndExit(__LINE__); global_info.psvIp = optarg; sprintf(buf, "passive_ip %s\n", global_info.psvIp.c_str()); config.append(buf); break; case PASSIVE_PORT: { if(global_info.psvPort != 0) printUsageAndExit(__LINE__); char* endptr = NULL; global_info.psvPort = strtol(optarg, &endptr, 10); if(*endptr != '\0') printUsageAndExit(__LINE__); sprintf(buf, "passive_port %" PRIu16 "\n", global_info.psvPort); config.append(buf); break; } case ACTIVE_IP: if(!global_info.actIp.empty()) printUsageAndExit(__LINE__); global_info.actIp = optarg; sprintf(buf, "active_ip %s\n", global_info.actIp.c_str()); config.append(buf); break; case DEV_NAME: if(!rcv_info.dev_name.empty()) printUsageAndExit(__LINE__); rcv_info.dev_name = optarg; sprintf(buf, "dev_name %s\n", rcv_info.dev_name.c_str()); config.append(buf); break; case DEV_WAIT_MAX: { if(rcv_info.dev_wait_max != -1) printUsageAndExit(__LINE__); char* endptr = NULL; rcv_info.dev_wait_max = 1e6 * strtod(optarg, &endptr); if(*endptr != '\0') printUsageAndExit(__LINE__); sprintf(buf, "dev_wait_max %.3f\n", rcv_info.dev_wait_max / 1e6); config.append(buf); break; } case DEV_NAME_MON: if(!rcv_info.dev_name_mon.empty()) printUsageAndExit(__LINE__); rcv_info.dev_name_mon = optarg; sprintf(buf, "dev_name_mon %s\n", rcv_info.dev_name_mon.c_str()); config.append(buf); break; case TRACE_DURATION: { if(Tmax != -1) printUsageAndExit(__LINE__); char* endptr = NULL; Tmax = (int64_t)1000000 * (int64_t)strtol(optarg, &endptr, 10); if(*endptr != '\0') printUsageAndExit(__LINE__); sprintf(buf, "Tmax %" PRId64 "\n", Tmax); config.append(buf); break; } case MAX_THRPT: { if(rcv_info.max_thrpt != -1) printUsageAndExit(__LINE__); char* endptr = NULL; rcv_info.max_thrpt = 1e6 * strtod(optarg, &endptr); if(*endptr != '\0') printUsageAndExit(__LINE__); sprintf(buf, "max_thrpt %.3f\n", rcv_info.max_thrpt); config.append(buf); break; } case MAX_THRPT_DURATION: { if(rcv_info.max_thrpt_duration != -1) printUsageAndExit(__LINE__); char* endptr = NULL; rcv_info.max_thrpt_duration = 1e6 * strtod(optarg, &endptr); if(*endptr != '\0') printUsageAndExit(__LINE__); sprintf(buf, "max_thrpt_duration %" PRId64 "\n", rcv_info.max_thrpt_duration); config.append(buf); break; } case LOG_DIR: traceDir = optarg; sprintf(buf, "log_dir %s\n", traceDir.c_str()); config.append(buf); break; case TCP_INFO_LOG_INTERVAL: { char* endptr = NULL; global_info.tcp_info_log_interval = (int64_t)1000 * (int64_t)strtol(optarg, &endptr, 10); if(*endptr != '\0') printUsageAndExit(__LINE__); sprintf(buf, "tcp_info_log_interval %" PRId64 "\n", global_info.tcp_info_log_interval); config.append(buf); break; } case REQUEST_PATTERN: if(!rcv_info.request_pattern.empty()) printUsageAndExit(__LINE__); parse_request_pattern(optarg); sprintf(buf, "request_pattern %s\n", optarg); config.append(buf); break; default: printUsageAndExit(__LINE__); } } /* Input arguments consistency check */ // if(global_info.psvIp.empty() || 49152 > global_info.psvPort || global_info.psvPort > 65535) printUsageAndExit(__LINE__); if(global_info.psvIp.empty()) printUsageAndExit(__LINE__); if(global_info.ifActive && sender_info.permanent) printUsageAndExit(__LINE__); if(global_info.psvIp.empty() || global_info.psvPort == 0) printUsageAndExit(__LINE__); if(!rcv_info.dev_name.empty() && !(global_info.ifActive && global_info.actIp.empty())) printUsageAndExit(__LINE__); if((Tmax == -1 && global_info.ifActive) || (Tmax != -1 && !global_info.ifActive)) printUsageAndExit(__LINE__); if(!rcv_info.request_pattern.empty() && global_info.senderReceiver == global_info.SENDER) printUsageAndExit(__LINE__); if((rcv_info.max_thrpt != -1 && rcv_info.max_thrpt_duration == -1) || (rcv_info.max_thrpt == -1 && rcv_info.max_thrpt_duration != -1) || (rcv_info.max_thrpt != -1 && global_info.senderReceiver == global_info.SENDER)) printUsageAndExit(__LINE__); if(global_info.senderReceiver == global_info.SENDER && rcv_info.dev_wait_max != -1) printUsageAndExit(__LINE__); } void* runSender(void* _args) { int _fd = -1; int fd = -1; if(global_info.ifActive) { fd = socket(AF_INET, SOCK_STREAM, 0); assert(-1 != fd); if(!global_info.actIp.empty()) { struct sockaddr_in sockaddr_src; memset(&sockaddr_src, 0, sizeof(sockaddr_src)); sockaddr_src.sin_family = AF_INET; sockaddr_src.sin_addr.s_addr = inet_addr(global_info.actIp.c_str()); assert(0 == bind(fd, (struct sockaddr*)&sockaddr_src, sizeof(struct sockaddr_in))); } struct sockaddr_in sockaddr; sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = inet_addr(global_info.psvIp.c_str()); sockaddr.sin_port = htons(global_info.psvPort); assert(-1 != connect(fd, (struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in))); } /* passive sender */ else { _fd = socket(AF_INET, SOCK_STREAM, 0); assert(-1 != _fd); if(sender_info.permanent) { int optval = 1; setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); } fprintf(sender_info.f_sender_log, "%s Binding to %s:%u.\n", getTimeString(0, true).c_str(), global_info.psvIp.c_str(), global_info.psvPort); struct sockaddr_in sockaddr; sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = inet_addr(global_info.psvIp.c_str()); sockaddr.sin_port = htons(global_info.psvPort); assert(0 == bind(_fd, (struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in))); assert(0 == listen(_fd, 0)); /* waiting for incoming connections */ while(!globalTerminationFlag && fd == -1) { fd_set readfds; FD_ZERO(&readfds); FD_SET(_fd, &readfds); struct timeval to; to.tv_sec = 1; to.tv_usec = 0; int ret = select(_fd + 1, &readfds, NULL, NULL, &to); if(ret < 0) { perror("select()"); abort(); } else if(ret == 0) { continue; } else if(ret == 1) { struct sockaddr_in activeSockaddr; unsigned senderSockaddrLength = sizeof(struct sockaddr_in); fd = accept(_fd, (struct sockaddr*)&activeSockaddr, &senderSockaddrLength); assert(fd > 0 && senderSockaddrLength == sizeof(struct sockaddr_in)); fprintf(sender_info.f_sender_log, "%s Got incoming connection from %s:%d.\n", getTimeString(0, true).c_str(), inet_ntoa(activeSockaddr.sin_addr), ntohs(activeSockaddr.sin_port)); } else { abort(); } } if(globalTerminationFlag){ assert(0 == close(_fd)); if(fd != -1) assert(0 == close(fd)); return NULL; } if(_fd != -1) assert(0 == close(_fd)); } assert(fd != -1); t_start_sender = now(); fprintf(sender_info.f_sender_log, "%s Starting sender %" PRId64 ".\n", getTimeString(0, true).c_str(), t_start_sender); // adjust sending buffer size //assert(0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sndbufsize, sizeof(sndbufsize))); /* disable Nagle */ //const int disable_nagle = 1; //assert(0 == setsockopt(fd, SOL_TCP, TCP_NODELAY, &disable_nagle, sizeof(disable_nagle))); // log sending buffer size { int dummy_int = 0; unsigned dummy_int_size = sizeof(dummy_int); assert(0 == getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void*)&dummy_int, &dummy_int_size)); sprintf(buf, "%s/snd_config_%016" PRId64 ".txt", traceDir.c_str(), t_start_sender); FILE* f = fopen(buf, "w"); sprintf(buf, "SO_SNDBUF %d\n", dummy_int); fprintf(f, "%s", buf); fclose(f); } /* open file for logging */ char logFileName[2048]; sprintf(logFileName, "%s/snd_tcpinfo_log_%016" PRId64 ".txt", traceDir.c_str(), t_start_sender); FILE* logFile = fopen(logFileName, "w"); assert(logFile); /* starting logger thread */ tcp_logger_info.fd = fd; tcp_logger_info.logFile = logFile; terminate_tcp_logger = false; pthread_t loggerThread; if(global_info.tcp_info_log_interval > 0) assert(0 == pthread_create(&loggerThread, NULL, &runTcpStateLogger, NULL)); do // while not hang up { /* if passive, read Tmax from the active peer */ if(!global_info.ifActive) { fd_set readfds; FD_ZERO(&readfds); FD_SET(fd, &readfds); struct timeval to; to.tv_sec = 1; to.tv_usec = 0; int ret = select(fd + 1, &readfds, NULL, NULL, &to); if(ret < 0) { perror("select()"); throw std::runtime_error("Error in select() 1.\n"); } else if(ret == 0) { sender_info.hang_up = false; continue; } else if(ret > 1) { throw std::runtime_error("Error in select() 2.\n"); } assert(FD_ISSET(fd, &readfds)); Rcv2Snd_Params rcv2snd_params; int br = read(fd, &rcv2snd_params, sizeof(rcv2snd_params)); assert(br >= 0); if(br == 0) { printf("%s ERROR: Connection %" PRId64 " reset by peer.\n", getTimeString(0, true).c_str(), t_start_sender); fprintf(sender_info.f_sender_log, "%s ERROR: Connection %" PRId64 " reset by peer.\n", getTimeString(0, true).c_str(), t_start_sender); break; } else { assert(br == sizeof(rcv2snd_params)); } rcv2snd_params.limitValue = ntohl(rcv2snd_params.limitValue); sender_info.hang_up = rcv2snd_params.hang_up; if(rcv2snd_params.limitType == 0) { Tmax = (int64_t)rcv2snd_params.limitValue * 1000; fprintf(sender_info.f_sender_log, "%s Will send data for AT LEAST %.3f seconds and %shang up.\n", getTimeString(0, true).c_str(), Tmax / 1e6, sender_info.hang_up ? "" : "NOT "); } else { throw std::runtime_error("only supporting time for the moment."); } } int64_t bytesSent = 0; int64_t bufSend[sndbufsize >> 3]; memset(bufSend, 0, sizeof(int64_t)); int64_t Tstart = now(); int64_t chunk_size = sndbufsize; // [byte] double nextInfoOutput = Tmax >= 100000000 ? 0.01 : (Tmax >= 5000000 ? 0.1 : 2.0); // never output for short requests //int cnt_write = 0; //boost::circular_buffer<int64_t> chunk_times(10); //boost::circular_buffer<int64_t> chunk_sizes(10); //boost::circular_buffer<double> chunk_thrpts(10); //for(int i = 0; i < chunk_times.size(); ++i) {chunk_times.push_back(100000); chunk_sizes.push_back(65536); chunk_thrpts.push_back((8.0 * chunk_sizes.at(i)) / (chunk_times.at(i) / 1e6));} while(!globalTerminationFlag) { //int value = -1; //assert(0 == ioctl(fd, TIOCOUTQ, &value) && value != -1); //printf("Still have %d bytes to send.\n", value); /* send next portion of data */ //for(int64_t i = 0; i < (chunk_size >> 3); ++i) // bufSend[i] = bytesSent + 8 * (i + 1); if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "before write", logFile); int64_t tic_write = now(); int ret = write(fd, bufSend, chunk_size); //printf("After write. ret: %d\n", ret); //++cnt_write; int64_t toc_write = now(); if(ret == -1 && errno == ECONNRESET) { perror("write()"); printf("ERROR: Connection %" PRId64 " reset by peer while sending data.\n", t_start_sender); fprintf(sender_info.f_sender_log, "%s ERROR: Connection %" PRId64 " reset by peer while sending data.\n", getTimeString(0, true).c_str(), t_start_sender); sender_info.hang_up = true; break; } else if(ret == -1){ perror("write()"); static char buf[2048]; sprintf(buf, "Could not write %" PRId64 " bytes to socket.\n", chunk_size); throw std::runtime_error(buf); } assert(ret >= 0); bytesSent += ret; if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "after write", logFile); if(ret != chunk_size) { printf("ERROR: Could not complete writing chunk to socket. Potential reason: connection %" PRId64 " reset by peer while sending data.\n", t_start_sender); fprintf(sender_info.f_sender_log, "%s ERROR: Could not complete writing chunk to socket. Potential reason: connection %" PRId64 " reset by peer while sending data.\n", getTimeString(0, true).c_str(), t_start_sender); sender_info.hang_up = true; break; } assert(ret == chunk_size); const int64_t t = now(); if(t - Tstart >= Tmax - tcp_logger_info.lastTcpInfo.tcpi_rtt / 2) { //printf("%d writes, %.0f writes per sec., %.0f ms inter-write time.\n", cnt_write, cnt_write / ((t - Tstart) / 1e6), ((t - Tstart) / 1e3) / cnt_write); //cnt_write = 0; printf("Request completed: %6.3f seconds.\n", (t - Tstart) / 1e6); fprintf(sender_info.f_sender_log, "%s Tmax (%d sec) expired. Sender: %" PRId64 ".\n", getTimeString(0, true).c_str(), (int)(Tmax / 1000000), t_start_sender); if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "before write", logFile); uint8_t _tmp = 1; int ret = write(fd, (void*)&_tmp, 1); if(ret == -1 && errno == ECONNRESET) { perror("write()"); printf("ERROR: Connection %" PRId64 " reset by peer while finalizing request.\n", t_start_sender); fprintf(sender_info.f_sender_log, "%s ERROR: Connection %" PRId64 " reset by peer while finalizing request.\n", getTimeString(0, true).c_str(), t_start_sender); sender_info.hang_up = true; break; } else if(ret == -1){ perror("write()"); static char buf[2048]; sprintf(buf, "Could not write %u bytes to socket.\n", (unsigned)sizeof(_tmp)); throw std::runtime_error(buf); } else { assert(ret == sizeof(_tmp)); //printf("Sent %d bytes.\n", ret); } if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "after write", logFile); break; } else if((double)(t - Tstart) / (double)Tmax >= nextInfoOutput) { nextInfoOutput += Tmax >= 100000000 ? 0.01 : 0.1; printf("Progress: %6.2f%%.\n", 100.0 * (double)(t - Tstart) / (double)Tmax); } // determine chunk size //chunk_times.push_back(toc_write - tic_write); //chunk_sizes.push_back(chunk_size); //chunk_thrpts.push_back((8.0 * chunk_sizes.back()) / (chunk_times.back() / 1e6)); //double chunk_thrpt = std::accumulate(chunk_sizes.begin(), chunk_sizes.end(), 0.0) / (std::accumulate(chunk_times.begin(), chunk_times.end(), 0.0) / 1e6); // [byte/sec] //for(int i = 0; i < chunk_times.size(); ++i) chunk_thrpt += 1.0 / chunk_times.size() * chunk_sizes.at(i) / ((double)chunk_times.at(i) / 1e6); //const int64_t chunk_size_old = chunk_size; //chunk_size = 0.05 / 8.0 * *std::min_element(chunk_thrpts.begin(), chunk_thrpts.end()); // number of byte to be send in approximately 100 ms //chunk_size = std::min<int64_t>(chunk_size, 65536); //chunk_size = std::max<int64_t>(chunk_size, 8192); //chunk_size = sndbufsize; //printf("old chunk_size: %5" PRId64 ", duration: %8.6f, new chunk_size: %5" PRId64 "\n", chunk_size_old, (toc_write - tic_write) / 1e6, chunk_size); } } while(!sender_info.hang_up); terminate_tcp_logger = true; if(global_info.tcp_info_log_interval > 0) assert(0 == pthread_join(loggerThread, NULL)); /* close log file */ assert(0 == fclose(logFile)); /* shutdown connection and close sockets */ shutdown(fd, SHUT_RDWR); // intentionally don't check return value assert(0 == close(fd)); //if(_fd != -1) assert(0 == close(_fd)); fprintf(sender_info.f_sender_log, "%s All sockets closed.\n", getTimeString(0, true).c_str()); /* write parameters to file */ { sprintf(buf, "%s/snd_config_%016" PRId64 ".txt", traceDir.c_str(), t_start_sender); FILE* f = fopen(buf, "w"); fprintf(f, "%s", config.c_str()); fclose(f); } return NULL; } void* runReceiver(void* _args) { #ifndef __SENDER int _fd = -1; int fd = -1; if(global_info.ifActive) { /* wait for device to become available */ if(!rcv_info.dev_name.empty() && rcv_info.dev_wait_max > 0 && !wait_for_dev(rcv_info.dev_name, rcv_info.dev_wait_max)) return NULL; /* create socket */ fd = socket(AF_INET, SOCK_STREAM, 0); assert(-1 != fd); /* bind to specified network interface or IP if requested */ if(!global_info.actIp.empty() || !rcv_info.dev_name.empty()) { if(rcv_info.dev_name.empty()) rcv_info.dev_name = get_dev_for_ip(global_info.actIp); if(global_info.actIp.empty()) { global_info.actIp = get_ip_for_dev(rcv_info.dev_name); printf("Determined %s as IP address of %s.\n", global_info.actIp.c_str(), rcv_info.dev_name.c_str()); } struct sockaddr_in sockaddr_src; memset(&sockaddr_src, 0, sizeof(sockaddr_src)); sockaddr_src.sin_family = AF_INET; sockaddr_src.sin_addr.s_addr = inet_addr(global_info.actIp.c_str()); assert(0 == bind(fd, (struct sockaddr*)&sockaddr_src, sizeof(struct sockaddr_in))); printf("Bound to specified active IP.\n"); } /* connect */ struct sockaddr_in sockaddr; sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = inet_addr(global_info.psvIp.c_str()); sockaddr.sin_port = htons(global_info.psvPort); assert(-1 != connect(fd, (struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in))); printf("Connected.\n"); } else { _fd = socket(AF_INET, SOCK_STREAM, 0); assert(-1 != _fd); printf("Binding to %s:%u.\n", global_info.psvIp.c_str(), global_info.psvPort); struct sockaddr_in sockaddr; sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = inet_addr(global_info.psvIp.c_str()); sockaddr.sin_port = htons(global_info.psvPort); assert(0 == bind(_fd, (struct sockaddr*)&sockaddr, sizeof(struct sockaddr_in))); assert(0 == listen(_fd, 0)); printf("Ready and listening for incoming connections.\n"); while(!globalTerminationFlag && fd == -1) { fd_set readfds; FD_ZERO(&readfds); FD_SET(_fd, &readfds); struct timeval to; to.tv_sec = 1; to.tv_usec = 0; int ret = select(_fd + 1, &readfds, NULL, NULL, &to); if(ret < 0) { perror("select()"); abort(); } else if(ret == 0) { continue; } else if(ret == 1) { struct sockaddr_in activeSockaddr; unsigned senderSockaddrLength = sizeof(struct sockaddr_in); fd = accept(_fd, (struct sockaddr*)&activeSockaddr, &senderSockaddrLength); assert(fd > 0 && senderSockaddrLength == sizeof(struct sockaddr_in)); printf("Got incoming connection from %s:%d.\n", inet_ntoa(activeSockaddr.sin_addr), ntohs(activeSockaddr.sin_port)); } else { abort(); } } if(globalTerminationFlag){ assert(0 == close(_fd)); if(fd != -1) assert(0 == close(fd)); return NULL; } } assert(fd != -1); // adjust receiving buffer size //assert(0 == setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbufsize, sizeof(rcvbufsize))); // log receiving buffer size int dummy_int = 0; unsigned dummy_int_size = sizeof(dummy_int); assert(0 == getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void*)&dummy_int, &dummy_int_size)); sprintf(buf, "SO_RCVBUF %d\n", dummy_int); config.append(buf); t_start_receiver = now(); /* initialize pcap sniffer and radiotap monitor */ pthread_t snifferThread, radiotapThread; if(!rcv_info.dev_name.empty()) assert(0 == pthread_create(&snifferThread, NULL, &runSniffer, NULL)); if(!rcv_info.dev_name_mon.empty()) assert(0 == pthread_create(&radiotapThread, NULL, &runRadiotap, NULL)); sleep(2); // give the sniffers some time to initialize /* open file for logging */ char logFileName[4096]; sprintf(logFileName, "%s/rcv_tcpinfo_log_%016" PRId64 ".txt", traceDir.c_str(), t_start_receiver); tcp_logger_info.logFile = fopen(logFileName, "w"); assert(tcp_logger_info.logFile); /* start logger thread */ tcp_logger_info.fd = fd; pthread_t loggerThread; if(global_info.tcp_info_log_interval > 0) assert(0 == pthread_create(&loggerThread, NULL, &runTcpStateLogger, NULL)); /* open file for request logging */ char fn_request_log[4096]; sprintf(fn_request_log, "%s/rcv_request_log_%016" PRId64 ".txt", traceDir.c_str(), t_start_receiver); rcv_info.file_request_log = fopen(fn_request_log, "w"); assert(rcv_info.file_request_log); fprintf(rcv_info.file_request_log, "| request_sent | first_data_received | last_data_received | request_size | scheduled_on_duration |\n"); /* loop over requests */ bool log_to_console = true; while(!globalTerminationFlag) { /* if active, send request parameters */ if(global_info.ifActive) { const int64_t _now = now(); rcv_info.request_sent = _now; rcv_info.first_data_received = 0; assert(Tmax > 0); if(rcv_info.request_pattern.empty()) { rcv_info.scheduled_on_duration = Tmax; Rcv2Snd_Params rcv2snd_params; rcv2snd_params.limitType = 0; rcv2snd_params.limitValue = htonl((uint32_t)(rcv_info.scheduled_on_duration / 1000)); rcv2snd_params.hang_up = true; assert(sizeof(rcv2snd_params) == write(fd, &rcv2snd_params, sizeof(rcv2snd_params))); } else if(rcv_info.request_pattern_type == rcv_info.DETERMINISTIC) { rcv_info.scheduled_on_duration = rcv_info.request_pattern_deterministic.on_duration; Rcv2Snd_Params rcv2snd_params; rcv2snd_params.limitType = 0; rcv2snd_params.limitValue = htonl((uint32_t)(rcv_info.scheduled_on_duration / 1000)); if(_now + rcv_info.request_pattern_deterministic.on_duration + rcv_info.request_pattern_deterministic.off_duration - t_start_receiver >= Tmax) rcv2snd_params.hang_up = true; else rcv2snd_params.hang_up = false; assert(sizeof(rcv2snd_params) == write(fd, &rcv2snd_params, sizeof(rcv2snd_params))); } else if(rcv_info.request_pattern_type == rcv_info.NORMAL) { std::normal_distribution<double> distribution(rcv_info.request_pattern_normal.mean, rcv_info.request_pattern_normal.std); rcv_info.scheduled_on_duration = 0; do { rcv_info.scheduled_on_duration = distribution(generator); } while(rcv_info.request_pattern_normal.min <= rcv_info.scheduled_on_duration && rcv_info.scheduled_on_duration <= rcv_info.request_pattern_normal.max); Rcv2Snd_Params rcv2snd_params; rcv2snd_params.limitType = 0; rcv2snd_params.limitValue = htonl((uint32_t)(rcv_info.scheduled_on_duration / 1000)); if(_now + rcv_info.request_pattern_normal.tau - t_start_receiver >= Tmax) rcv2snd_params.hang_up = true; else rcv2snd_params.hang_up = false; assert(sizeof(rcv2snd_params) == write(fd, &rcv2snd_params, sizeof(rcv2snd_params))); } else { throw std::runtime_error("Unknown request pattern: " + rcv_info.request_pattern); } log_to_console = rcv_info.scheduled_on_duration / 1e6 >= 5 ? true : false; } /* loop until all bytes of the request have been received */ int64_t bytesReceived = 0; int64_t bytes_received_last_output = 0; uint8_t bufReceive[1048576]; int64_t t_first_data = 0; int64_t t_last_output = 0; while(!globalTerminationFlag) { /* sleep until there is data in the socket to read */ fd_set readfds; FD_ZERO(&readfds); FD_SET(fd, &readfds); struct timeval to; to.tv_sec = 1; to.tv_usec = 0; int ret = select(fd + 1, &readfds, NULL, NULL, &to); if(ret < 0) { perror("select()"); abort(); } else if(ret == 0) { continue; } else if(ret > 1) { abort(); } /* read data from the socket */ assert(FD_ISSET(fd, &readfds)); int br = 0; if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "before recv", tcp_logger_info.logFile); br = recv(fd, bufReceive, sizeof(bufReceive), MSG_DONTWAIT); assert(br >= 0); if(global_info.tcp_info_log_interval == 0) recordTcpState(fd, "after recv", tcp_logger_info.logFile); const int64_t _now = now(); if(rcv_info.first_data_received == 0) rcv_info.first_data_received = _now; /* If the sender closed the connection -> terminate. */ if(br == 0) { printf("Sender closed the connection.\n"); globalTerminationFlag = true; continue; } /* throughput logging to console */ if(t_first_data == 0) { t_first_data = t_last_output = _now; } bytesReceived += br; if(log_to_console && (_now - t_last_output) / 1e6 >= 1) { printf("Received %.6f MB. Average throughput last second: %.3f Mbps, total: %.3f Mbps.\n", bytesReceived / 1e6, 8.0 * (bytesReceived - bytes_received_last_output) / (double)(_now - t_last_output), 8.0 * bytesReceived / (double)(_now - t_first_data)); bytes_received_last_output = bytesReceived; t_last_output = _now; } /* Check if throughput exceeds upper bound. If yes, terminate experiment. */ if(rcv_info.max_thrpt != -1 && (_now - rcv_info.first_data_received) >= rcv_info.max_thrpt_duration) { const double thrpt = (8.0 * bytesReceived) / ((_now - rcv_info.first_data_received) / 1e6); // [bps] if(thrpt >= rcv_info.max_thrpt) { printf("Average throughput over first %.3f s was %.3f Mbps. Terminating.\n", (_now - rcv_info.first_data_received) / 1e6, thrpt / 1e6); globalTerminationFlag = true; continue; } } /* Did we just receive last bytes of the request? */ if(bufReceive[br-1] == 1) { rcv_info.last_data_received = _now; rcv_info.request_size = bytesReceived; fprintf(rcv_info.file_request_log, " %" PRId64 " %16.6f %16.6f %14.6f %23.6f\n", rcv_info.request_sent, (rcv_info.first_data_received - rcv_info.request_sent) / 1e6, (rcv_info.last_data_received - rcv_info.request_sent) / 1e6, rcv_info.request_size / 1e6, rcv_info.scheduled_on_duration / 1e6); if(rcv_info.request_pattern.empty()) { printf("End of request. Duration: %6.3f s. Average throughput: %6.3f Mbps. Terminating.\n", (_now - rcv_info.first_data_received) / 1e6, 8.0 * bytesReceived / (double)(_now - t_first_data)); globalTerminationFlag = true; } else if(rcv_info.request_pattern_type == rcv_info.DETERMINISTIC) { if(_now + rcv_info.request_pattern_deterministic.off_duration - t_start_receiver >= Tmax) { printf("End of request. Duration: %6.3f s. Average throughput: %6.3f Mbps.\n", (_now - rcv_info.first_data_received) / 1e6, 8.0 * bytesReceived / (double)(_now - t_first_data)); printf("End of trace. %.3f (>= %.3f - %.3f) sec expired. Terminating\n", (_now - t_start_receiver) / 1e6, Tmax / 1e6, rcv_info.request_pattern_deterministic.off_duration / 1e6); globalTerminationFlag = true; } else { printf("End of request. Duration: %6.3f s. Average throughput: %6.3f Mbps. Will wait for %6.3f s.\n", (_now - rcv_info.first_data_received) / 1e6, 8.0 * bytesReceived / (double)(_now - t_first_data), rcv_info.request_pattern_deterministic.off_duration / 1e6); usleep(rcv_info.request_pattern_deterministic.off_duration); } } else if(rcv_info.request_pattern_type == rcv_info.NORMAL) { if(rcv_info.first_data_received + rcv_info.request_pattern_normal.tau - t_start_receiver >= Tmax) { printf("End of request. Duration: %6.3f s. Average throughput: %6.3f Mbps.\n", (_now - rcv_info.first_data_received) / 1e6, 8.0 * bytesReceived / (double)(_now - t_first_data)); printf("End of trace. %.3f sec expired. Terminating\n", (_now - t_start_receiver) / 1e6); globalTerminationFlag = true; } else { int64_t off_duration = std::max<int64_t>(0, rcv_info.request_pattern_normal.tau - (_now - rcv_info.first_data_received)); if(off_duration) { printf("End of request. Duration: %6.3f s (< %6.3f). Average throughput: %6.3f Mbps. Will wait for %6.3f s.\n", (_now - rcv_info.first_data_received) / 1e6, rcv_info.request_pattern_normal.tau / 1e6, 8.0 * bytesReceived / (double)(_now - t_first_data), off_duration / 1e6); usleep(rcv_info.request_pattern_deterministic.off_duration); } else { printf("End of request. Duration: %6.3f s (> %6.3f). Average throughput: %6.3f Mbps. Will not wait.\n", (_now - rcv_info.first_data_received) / 1e6, rcv_info.request_pattern_normal.tau / 1e6, 8.0 * bytesReceived / (double)(_now - t_first_data)); } } } else { throw std::runtime_error("Unknown request pattern: " + rcv_info.request_pattern); } break; } } } terminate_tcp_logger = true; if(global_info.tcp_info_log_interval > 0) assert(0 == pthread_join(loggerThread, NULL)); if(rcv_log_info.pcap_tcp) pcap_breakloop(rcv_log_info.pcap_tcp); if(rcv_log_info.pcap_rdtap) pcap_breakloop(rcv_log_info.pcap_rdtap); if(!rcv_info.dev_name.empty()) assert(0 == pthread_join(snifferThread, NULL)); if(!rcv_info.dev_name_mon.empty()) assert(0 == pthread_join(radiotapThread, NULL)); /* close log files */ assert(0 == fclose(tcp_logger_info.logFile)); //assert(0 == fclose(rcv_log_info.f)); assert(0 == fclose(rcv_info.file_request_log)); /* shutdown connection and close sockets */ shutdown(fd, SHUT_RDWR); // intentionally don't check return value assert(0 == close(fd)); if(_fd != -1) assert(0 == close(_fd)); #if 0 { char buf[1024]; sprintf(buf, "%s/rcv_throughput_process_psvport%05d.txt", args.traceDir.c_str(), args.psvPort); FILE* f = fopen(buf, "w"); assert(f); for(list<vector<pair<int64_t,int64_t> > >::const_iterator it = thrptProcess.begin(); it != thrptProcess.end(); ++it) { const vector<pair<int64_t,int64_t> >& v = *it; for(int i = 0; i < v.size(); ++i) { const int64_t ts = v.at(i).first; const int64_t numBytes = v.at(i).second; fprintf(f, "%" PRId64 " %" PRId64 "\n", ts, numBytes); } } assert(0 == fclose(f)); } #endif return NULL; #endif } void* runTcpStateLogger(void* _args) { while(!terminate_tcp_logger) { recordTcpState(tcp_logger_info.fd, "periodic", tcp_logger_info.logFile); assert(0 == usleep(global_info.tcp_info_log_interval)); } return NULL; } /* merges pair p with pairs in [first, last). * Preconditions: * all the pairs in [first, last] are non-overlapping and sorted. * If nothing has to be inserted, it returns toBeInserted.second < toBeInserted.first. */ template <class InputIterator, class T> void merge(const InputIterator begin, const InputIterator end, const std::pair<T, T>& p, list<InputIterator>& toBeErased, std::pair<T, T>& toBeInserted) { if(!toBeErased.empty()) {printf("Bug in %s:%d.\n", __FILE__, __LINE__); abort();} /* Can we insert before first? */ if(begin == end || p.second + 1 < begin->first) { toBeInserted = p; return; } else if(p.second + 1 == begin->first) { toBeInserted.first = p.first; toBeInserted.second = begin->second; toBeErased.push_back(begin); return; } /* Can we insert after last? */ if(begin != end) { InputIterator endMinusOne = end; --endMinusOne; if(endMinusOne->second + 1 < p.first) { toBeInserted = p; return; } else if(endMinusOne->second + 1 == p.first) { toBeInserted.first = endMinusOne->first; toBeInserted.second = p.second; toBeErased.push_back(endMinusOne); return; } } /* find * 1. the pair where, or the one after which, p starts * 2. the pair where, or the one before which, p ends */ InputIterator itStart = begin; bool startsWithinOrNeighboring = false; bool foundStart = false; InputIterator itEnd = end; bool endsWithinOrNeighboring = false; bool foundEnd = false; for(InputIterator it = begin; it != end; ++it) { const pair<T, T>& _p = *it; if(_p.second + 1 < p.first) { itStart = it; startsWithinOrNeighboring = false; foundStart = true; } else if(_p.first <= p.first) { itStart = it; startsWithinOrNeighboring = true; foundStart = true; } if(p.second + 1 < _p.first) { itEnd = it; endsWithinOrNeighboring = false; foundEnd = true; break; } else if(p.second <= _p.second) { itEnd = it; endsWithinOrNeighboring = true; foundEnd = true; break; } } if(itStart == itEnd) { if(!startsWithinOrNeighboring || !endsWithinOrNeighboring) {printf("Bug in %s:%d.\n", __FILE__, __LINE__); abort();} toBeInserted.first = 1; toBeInserted.second = 0; return; } if(startsWithinOrNeighboring) { toBeInserted.first = itStart->first; toBeErased.push_back(itStart); } else { toBeInserted.first = p.first; } InputIterator it = itStart; ++it; for(; it != itEnd; ++it) toBeErased.push_back(it); if(endsWithinOrNeighboring) { toBeInserted.second = itEnd->second; toBeErased.push_back(itEnd); } else { toBeInserted.second = p.second; } } /* Ethernet header: 14 bytes */ #define ETHER_ADDR_LEN 6 #pragma pack(push, 1) struct ethernethdr { uint8_t dst[ETHER_ADDR_LEN]; uint8_t src[ETHER_ADDR_LEN]; uint16_t type ; /* IP? ARP? RARP? etc */ }; #pragma pack(pop) /* IP header: 20 to 60 bytes */ #pragma pack(push, 1) struct iphdr { uint8_t vhl; /* version << 4 | header length >> 2 */ uint8_t tos; /* type of service */ uint16_t len; /* total length */ uint16_t id; /* identification */ uint16_t off; /* fragment offset field */ uint8_t ttl; /* time to live */ uint8_t p; /* protocol */ uint16_t sum; /* checksum */ uint32_t src; /* source address */ uint32_t dst; /* destination address */ }; #pragma pack(pop) int ip_hl(const struct iphdr* ip) {return 4 * (ip->vhl & 0x0f);} /* TCP header: 20 to 60 bytes */ #pragma pack(push, 1) struct my_tcphdr { uint16_t th_sport; /* source port */ uint16_t th_dport; /* destination port */ uint32_t th_seq; /* sequence number */ uint32_t th_ack; /* acknowledgement number */ uint8_t th_offx2; uint8_t th_flags; uint16_t th_win; /* window */ uint16_t th_sum; /* checksum */ uint16_t th_urp; /* urgent pointer */ }; struct tcp_option { uint8_t kind; uint8_t size; }; #pragma pack(pop) struct my_tcphdr_tools { static int tcp_off(const struct my_tcphdr& tcpHdr) {return 4 * ((tcpHdr.th_offx2 >> 4) & 0x0f);} static bool tcp_syn(const struct my_tcphdr& tcpHdr) {return tcpHdr.th_flags & 0x02;} static bool tcp_fin(const struct my_tcphdr& tcpHdr) {return tcpHdr.th_flags & 0x01;} static bool tcp_ack(const struct my_tcphdr& tcpHdr) {return tcpHdr.th_flags & 0x10;} static uint32_t tcp_seq(const struct my_tcphdr& tcpHdr) {return ntohl(tcpHdr.th_seq);} //static string tcp2str(const struct my_tcphdr& tcpHdr); }; struct LessThenNonOverlapping { //bool operator() (const pair<int64_t, int64_t>& a, const pair<int64_t, int64_t>& b) const; bool operator() (const pair<int64_t, int64_t>& a, const pair<int64_t, int64_t>& b) const { if(a.first <= a.second && b.first <= b.second && a.second < b.first) return true; else if(a.first <= a.second && b.first <= b.second && b.second < a.first) return false; else { static char buf[2048]; sprintf(buf, "Overlapping pairs detected: [%lld, %lld] and [%lld, %lld].", (long long)a.first, (long long)a.second, (long long)b.first, (long long)b.second); throw std::logic_error(buf); } } }; void sniffer_callback(u_char *_args, const struct pcap_pkthdr *header, const u_char *pkt_data) { #ifndef __SENDER // save the packet into circular buffer rcv_log_info.pcap_tcp_data_mutex.lock(); assert(rcv_log_info.pcap_tcp_data.size() < rcv_log_info.pcap_tcp_data.capacity()); rcv_log_info.pcap_tcp_data.push_back(rcv_log_info_t::pcap_element(header, pkt_data)); rcv_log_info.pcap_tcp_data_mutex.unlock(); #if 0 static bool first_packet = true; const int64_t _now = now(); // // parse packet // const struct ethernethdr* ethernetHdr = (struct ethernethdr*)(pkt_data); assert(ntohs(ethernetHdr->type) == 0x0800); // IP packet const struct iphdr* ipHdr = (struct iphdr*)((int8_t*)ethernetHdr + sizeof(*ethernetHdr)); if(ipHdr->p != 0x06) // TCP packet return; const struct my_tcphdr* tcpHdr = (struct my_tcphdr*)((int8_t*)ipHdr + ip_hl(ipHdr)); const uint32_t tcpPldSize = ntohs(ipHdr->len) - ip_hl(ipHdr) - my_tcphdr_tools::tcp_off(*tcpHdr); assert(14 + ip_hl(ipHdr) + my_tcphdr_tools::tcp_off(*tcpHdr) <= rcv_log_info.pcap_snaplen); const uint32_t seqNr1 = my_tcphdr_tools::tcp_seq(*tcpHdr); /* check for timestamp */ uint32_t tcp_ts = 0; if(my_tcphdr_tools::tcp_off(*tcpHdr) > 5) { uint8_t* opt = (uint8_t*)tcpHdr + sizeof(struct my_tcphdr); while( *opt != 0 ) { tcp_option* _opt = (tcp_option*)opt; if( _opt->kind == 1 /* NOP */ ) { ++opt; // NOP is one byte; continue; } if( _opt->kind == 8 /* TSopt */ ) { assert(_opt->size == 10); tcp_ts = ntohl(*(uint32_t*)(opt+2)); break; } opt += _opt->size; } } assert(tcp_ts != 0); if(first_packet) { //assert(tcp_syn(*tcpHdr)); first_packet = false; //assert(rcv_log_info.ts_first_packet == 0 && rcv_log_info.tcp_ts_first_packet == 0); //rcv_log_info.ts_first_packet = _now; //rcv_log_info.tcp_ts_first_packet = tcp_ts; }/* else if(!tcp_fin(*tcpHdr)) { assert(tcpPldSize > 0); }*/ #endif #if 0 // // sequence number monitoring // /* We only process packets with payload */ if(tcpPldSize > 0) { /* sequence number of the first segment of the TCP flow (sequence number of the SYN packet plus 1). */ static uint32_t seqStart = seqNr1 + 1; /* since a TCP sequence is only 32-bit and * a TCP flow can carry much more (in fact, unlimited) bytes, the sequence number * may overflow and start again from 0. seqRound stores the number of times this happened for * the last byte of the first contiguous range of data starting with the initial sequence number seqStart. */ static int seqRound = 0; /* received sequence numbers */ static set<pair<int64_t, int64_t>, LessThenNonOverlapping> seqOffRcvd; /* calculate the ABSOLUTE sequence number of the last data byte in the received segment. * if segment number space overflows, it can be smaller than the sequence number of the first data byte. */ const uint32_t seqNr2 = ((int64_t)seqNr1 + (int64_t)tcpPldSize - 1) % ((int64_t)std::numeric_limits<uint32_t>::max() + 1); /* if the first byte of the flow was not received yet, seqRound is w.r.t. seqStart. * note that the first byte here means not any byte of the flow but the byte with sequence number seqStart. */ uint32_t seqRef = seqStart; if(seqOffRcvd.empty() || seqOffRcvd.begin()->first > 0) { seqRef = seqStart; } else { seqRef = (seqStart + seqOffRcvd.begin()->second) % ((int64_t)std::numeric_limits<uint32_t>::max() + 1); } uint32_t seqMax = ((uint64_t)seqRef + (uint64_t)1073725440 - 1) % ((uint64_t)std::numeric_limits<uint32_t>::max() + 1); //fprintf(fd, "seqRef: %" PRIu32 ", seqMax: %" PRIu32 ". Got: [%" PRIu32 ", %" PRIu32 "].\n", seqRef, seqMax, seqNr1, seqNr2); /* since sequence numbers are not unique within a TCP flow (they might overflow and start again from 0), * we re-calculate the sequence numbers in offsets relative to the first byte of the flow */ int64_t off1 = (int64_t)seqNr1 - (int64_t)seqStart; int64_t off2 = (int64_t)seqNr2 - (int64_t)seqStart; if( (seqNr1 >= seqRef) || (seqNr1 < seqRef && (seqMax > seqRef || seqMax < seqNr1))) off1 += (int64_t)seqRound * ((int64_t)std::numeric_limits<uint32_t>::max() + (int64_t)1); else off1 += (int64_t)(seqRound + 1) * ((int64_t)std::numeric_limits<uint32_t>::max() + (int64_t)1); if( (seqNr2 >= seqRef) || (seqNr2 < seqRef && (seqMax > seqRef || seqMax < seqNr2))) off2 += (int64_t)seqRound * ((int64_t)std::numeric_limits<uint32_t>::max() + (int64_t)1); else off2 += (int64_t)(seqRound + 1) * ((int64_t)std::numeric_limits<uint32_t>::max() + (int64_t)1); //printf("Translated into offset range [%" PRId64 ", %" PRId64 "]\n", off1, off2); //fprintf(fd, "%10u %10u %10u %12lld %12lld %10u %d\n", (unsigned)seqRef, (unsigned)seqNr1, (unsigned)seqNr2, (long long)off1, (long long)off2, (unsigned)seqMax, seqRound); /* log the received range in the variable seqOffRcvd */ //printf("Segments before insertion:\n"); //for(set<pair<int64_t, int64_t> >::const_iterator it = seqOffRcvd.begin(); it != seqOffRcvd.end(); ++it) // printf("[%lld, %lld]\n", (long long)it->first, (long long)it->second); const pair<int64_t, int64_t> firstRangeBefore = (seqOffRcvd.empty()) ? (pair<int64_t, int64_t>(-1, -1)) : (*(seqOffRcvd.begin())); typedef set<pair<int64_t, int64_t> >::iterator IteratorType; list<IteratorType> toBeErased; pair<int64_t, int64_t> toBeInserted; merge(seqOffRcvd.begin(), seqOffRcvd.end(), pair<int64_t, int64_t>(off1, off2), toBeErased, toBeInserted); for(list<IteratorType>::const_iterator it = toBeErased.begin(); it != toBeErased.end(); ++it) { //printf("Erasing [%" PRId64 ", %" PRId64 "].\n", (*it)->first, (*it)->second); seqOffRcvd.erase(*it); } if(toBeInserted.first <= toBeInserted.second) { //printf("Inserting [%" PRId64 ", %" PRId64 "].\n", toBeInserted.first, toBeInserted.second); if(!seqOffRcvd.insert(toBeInserted).second) {printf("Bug in %s:%d.\n", __FILE__, __LINE__); abort();} } /* Did we update the first range? */ //if(*(seqOffRcvd.begin()) != firstRangeBefore) // firstRangeUpdated = true; /* update sequence round if necessary */ if(seqOffRcvd.begin()->first == 0 && (seqStart + seqOffRcvd.begin()->second) % ((int64_t)std::numeric_limits<uint32_t>::max() + 1) < seqRef) { ++seqRound; //fprintf(fd, "seqRound incremented\n"); } //printf("Segments after insertion:\n"); //for(set<pair<int64_t, int64_t> >::const_iterator it = seqOffRcvd.begin(); it != seqOffRcvd.end(); ++it) // fprintf(fd, "[%lld, %lld]\n", (long long)it->first, (long long)it->second); /* search for missing packets */ int64_t seq_missing = 0; if(seqOffRcvd.size() > 1) { set<pair<int64_t, int64_t> >::const_iterator it = seqOffRcvd.begin(); ++it; for(; it != seqOffRcvd.end(); ++it) { set<pair<int64_t, int64_t> >::const_iterator it_prev = it; --it_prev; seq_missing += it->first - it_prev->second - 1; } } } #endif // // logging BEGIN // #if 0 rcv_log_info.mutex.lock(); // initialization if(rcv_log_info.index == -1) rcv_log_info.index = (_now - rcv_log_info.ts_first_packet) / rcv_log_info.dt; // integer division if(rcv_log_info.delay_vec.capacity() == 0) rcv_log_info.delay_vec.reserve(1048576); if(rcv_log_info.missing_vec.capacity() == 0) rcv_log_info.missing_vec.reserve(1048576); if(rcv_log_info.dt > 0 && _now >= rcv_log_info.ts_first_packet + (1 + rcv_log_info.index) * rcv_log_info.dt) { rcv_log_output(); rcv_log_info.index = (_now - rcv_log_info.ts_first_packet) / rcv_log_info.dt; // integer division } assert(rcv_log_info.delay_vec.size() < rcv_log_info.delay_vec.capacity() && rcv_log_info.missing_vec.size() < rcv_log_info.missing_vec.capacity()); rcv_log_info.delay_vec.push_back((_now - rcv_log_info.ts_first_packet) - 4000 * (tcp_ts - rcv_log_info.tcp_ts_first_packet)); rcv_log_info.missing_vec.push_back(seq_missing); if(rcv_log_info.off1 == 0) rcv_log_info.off1 = off1; rcv_log_info.off2 = off2; if(rcv_log_info.dt == 0) { rcv_log_info.index = _now; rcv_log_output(); } rcv_log_info.mutex.unlock(); #endif // // logging END // #endif } void radiotap_callback(u_char *_args, const struct pcap_pkthdr *header, const u_char *pkt_data) { #ifndef __SENDER // save the packet into circular buffer rcv_log_info.pcap_rdtap_data_mutex.lock(); assert(rcv_log_info.pcap_rdtap_data.size() < rcv_log_info.pcap_rdtap_data.capacity()); rcv_log_info.pcap_rdtap_data.push_back(rcv_log_info_t::pcap_element(header, pkt_data)); rcv_log_info.pcap_rdtap_data_mutex.unlock(); #endif } bool stop_pcap_tcp_dumper = false; void* run_pcap_tcp_dumper(void* args) { /* prepare pcap output file */ char fn_pcap[4096]; sprintf(fn_pcap, "%s/rcv_tcp_pcap_%016" PRId64 ".pcap", traceDir.c_str(), t_start_receiver); rcv_log_info.pcap_dumper_tcp = pcap_dump_open(rcv_log_info.pcap_tcp, fn_pcap); assert(rcv_log_info.pcap_dumper_tcp != NULL); while(true) { rcv_log_info.pcap_tcp_data_mutex.lock(); const bool has_data = !rcv_log_info.pcap_tcp_data.empty(); rcv_log_info.pcap_tcp_data_mutex.unlock(); if(has_data) { //save the packet on the dump file pcap_dump((u_char*)rcv_log_info.pcap_dumper_tcp, &rcv_log_info.pcap_tcp_data.front().pkthdr, rcv_log_info.pcap_tcp_data.front().pktdata); rcv_log_info.pcap_tcp_data_mutex.lock(); rcv_log_info.pcap_tcp_data.pop_front(); rcv_log_info.pcap_tcp_data_mutex.unlock(); } else if(stop_pcap_tcp_dumper) { break; } else { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10000; nanosleep(&ts, NULL); } } /* close pcap output file */ pcap_dump_close(rcv_log_info.pcap_dumper_tcp); return NULL; } void* runSniffer(void* _args) { #ifndef __SENDER char errbuf[PCAP_ERRBUF_SIZE]; printf("Sniffing on device: %s\n", rcv_info.dev_name.c_str()); rcv_log_info.pcap_tcp = pcap_open_live(rcv_info.dev_name.c_str(), rcv_log_info.pcap_snaplen, 0, 100, errbuf); if(!rcv_log_info.pcap_tcp) { printf("Error: %s.\n", errbuf); return NULL; } else if(errbuf[0]) { printf("Warning: %s.\n", errbuf); } /* create and apply a filter expression */ { std::ostringstream oss; if(global_info.ifActive) { oss << "tcp and src host " << global_info.psvIp << " and src port " << global_info.psvPort; } else { oss << "tcp and dst host " << global_info.psvIp << " and dst port " << global_info.psvPort; } struct bpf_program filter; int ret = pcap_compile(rcv_log_info.pcap_tcp, &filter, oss.str().c_str(), 0, PCAP_NETMASK_UNKNOWN); if(ret != 0) { printf("Failed to compile the filter expression: %s.\n", oss.str().c_str()); return NULL; } ret = pcap_setfilter(rcv_log_info.pcap_tcp, &filter); if(ret != 0) { printf("Failed to apply the filter expression: %s.\n", oss.str().c_str()); return NULL; } pcap_freecode(&filter); } /* start dumper */ pthread_t pcap_tcp_dumper_thread; stop_pcap_tcp_dumper = false; assert(0 == pthread_create(&pcap_tcp_dumper_thread, NULL, &run_pcap_tcp_dumper, NULL)); int ret = pcap_loop(rcv_log_info.pcap_tcp, -1, sniffer_callback, NULL); /* stop dumper */ stop_pcap_tcp_dumper = true; assert(0 == pthread_join(pcap_tcp_dumper_thread, NULL)); /* close pcap */ pcap_close(rcv_log_info.pcap_tcp); #endif return NULL; } bool stop_pcap_rdtap_dumper = false; void* run_pcap_rdtap_dumper(void* args) { /* prepare pcap output file */ char fn_pcap[4096]; sprintf(fn_pcap, "%s/rcv_rdtap_pcap_%016" PRId64 ".pcap", traceDir.c_str(), t_start_receiver); rcv_log_info.pcap_dumper_rdtap = pcap_dump_open(rcv_log_info.pcap_rdtap, fn_pcap); assert(rcv_log_info.pcap_dumper_rdtap != NULL); while(true) { rcv_log_info.pcap_rdtap_data_mutex.lock(); const bool has_data = !rcv_log_info.pcap_rdtap_data.empty(); rcv_log_info.pcap_rdtap_data_mutex.unlock(); if(has_data) { //save the packet on the dump file pcap_dump((u_char*)rcv_log_info.pcap_dumper_rdtap, &rcv_log_info.pcap_rdtap_data.front().pkthdr, rcv_log_info.pcap_rdtap_data.front().pktdata); rcv_log_info.pcap_rdtap_data_mutex.lock(); rcv_log_info.pcap_rdtap_data.pop_front(); rcv_log_info.pcap_rdtap_data_mutex.unlock(); } else if(stop_pcap_rdtap_dumper) { break; } else { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10000; nanosleep(&ts, NULL); } } /* close pcap output file */ pcap_dump_close(rcv_log_info.pcap_dumper_rdtap); return NULL; } void* runRadiotap(void* _args) { #ifndef __SENDER char errbuf[PCAP_ERRBUF_SIZE]; printf("Sniffing on device: %s\n", rcv_info.dev_name_mon.c_str()); rcv_log_info.pcap_rdtap = pcap_open_live(rcv_info.dev_name_mon.c_str(), rcv_log_info.radiotap_snaplen, 1, 100, errbuf); if(!rcv_log_info.pcap_rdtap) { printf("Error: %s.\n", errbuf); return NULL; } else if(errbuf[0]) { printf("Warning: %s.\n", errbuf); } /* start dumper */ pthread_t pcap_rdtap_dumper_thread; stop_pcap_rdtap_dumper = false; assert(0 == pthread_create(&pcap_rdtap_dumper_thread, NULL, &run_pcap_rdtap_dumper, NULL)); int ret = pcap_loop(rcv_log_info.pcap_rdtap, -1, radiotap_callback, NULL); /* stop dumper */ stop_pcap_rdtap_dumper = true; assert(0 == pthread_join(pcap_rdtap_dumper_thread, NULL)); /* close pcap */ pcap_close(rcv_log_info.pcap_rdtap); #endif return NULL; } void signalHandler(int sig) { assert((sig == SIGINT || sig == SIGTERM || sig == SIGALRM) && !globalTerminationFlag); printf("Got signal %d. Terminating.\n", sig); globalTerminationFlag = true; } int64_t now() { struct timeval tv; assert(0 == gettimeofday(&tv, NULL)); return (int64_t)tv.tv_sec * (int64_t)1000000 + (int64_t)tv.tv_usec; } void recordTcpState(int fd, const char* reason, FILE* f) { static std::mutex logMutex; static struct tcp_info tcpInfo; logMutex.lock(); memset(&tcpInfo, 0, sizeof(tcpInfo)); socklen_t len = sizeof(tcpInfo); assert(0 == getsockopt(fd, SOL_TCP, TCP_INFO, &tcpInfo, &len) && len == sizeof(tcpInfo)); //if(0 != memcmp(&tcpInfo, &lastTcpInfo, sizeof(struct tcp_info))) { recordTcpState(f, tcpInfo, now(), reason); tcp_logger_info.lastTcpInfo = tcpInfo; //} logMutex.unlock(); } void recordTcpState(FILE* f, const struct tcp_info& tcpInfo, const int64_t t, const char* reason) { fprintf(f, "%17" PRId64 " %17s %19s %19s %13u %8u %9u %9u %12u %12u % 11.6f %9u %9u %9u %9u %8u %8u %9u %9u %16u %15u %16u %15u %8u %14u % 11.6f % 10.6f %14u %10u %8u %12u %9u %11u %15u\n", t, reason, tcpState2String(tcpInfo.tcpi_state).c_str(), tcpCAState2String(tcpInfo.tcpi_ca_state).c_str(), tcpInfo.tcpi_retransmits, tcpInfo.tcpi_probes, tcpInfo.tcpi_backoff, tcpInfo.tcpi_options, tcpInfo.tcpi_snd_wscale, tcpInfo.tcpi_rcv_wscale, tcpInfo.tcpi_rto / 1e6, tcpInfo.tcpi_ato, tcpInfo.tcpi_snd_mss, tcpInfo.tcpi_rcv_mss, tcpInfo.tcpi_unacked, tcpInfo.tcpi_sacked, tcpInfo.tcpi_lost, tcpInfo.tcpi_retrans, tcpInfo.tcpi_fackets, tcpInfo.tcpi_last_data_sent, tcpInfo.tcpi_last_ack_sent, tcpInfo.tcpi_last_data_recv, tcpInfo.tcpi_last_ack_recv, tcpInfo.tcpi_pmtu, tcpInfo.tcpi_rcv_ssthresh, tcpInfo.tcpi_rtt / 1e6, tcpInfo.tcpi_rttvar / 1e6, tcpInfo.tcpi_snd_ssthresh, tcpInfo.tcpi_snd_cwnd, tcpInfo.tcpi_advmss, tcpInfo.tcpi_reordering, tcpInfo.tcpi_rcv_rtt, tcpInfo.tcpi_rcv_space, tcpInfo.tcpi_total_retrans); } string tcpState2String(int tcpState) { switch(tcpState) { case TCP_ESTABLISHED: return "TCP_ESTABLISHED"; case TCP_SYN_SENT: return "TCP_SYN_SENT"; case TCP_SYN_RECV: return "TCP_SYN_RECV"; case TCP_FIN_WAIT1: return "TCP_FIN_WAIT1"; case TCP_FIN_WAIT2: return "TCP_FIN_WAIT2"; case TCP_TIME_WAIT: return "TCP_TIME_WAIT"; case TCP_CLOSE: return "TCP_CLOSE"; case TCP_CLOSE_WAIT: return "TCP_CLOSE_WAIT"; case TCP_LAST_ACK: return "TCP_LAST_ACK"; case TCP_LISTEN: return "TCP_LISTEN"; case TCP_CLOSING: return "TCP_CLOSING"; default: throw "Unrecognized TCP state."; } } string tcpCAState2String(int tcpCAState) { switch(tcpCAState) { case TCP_CA_Open: return "TCP_CA_Open"; case TCP_CA_Disorder: return "TCP_CA_Disorder"; case TCP_CA_CWR: return "TCP_CA_CWR"; case TCP_CA_Recovery: return "TCP_CA_Recovery"; case TCP_CA_Loss: return "TCP_CA_Loss"; default: throw "Unrecognized TCP CA state."; } } #if 0 void rcv_log_output() { assert(rcv_log_info.ts_first_packet > 0); if(rcv_log_info.dt == 0) { assert(rcv_log_info.delay_vec.size() <= 1 && rcv_log_info.missing_vec.size() <= 1); //'time [us] | bytes [byte] | delay [s] | missing bytes [byte] |' fprintf(rcv_log_info.f, "%" PRId64 " %" PRId64 " %.6f %10d\n", rcv_log_info.index, rcv_log_info.num_bytes, rcv_log_info.delay_vec.empty() ? std::numeric_limits<double>::quiet_NaN() : rcv_log_info.delay_vec.at(0), rcv_log_info.missing_vec.empty() ? std::numeric_limits<int>::quiet_NaN() : rcv_log_info.missing_vec.at(0)); } else { std::sort(rcv_log_info.delay_vec.begin(), rcv_log_info.delay_vec.end()); //const int64_t index = rcv_log_info.tic / rcv_log_info.dt; const double thrpt_mbps = 8.0 * rcv_log_info.num_bytes / double(rcv_log_info.dt); double delay_min_s, delay_max_s, delay_mean_s, delay_median_s, delay_var; delay_min_s = delay_max_s = delay_mean_s = delay_median_s = delay_var = std::numeric_limits<double>::quiet_NaN(); if(!rcv_log_info.delay_vec.empty()) { delay_min_s = rcv_log_info.delay_vec.front() / 1e6; delay_max_s = rcv_log_info.delay_vec.back() / 1e6; delay_mean_s = std::accumulate(rcv_log_info.delay_vec.begin(), rcv_log_info.delay_vec.end(), 0.0) / rcv_log_info.delay_vec.size() / 1e6; delay_median_s = (rcv_log_info.delay_vec.size() % 2 == 0) ? 0.5 * (rcv_log_info.delay_vec.at(rcv_log_info.delay_vec.size() / 2 - 1) + rcv_log_info.delay_vec.at(rcv_log_info.delay_vec.size() / 2)) / 1e6 : rcv_log_info.delay_vec.at(rcv_log_info.delay_vec.size() / 2) / 1e6; if(rcv_log_info.delay_vec.size() == 1) { delay_var = 0; } else { double _sqr_sum = std::inner_product(rcv_log_info.delay_vec.begin(), rcv_log_info.delay_vec.end(), rcv_log_info.delay_vec.begin(), 0.0); delay_var = rcv_log_info.delay_vec.size() / (rcv_log_info.delay_vec.size() - 1.0) * (_sqr_sum / rcv_log_info.delay_vec.size() / 1e12 - delay_mean_s * delay_mean_s); } } //'index | thrpt [Mbps] | delay [s]: min | max | mean | median | var | missing bytes: max |' fprintf(rcv_log_info.f, "%7" PRId64 " %14.6f %16.6f %13.6f %14.6f %16.6f %12.6f %19d\n", rcv_log_info.index, thrpt_mbps, delay_min_s, delay_max_s, delay_mean_s, delay_median_s, delay_var, *std::max_element(rcv_log_info.missing_vec.begin(), rcv_log_info.missing_vec.end())); } #if 0 if(tcpPldSize <= 0) // this is only for SYN and FIN packets fprintf(file_sniffer, "%" PRId64 " %" PRIu32 " %" PRId64 " %" PRId64 " %" PRId64 "\n", _now, tcp_ts, (int64_t)-1, (int64_t)-1, seq_missing); else fprintf(file_sniffer, "%" PRId64 " %" PRIu32 " %" PRId64 " %" PRId64 " %" PRId64 "\n", _now, tcp_ts, off1, off2, seq_missing); #endif rcv_log_info.reset(); } #endif string getTimeString(int64_t t, bool showDate) { static char buf[1024]; time_t _t; int64_t usecs = 0; if(t == 0) { int64_t absTime = now(); _t = absTime / 1000000; usecs = absTime % 1000000; } else { _t = t / 1000000; usecs = t % 1000000; } struct tm T; localtime_r(&_t, &T); if(showDate) assert(strftime(buf, 1024, "%d.%m.%Y %H:%M:%S", &T) + 2 < 1024); // + 2 in order to ensure that nothing was truncated else assert(strftime(buf, 1024, "%H:%M:%S", &T) + 2 < 1024); // + 2 in order to ensure that nothing was truncated sprintf(buf + strlen(buf), ".%06" PRId64, usecs); return string(buf); } string get_dev_for_ip(string ip) { struct ifaddrs* if_list = NULL; assert(0 == getifaddrs(&if_list) && if_list != NULL); struct ifaddrs* it = if_list; while(it != NULL) { if(inet_addr(get_ip_for_dev(it->ifa_name).c_str()) == inet_addr(ip.c_str())) { string ret(it->ifa_name); freeifaddrs(if_list); return ret; } it = it->ifa_next; } throw std::runtime_error("Could not find network device for IP: " + ip); } bool wait_for_dev(string dev, int64_t max_wait) { printf("Waiting for device %s to become available. Max. waiting time: %.2f s.\n", dev.c_str(), max_wait / 1e6); bool first_check = true; const int64_t t0 = now(); do { if(!first_check) sleep(1); else first_check = false; const int fd = socket(AF_INET, SOCK_DGRAM, 0); struct ifreq ifr; ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name, dev.c_str(), IFNAMSIZ-1); const int ret = ioctl(fd, SIOCGIFADDR, &ifr); close(fd); if(ret == 0) return true; } while(now() - t0 < max_wait); return false; } string get_ip_for_dev(string dev) { const int fd = socket(AF_INET, SOCK_DGRAM, 0); struct ifreq ifr; ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name, dev.c_str(), IFNAMSIZ-1); if(-1 == ioctl(fd, SIOCGIFADDR, &ifr)) { perror("ioctl()"); abort(); } close(fd); return inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr); } #if 0 string get_ip_for_dev(string dev) { struct ifaddrs* if_list = NULL; assert(0 == getifaddrs(&if_list) && if_list != NULL); struct ifaddrs* it = if_list; while(it != NULL) { if(it->ifa_addr->sa_family != AF_INET) { it = it->ifa_next; continue; } if(0 == strcmp(dev.c_str(), it->ifa_name)) { struct sockaddr_in* sockaddr_in = (struct sockaddr_in*)it->ifa_addr; string ip(inet_ntoa(sockaddr_in->sin_addr)); freeifaddrs(if_list); return ip; } it = it->ifa_next; } throw std::runtime_error("Could not find IP address for device: " + dev + ". Please make sure the device is up and running."); } #endif void parse_request_pattern(const char* request_pattern) { rcv_info.request_pattern = request_pattern; if(0 == strncmp(request_pattern, "deterministic:", 14)) // deterministic:<ON duration, integer, [ms]>:<OFF duration, integer, [ms]> { rcv_info.request_pattern_type = rcv_info.DETERMINISTIC; char* endptr = NULL; rcv_info.request_pattern_deterministic.on_duration = 1000 * strtol(request_pattern + 14, &endptr, 10); assert(endptr && endptr[0] == ':'); rcv_info.request_pattern_deterministic.off_duration = 1000 * strtol(endptr + 1, &endptr, 10); assert(endptr[0] == '\0'); } else if(0 == strncmp(request_pattern, "normal:", 7)) // normal:<mean, integer, [ms]>:<std, integer, [ms]>:<min, integer, [ms]>:<max, integer, [ms]>:<segment duration, integer, [ms]> { rcv_info.request_pattern_type = rcv_info.NORMAL; char* endptr = NULL; rcv_info.request_pattern_normal.mean = 1000 * strtol(request_pattern + 7, &endptr, 10); assert(endptr && endptr[0] == ':'); rcv_info.request_pattern_normal.std = 1000 * strtol(endptr + 1, &endptr, 10); assert(endptr && endptr[0] == ':'); rcv_info.request_pattern_normal.min = 1000 * strtol(endptr + 1, &endptr, 10); assert(endptr && endptr[0] == ':'); rcv_info.request_pattern_normal.max = 1000 * strtol(endptr + 1, &endptr, 10); assert(endptr && endptr[0] == ':'); rcv_info.request_pattern_normal.tau = 1000 * strtol(endptr + 1, &endptr, 10); assert(endptr[0] == '\0'); if(rcv_info.request_pattern_normal.mean <= 0 || rcv_info.request_pattern_normal.std <= 0 || rcv_info.request_pattern_normal.min > rcv_info.request_pattern_normal.mean || rcv_info.request_pattern_normal.max < rcv_info.request_pattern_normal.mean || rcv_info.request_pattern_normal.tau < rcv_info.request_pattern_normal.mean) { throw std::runtime_error("Invalid request pattern: " + string(request_pattern)); } } else { throw std::runtime_error("Invalid request pattern: " + string(request_pattern)); } } #if 0 void* run_flusher(void* _args) { while(!globalTerminationFlag) { std::fflush(NULL); sleep(1); } return NULL; } #endif
39.031935
286
0.615077
[ "vector" ]
f836f2c80c92452a31bccac3cb861306222b6609
2,348
cpp
C++
src/utils/io.cpp
momo5502/t7x
2864e73de494827ec32df1cb709d9bfd99b6314d
[ "MIT" ]
13
2020-03-29T13:07:25.000Z
2022-01-29T03:09:25.000Z
src/utils/io.cpp
momo5502/w3x
a684c0378e1b64b29e1e9709c9be4b947d511775
[ "MIT" ]
10
2021-12-10T05:20:53.000Z
2022-03-28T05:22:52.000Z
src/utils/io.cpp
momo5502/w3x
a684c0378e1b64b29e1e9709c9be4b947d511775
[ "MIT" ]
1
2020-05-10T17:11:06.000Z
2020-05-10T17:11:06.000Z
#include <std_include.hpp> #include "io.hpp" namespace utils::io { bool file_exists(const std::string& file) { return std::ifstream(file).good(); } bool write_file(const std::string& file, const std::string& data, const bool append) { const auto pos = file.find_last_of("/\\"); if (pos != std::string::npos) { create_directory(file.substr(0, pos)); } std::ofstream stream( file, std::ios::binary | std::ofstream::out | (append ? std::ofstream::app : 0)); if (stream.is_open()) { stream.write(data.data(), data.size()); stream.close(); return true; } return false; } std::string read_file(const std::string& file) { std::string data; read_file(file, &data); return data; } bool read_file(const std::string& file, std::string* data) { if (!data) return false; data->clear(); if (file_exists(file)) { std::ifstream stream(file, std::ios::binary); if (!stream.is_open()) return false; stream.seekg(0, std::ios::end); const std::streamsize size = stream.tellg(); stream.seekg(0, std::ios::beg); if (size > -1) { data->resize(static_cast<uint32_t>(size)); stream.read(const_cast<char*>(data->data()), size); stream.close(); return true; } } return false; } size_t file_size(const std::string& file) { if (file_exists(file)) { std::ifstream stream(file, std::ios::binary); if (stream.good()) { stream.seekg(0, std::ios::end); return static_cast<size_t>(stream.tellg()); } } return 0; } bool create_directory(const std::string& directory) { return std::filesystem::create_directories(directory); } bool directory_exists(const std::string& directory) { return std::filesystem::is_directory(directory); } bool directory_is_empty(const std::string& directory) { return std::filesystem::is_empty(directory); } std::vector<std::string> list_files(const std::string& directory) { std::vector<std::string> files; for (auto& file : std::filesystem::directory_iterator(directory)) { files.push_back(file.path().generic_string()); } return files; } void copy_folder(const std::filesystem::path& src, const std::filesystem::path& target) { std::filesystem::copy(src, target, std::filesystem::copy_options::overwrite_existing | std::filesystem::copy_options::recursive); } }
20.778761
131
0.659284
[ "vector" ]
f8381e9254f1b7bb94cc155cfdd371451a6932a5
493
cpp
C++
abc178/c.cpp
magurotuna/atcoder-submissions-cpp
afbf5df2f22bcd17d8ad580d3c143602d9af7398
[ "CC0-1.0" ]
null
null
null
abc178/c.cpp
magurotuna/atcoder-submissions-cpp
afbf5df2f22bcd17d8ad580d3c143602d9af7398
[ "CC0-1.0" ]
null
null
null
abc178/c.cpp
magurotuna/atcoder-submissions-cpp
afbf5df2f22bcd17d8ad580d3c143602d9af7398
[ "CC0-1.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; using ll = long long int; ll modpow(ll a, ll n, ll mod) { ll res = 1; while (n > 0) { if (n % 2 != 0) res = res * a % mod; a = a * a % mod; n /= 2; } return res; } const ll mod = 1e9 + 7; int main() { int N; cin >> N; ll ans = modpow(10, N, mod) - (2 * modpow(9, N, mod)) + modpow(8, N, mod); ans %= mod; ans = (ans + mod) % mod; cout << ans << endl; }
16.433333
76
0.515213
[ "vector" ]
f839ad2e35d11fce68027ebda8297a99e1e60bab
7,119
cc
C++
LiquidCore/src/main/cpp/jni_process.cc
vivocha/LiquidCore
8fdc3abc4a7a4601ae9049f163b6b9debd2eb9a4
[ "MIT" ]
null
null
null
LiquidCore/src/main/cpp/jni_process.cc
vivocha/LiquidCore
8fdc3abc4a7a4601ae9049f163b6b9debd2eb9a4
[ "MIT" ]
null
null
null
LiquidCore/src/main/cpp/jni_process.cc
vivocha/LiquidCore
8fdc3abc4a7a4601ae9049f163b6b9debd2eb9a4
[ "MIT" ]
1
2020-05-04T22:27:52.000Z
2020-05-04T22:27:52.000Z
/* * Copyright (c) 2018 Eric Lange * * Distributed under the MIT License. See LICENSE.md at * https://github.com/LiquidPlayer/LiquidCore for terms and conditions. */ #include "node.h" #include <jni.h> #include <string.h> #include "JNI/JNI.h" #include "JSC/JSC.h" #include "node_instance.h" #undef NATIVE #define NATIVE(package,rt,f) extern "C" JNIEXPORT \ rt JNICALL Java_org_liquidplayer_node_##package##_##f #undef PARAMS #define PARAMS JNIEnv* env, jobject thiz struct AndroidInstance : NodeInstance { AndroidInstance(JNIEnv *env, jobject thiz) { if (!s_jvm) env->GetJavaVM(&s_jvm); m_JavaThis = env->NewGlobalRef(thiz); } ~AndroidInstance() { JNIEnv *env; int getEnvStat = s_jvm->GetEnv((void**)&env, JNI_VERSION_1_6); if (getEnvStat == JNI_EDETACHED) { s_jvm->AttachCurrentThread(&env, nullptr); } env->DeleteGlobalRef(m_JavaThis); if (getEnvStat == JNI_EDETACHED) { s_jvm->DetachCurrentThread(); } } void spawnedThread(); void NotifyStart(JSContextRef ctxRef, JSContextGroupRef groupRef); jobject m_JavaThis; static JavaVM *s_jvm; }; static std::mutex s_instance_mutex; static std::map<std::thread::id, AndroidInstance*> s_instances; void AndroidInstance::spawnedThread() { { std::unique_lock<std::mutex> lock(s_instance_mutex); s_instances[std::this_thread::get_id()] = this; } enum { kMaxArgs = 64 }; char cmd[60]; setenv("NODE_PATH", "/home/node_modules", true); strcpy(cmd, "node -e global.__nodedroid_onLoad();"); int argc = 0; char *argv[kMaxArgs]; char *p2 = strtok(cmd, " "); while (p2 && argc < kMaxArgs-1) { argv[argc++] = p2; p2 = strtok(0, " "); } argv[argc] = 0; int ret = node::Start(argc, argv); { std::unique_lock<std::mutex> lock(s_instance_mutex); s_instances.erase(std::this_thread::get_id()); } JNIEnv *env; int getEnvStat = s_jvm->GetEnv((void**)&env, JNI_VERSION_1_6); if (getEnvStat == JNI_EDETACHED) { s_jvm->AttachCurrentThread(&env, nullptr); } jclass cls = env->GetObjectClass(m_JavaThis); jmethodID mid; do { mid = env->GetMethodID(cls,"onNodeExit","(J)V"); if (!env->ExceptionCheck()) break; env->ExceptionClear(); jclass super = env->GetSuperclass(cls); env->DeleteLocalRef(cls); if (super == NULL || env->ExceptionCheck()) { if (super != NULL) env->DeleteLocalRef(super); if (getEnvStat == JNI_EDETACHED) { s_jvm->DetachCurrentThread(); } return; } cls = super; } while (true); env->DeleteLocalRef(cls); env->CallVoidMethod(m_JavaThis, mid, (jlong)ret); env->DeleteGlobalRef(m_JavaThis); if (getEnvStat == JNI_EDETACHED) { s_jvm->DetachCurrentThread(); } } void AndroidInstance::NotifyStart(JSContextRef ctxRef, JSContextGroupRef groupRef) { JNIEnv *jenv; int getEnvStat = s_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6); if (getEnvStat == JNI_EDETACHED) { s_jvm->AttachCurrentThread(&jenv, nullptr); } jclass cls = jenv->GetObjectClass(m_JavaThis); jmethodID mid; do { mid = jenv->GetMethodID(cls,"onNodeStarted","(JJJ)V"); if (!jenv->ExceptionCheck()) break; jenv->ExceptionClear(); jclass super = jenv->GetSuperclass(cls); jenv->DeleteLocalRef(cls); if (super == nullptr || jenv->ExceptionCheck()) { if (super != nullptr) jenv->DeleteLocalRef(super); if (getEnvStat == JNI_EDETACHED) { s_jvm->DetachCurrentThread(); } __android_log_assert("FAIL","NotifyStart","This is bad"); } cls = super; } while (true); jenv->DeleteLocalRef(cls); auto group = const_cast<OpaqueJSContextGroup*>(groupRef); jenv->CallVoidMethod(m_JavaThis, mid, SharedWrap<JSContext>::New(ctxRef->Context()), SharedWrap<ContextGroup>::New(group->ContextGroup::shared_from_this()), reinterpret_cast<jlong>(ctxRef) ); if (getEnvStat == JNI_EDETACHED) { s_jvm->DetachCurrentThread(); } } v8::Local<v8::Context> NodeInstance::NewContext(v8::Isolate *isolate, JSContextGroupRef groupRef, JSGlobalContextRef *ctxRef) { v8::EscapableHandleScope scope(isolate); JSGlobalContextRef dummy; if (!ctxRef) ctxRef = &dummy; JSClassRef globalClass = nullptr; { JSClassDefinition definition = kJSClassDefinitionEmpty; definition.attributes |= kJSClassAttributeNoAutomaticPrototype; globalClass = JSClassCreate(&definition); *ctxRef = JSGlobalContextCreateInGroup(groupRef, globalClass); } JSClassRelease(globalClass); auto java_node_context = (*ctxRef)->Context(); v8::Local<v8::Context> context = java_node_context->Value(); return scope.Escape(context); } JSContextGroupRef NodeInstance::GroupFromIsolate(v8::Isolate *isolate, uv_loop_t* event_loop) { return &* OpaqueJSContextGroup::New(isolate, event_loop); } void NodeInstance::NotifyStart(JSContextRef ctxRef, JSContextGroupRef groupRef) { AndroidInstance * thiz; { std::unique_lock<std::mutex> lock(s_instance_mutex); thiz = s_instances[std::this_thread::get_id()]; } thiz->NotifyStart(ctxRef, groupRef); } JavaVM * AndroidInstance::s_jvm(nullptr); NATIVE(Process,jlong,start) (PARAMS) { auto instance = new AndroidInstance(env, thiz); return reinterpret_cast<jlong>(instance); } NATIVE(Process,void,runInThread) (PARAMS, jlong ref) { auto instance = reinterpret_cast<AndroidInstance*>(ref); instance->spawnedThread(); } NATIVE(Process,void,dispose) (PARAMS, jlong ref) { delete reinterpret_cast<NodeInstance*>(ref); } NATIVE(Process,void,setFileSystem) (PARAMS, jlong contextRef, jlong fsObjectRef) { auto ctx = SharedWrap<JSContext>::Shared(contextRef); if (!ISPOINTER(fsObjectRef)) { __android_log_assert("!ISPOINTER", "setFileSystem", "SharedWrap<JSValue> is not a pointer"); } auto fs = SharedWrap<JSValue>::Shared(boost::shared_ptr<JSContext>(),fsObjectRef); V8_ISOLATE_CTX(ctx,isolate,context) Local<Object> globalObj = context->Global(); Local<Object> fsObj = fs->Value()->ToObject(context).ToLocalChecked(); Local<Private> privateKey = v8::Private::ForApi(isolate, String::NewFromUtf8(isolate, "__fs")); auto success = globalObj->SetPrivate(context, privateKey, fsObj).FromJust(); V8_UNLOCK(); } extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) { ContextGroup::init_icu(); node::InitializeNode(); return JNI_VERSION_1_6; } extern "C" jlong JNICALL Java_org_liquidplayer_javascript_JSContext_getPlatform (JNIEnv* env, jclass klass) { return reinterpret_cast<jlong>(node::GetPlatform()); }
29.786611
107
0.640118
[ "object" ]
f83a36b078cb2fe3c45b5e2ecad17e4b21814eb0
6,331
cpp
C++
tests/test_gstate_translator.cpp
MathewRGB/BlaEngine
fd64b7e8b54efad09f6466c6cb47ee920dc445f7
[ "MIT" ]
1
2019-12-06T00:42:54.000Z
2019-12-06T00:42:54.000Z
tests/test_gstate_translator.cpp
MathewRGB/BlaEngine
fd64b7e8b54efad09f6466c6cb47ee920dc445f7
[ "MIT" ]
null
null
null
tests/test_gstate_translator.cpp
MathewRGB/BlaEngine
fd64b7e8b54efad09f6466c6cb47ee920dc445f7
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "helper_for_tests.h" #include "source/calculation/gstate_translator.h" using namespace blaengine::calculation; TEST(Calculator, test_set_fen_string) { auto translator = GSateTranslator(); auto gstate_controller = GameStateController(); GameState& current_game_state = gstate_controller.current_game_state; auto fen = "r2r2k1/pppqbppp/1nn1p3/8/1PPPN3/P3BN2/4QPPP/3R1RK1 b - b3 0 15"; current_game_state = translator.interpretAndSetFen(fen); auto comp_gstate_controller = GameStateController(); GameState& comp_game_state = comp_gstate_controller.current_game_state; comp_game_state.board[3] = 'R'; comp_game_state.board[5] = 'R'; comp_game_state.board[6] = 'K'; comp_game_state.board[12] = 'Q'; comp_game_state.board[13] = 'P'; comp_game_state.board[14] = 'P'; comp_game_state.board[15] = 'P'; comp_game_state.board[16] = 'P'; comp_game_state.board[20] = 'B'; comp_game_state.board[21] = 'N'; comp_game_state.board[25] = 'P'; comp_game_state.board[26] = 'P'; comp_game_state.board[27] = 'P'; comp_game_state.board[28] = 'N'; comp_game_state.board[41] = 'n'; comp_game_state.board[42] = 'n'; comp_game_state.board[44] = 'p'; comp_game_state.board[48] = 'p'; comp_game_state.board[49] = 'p'; comp_game_state.board[50] = 'p'; comp_game_state.board[51] = 'q'; comp_game_state.board[52] = 'b'; comp_game_state.board[53] = 'p'; comp_game_state.board[54] = 'p'; comp_game_state.board[55] = 'p'; comp_game_state.board[56] = 'r'; comp_game_state.board[59] = 'r'; comp_game_state.board[62] = 'k'; comp_game_state.en_passant_field = 17; comp_game_state.half_moves_for_draw = 0; comp_game_state.next_turn = Color::black; comp_game_state.next_half_move = 30; ASSERT_TRUE(compare_game_states(current_game_state, comp_game_state)); } TEST(Calculator, test_set_game_state_2_moves) { auto comparison_fen = "rnbqkbnr/pppp1ppp/4p3/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2"; auto fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; vector<string> moves{"e2e4", "e7e6"}; auto comp_translator = GSateTranslator(); auto comp_gstate_controller = GameStateController(); auto& comp_game_state = comp_gstate_controller.current_game_state; comp_game_state = comp_translator.interpretAndSetFen(comparison_fen); auto translator = GSateTranslator(); auto gstate_controller = GameStateController(); auto& game_state = gstate_controller.current_game_state; game_state = translator.interpretAndSetFen(fen); game_state = translator.makeMovesFromFieldStrings(game_state, moves); ASSERT_TRUE(compare_game_states(game_state, comp_game_state)); } TEST(GSateTranslator, test_set_game_state_29_moves) { auto comparison_fen = "r2r2k1/pppqbppp/1nn1p3/8/1PPPN3/P3BN2/4QPPP/3R1RK1 b - b3 0 15"; auto fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; vector<string> moves{"e2e4", "d7d5", "e4d5", "g8f6", "d2d4", "f6d5", "g1f3", "c8f5", "f1d3", "f5d3", "d1d3", "b8c6", "e1g1", "e7e6", "d3e2", "f8e7", "c2c4", "d5b6", "c1e3", "e8g8", "b1c3", "e7b4", "c3e4", "b4e7", "a1d1", "d8d7", "a2a3", "f8d8", "b2b4"}; auto comp_translator = GSateTranslator(); auto comp_gstate_controller = GameStateController(); auto& comp_game_state = comp_gstate_controller.current_game_state; comp_game_state = comp_translator.interpretAndSetFen(comparison_fen); auto translator = GSateTranslator(); auto gstate_controller = GameStateController(); auto& game_state = gstate_controller.current_game_state; game_state = translator.interpretAndSetFen(fen); game_state = translator.makeMovesFromFieldStrings(game_state, moves); ASSERT_TRUE(compare_game_states(game_state, comp_game_state)); } TEST(Calculator, test_en_passant_move_black) { auto comparison_fen = "7k/8/5p2/6p1/8/6p1/8/1K6 w - - 0 2"; auto fen = "7k/8/5p2/6p1/7p/8/6P1/1K6 w - - 0 1"; vector<string> moves{"g2g4", "h4g3"}; auto comp_translator = GSateTranslator(); auto comp_gstate_controller = GameStateController(); auto& comp_game_state = comp_gstate_controller.current_game_state; comp_game_state = comp_translator.interpretAndSetFen(comparison_fen); auto translator = GSateTranslator(); auto gstate_controller = GameStateController(); auto& game_state = gstate_controller.current_game_state; game_state = translator.interpretAndSetFen(fen); game_state = translator.makeMovesFromFieldStrings(game_state, moves); ASSERT_TRUE(compare_game_states(game_state, comp_game_state)); } TEST(Calculator, test_piece_transformation_white_Q) { auto comparison_fen = "5Q2/8/6k1/8/8/8/6PP/5K2 b - - 2 5"; auto fen = "8/p6k/8/1P6/8/8/6PP/5K2 b - - 0 1"; vector<string> moves{"a7a5", "b5a6", "h7g7", "a6a7", "g7f7", "a7a8q", "f7g6", "a8f8"}; auto comp_translator = GSateTranslator(); auto comp_gstate_controller = GameStateController(); auto& comp_game_state = comp_gstate_controller.current_game_state; comp_game_state = comp_translator.interpretAndSetFen(comparison_fen); auto translator = GSateTranslator(); auto gstate_controller = GameStateController(); auto& game_state = gstate_controller.current_game_state; game_state = translator.interpretAndSetFen(fen); game_state = translator.makeMovesFromFieldStrings(game_state, moves); ASSERT_TRUE(compare_game_states(game_state, comp_game_state)); } TEST(Calculator, test_piece_transformation_black_q) { auto comparison_fen = "7k/6pp/8/8/8/6PK/7P/5q2 w - - 2 5"; auto fen = "7k/6pp/8/8/1p6/8/P5PP/7K w - - 0 1"; vector<string> moves{"a2a4", "b4a3", "g2g3", "a3a2", "h1g2", "a2a1q", "g2h3", "a1f1"}; auto comp_translator = GSateTranslator(); auto comp_gstate_controller = GameStateController(); auto& comp_game_state = comp_gstate_controller.current_game_state; comp_game_state = comp_translator.interpretAndSetFen(comparison_fen); auto translator = GSateTranslator(); auto gstate_controller = GameStateController(); auto& game_state = gstate_controller.current_game_state; game_state = translator.interpretAndSetFen(fen); game_state = translator.makeMovesFromFieldStrings(game_state, moves); ASSERT_TRUE(compare_game_states(game_state, comp_game_state)); }
40.845161
78
0.731796
[ "vector" ]
f83bcceee4fe53652fbd4237c3ee00d97e205c12
9,744
cpp
C++
handlersocket/HandlerSocketClient.cpp
addb-swstarlab/YCSB-leveldb
e80c9742996da2c27fd1815932474117f659a18c
[ "Apache-2.0" ]
16
2019-11-22T04:48:17.000Z
2021-05-14T11:11:56.000Z
handlersocket/HandlerSocketClient.cpp
levyx/mapkeeper
adb2061031a2a8759771afb401c10c108e975ce0
[ "Apache-2.0" ]
null
null
null
handlersocket/HandlerSocketClient.cpp
levyx/mapkeeper
adb2061031a2a8759771afb401c10c108e975ce0
[ "Apache-2.0" ]
2
2015-09-18T06:18:13.000Z
2019-03-01T04:26:32.000Z
/* * Copyright 2012 Yahoo! Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cassert> #include <mysqld_error.h> #include <boost/lexical_cast.hpp> #include "HandlerSocketClient.h" using namespace dena; const std::string HandlerSocketClient::DBNAME = "mapkeeper"; const std::string HandlerSocketClient::FIELDS = "record_key,record_value"; HandlerSocketClient:: HandlerSocketClient(const std::string& host, uint32_t mysqlPort, uint32_t hsReaderPort, uint32_t hsWriterPort) : host_(host), mysqlPort_(mysqlPort), hsReaderPort_(hsReaderPort), hsWriterPort_(hsWriterPort), currentTableId_(0) { assert(&mysql_ == mysql_init(&mysql_)); // Automatically reconnect if the connection is lost. // http://dev.mysql.com/doc/refman/5.0/en/mysql-options.html my_bool reconnect = 1; assert(0 == mysql_options(&mysql_, MYSQL_OPT_RECONNECT, &reconnect)); assert(&mysql_ == mysql_real_connect(&mysql_, host_.c_str(), // hostname "root", // user NULL, // password NULL, // default database mysqlPort_, // port NULL, // unix socket 0 // flags )); std::string query = "create database if not exists " + DBNAME; assert(0 == mysql_query(&mysql_, query.c_str())); query = "use " + DBNAME; assert(0 == mysql_query(&mysql_, query.c_str())); dena::config conf; conf["host"] = host_; conf["port"] = boost::lexical_cast<std::string>(hsWriterPort_); socket_args sockargs; sockargs.set(conf); writer_ = hstcpcli_i::create(sockargs); conf["port"] = boost::lexical_cast<std::string>(hsReaderPort_); sockargs.set(conf); reader_ = hstcpcli_i::create(sockargs); } HandlerSocketClient::ResponseCode HandlerSocketClient:: createTable(const std::string& tableName) { std::string query = "create table " + escapeString(tableName) + "(record_key varbinary(512) primary key, record_value longblob not null) engine=innodb"; int result = mysql_query(&mysql_, query.c_str()); if (result != 0) { uint32_t error = mysql_errno(&mysql_); if (error == ER_TABLE_EXISTS_ERROR) { return TableExists; } else { fprintf(stderr, "%d %s\n", error, mysql_error(&mysql_)); return Error; } } return Success; } HandlerSocketClient::ResponseCode HandlerSocketClient:: dropTable(const std::string& tableName) { std::string query = "drop table " + escapeString(tableName); int result = mysql_query(&mysql_, query.c_str()); if (result != 0) { uint32_t error = mysql_errno(&mysql_); if (error == ER_BAD_TABLE_ERROR) { return TableNotFound; } else { fprintf(stderr, "%d %s\n", error, mysql_error(&mysql_)); return Error; } } return Success; } HandlerSocketClient::ResponseCode HandlerSocketClient:: insert(const std::string& tableName, const std::string& key, const std::string& value) { const std::string op = "+"; const int limit = 1; const int skip = 0; std::vector<string_ref> keyrefs; const string_ref ref(key.data(), key.size()); keyrefs.push_back(ref); const string_ref ref2(value.data(), value.size()); keyrefs.push_back(ref2); size_t num_keys = keyrefs.size(); const string_ref op_ref(op.data(), op.size()); size_t numflds = 0; uint32_t id; ResponseCode rc = getTableId(tableName, id); if (rc != Success) { return rc; } writer_->request_buf_exec_generic(0, op_ref, &keyrefs[0], num_keys, limit, skip, string_ref(), 0, 0); assert(writer_->request_send() == 0); if (writer_->response_recv(numflds) != 0) { // TODO handlersocket doesn't set error code properly, and it's // hard to tell why the request failed. writer_->response_buf_remove(); return RecordExists; } writer_->response_buf_remove(); return Success; } HandlerSocketClient::ResponseCode HandlerSocketClient:: update(const std::string& tableName, const std::string& key, const std::string& value) { const std::string op = "="; const std::string modOp = "U"; const int limit = 1; const int skip = 0; std::vector<string_ref> keyrefs; const string_ref ref(key.data(), key.size()); keyrefs.push_back(ref); const string_ref ref2(value.data(), value.size()); keyrefs.push_back(ref2); const string_ref op_ref(op.data(), op.size()); const string_ref modop_ref(modOp.data(), modOp.size()); size_t numflds = 0; uint32_t id; ResponseCode rc = getTableId(tableName, id); if (rc != Success) { return rc; } writer_->request_buf_exec_generic(id, op_ref, &keyrefs[0], 1, limit, skip, modop_ref, &keyrefs[0], 2); assert(writer_->request_send() == 0); if (writer_->response_recv(numflds) != 0) { // TODO this doesn't fail even if the record doesn't exist. writer_->response_buf_remove(); return RecordNotFound; } writer_->response_buf_remove(); return Success; } HandlerSocketClient::ResponseCode HandlerSocketClient:: get(const std::string& tableName, const std::string& key, std::string& value) { const std::string op = "="; const int limit = 1; const int skip = 0; std::vector<string_ref> keyrefs; const string_ref ref(key.data(), key.size()); keyrefs.push_back(ref); size_t num_keys = keyrefs.size(); const string_ref op_ref(op.data(), op.size()); size_t numflds = 0; uint32_t id; ResponseCode rc = getTableId(tableName, id); if (rc != Success) { return rc; } reader_->request_buf_exec_generic(id, op_ref, &keyrefs[0], num_keys, limit, skip, string_ref(), 0, 0); assert(reader_->request_send() == 0); assert(reader_->response_recv(numflds) == 0); assert(numflds == 2); const string_ref *const row = reader_->get_next_row(); if (row == 0) { reader_->response_buf_remove(); return RecordNotFound; } value.assign(row[1].begin(), row[1].size()); reader_->response_buf_remove(); return Success; } HandlerSocketClient::ResponseCode HandlerSocketClient:: remove(const std::string& tableName, const std::string& key) { const std::string op = "="; const std::string modOp = "D"; const int limit = 1; const int skip = 0; std::vector<string_ref> keyrefs; const string_ref ref(key.data(), key.size()); keyrefs.push_back(ref); size_t numKeys = keyrefs.size(); const string_ref op_ref(op.data(), op.size()); const string_ref modop_ref(modOp.data(), modOp.size()); size_t numflds = 0; uint32_t id; ResponseCode rc = getTableId(tableName, id); if (rc != Success) { return rc; } writer_->request_buf_exec_generic(id, op_ref, &keyrefs[0], numKeys, limit, skip, modop_ref, 0, 0); assert(writer_->request_send() == 0); if (writer_->response_recv(numflds) != 0) { // TODO this doesn't fail even if the record doesn't exist. writer_->response_buf_remove(); return RecordNotFound; } writer_->response_buf_remove(); return Success; } void HandlerSocketClient:: scan(mapkeeper::RecordListResponse& _return, const std::string& tableName, const mapkeeper::ScanOrder::type order, const std::string& startKey, const bool startKeyIncluded, const std::string& endKey, const bool endKeyIncluded, const int32_t maxRecords, const int32_t maxBytes) { } std::string HandlerSocketClient:: escapeString(const std::string& str) { // http://dev.mysql.com/doc/refman/4.1/en/mysql-real-escape-string.html char buffer[2 * str.length() + 1]; uint64_t length = mysql_real_escape_string(&mysql_, buffer, str.c_str(), str.length()); return std::string(buffer, length); } HandlerSocketClient::ResponseCode HandlerSocketClient:: getTableId(const std::string& tableName, uint32_t& id) { std::map<std::string, uint32_t>::iterator itr = tableIds_.find(tableName); if (itr != tableIds_.end()) { id = itr->second; return Success; } size_t numFields = 0; id = currentTableId_; currentTableId_++; // open index for writer writer_->request_buf_open_index(id, DBNAME.c_str(), tableName.c_str(), "PRIMARY", FIELDS.c_str()); assert(writer_->request_send() == 0); int code; if ((code = writer_->response_recv(numFields)) != 0) { // TODO handlersocket doesn't set error code properly, and it's // hard to tell why the request failed. writer_->response_buf_remove(); return TableNotFound; } writer_->response_buf_remove(); // open index for reader reader_->request_buf_open_index(id, DBNAME.c_str(), tableName.c_str(), "PRIMARY", FIELDS.c_str()); assert(reader_->request_send() == 0); if ((code = reader_->response_recv(numFields)) != 0) { // TODO handlersocket doesn't set error code properly, and it's // hard to tell why the request failed. reader_->response_buf_remove(); return TableNotFound; } reader_->response_buf_remove(); tableIds_[tableName] = id; return Success; }
35.05036
114
0.654454
[ "vector" ]
f83e39334f641aacaa26c731d71c6f54091cb329
55,809
cxx
C++
inetcore/mshtml/src/site/text/cglyph.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/mshtml/src/site/text/cglyph.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/mshtml/src/site/text/cglyph.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------- // // File: cglyph.cxx // // Contents: CGlyph Class which manages the information for glyphs and makes it available at rendering time. // // Classes: CGlyph // CGlyphTreeType // //------------------------------------------------------------------------ #include "headers.hxx" #pragma MARK_DATA(__FILE__) #pragma MARK_CODE(__FILE__) #pragma MARK_CONST(__FILE__) #include "cglyph.hxx" #ifndef X_FLOWLYT_HXX_ #define X_FLOWLYT_HXX_ #include "flowlyt.hxx" #endif #ifndef X_INTL_HXX_ #define X_INTL_HXX_ #include "intl.hxx" #endif #ifndef X_FORMKRNL_HXX_ #define X_FORMKRNL_HXX_ #include "formkrnl.hxx" #endif #ifndef X_ROOTELEM_HXX_ #define X_ROOTELEM_HXX_ #include "rootelem.hxx" #endif MtDefine(CGlyph, CDoc, "CGlyph") MtDefine(CTreeObject, CGlyph, "CTreeObject") MtDefine(CTreeList, CTreeObject, "CTreeList") MtDefine(GyphInfoType, CTreeObject, "GyphInfoType") //+--------------------------------------------------------------------------- // // Member: CGlyph::CGlyph() // // Synopsis: Initializes the class' static data. // //---------------------------------------------------------------------------- CGlyph::CGlyph(CDoc * pDoc) { _pDoc = pDoc; s_levelSize [0] = NUM_STATE_ELEMS; s_levelSize [1] = NUM_POS_ELEMS; s_levelSize [2] = NUM_ALIGN_ELEMS; s_levelSize [3] = NUM_ORIENT_ELEMS; _pchBeginDelimiter = NULL; _pchEndDelimiter = NULL; _pchEndLineDelimiter = NULL; _pchDefaultImgURL = NULL; } //+--------------------------------------------------------------------------- // // Member: CGlyph::Init() // // Synopsis: Makes the necessary memory allocations and initializations // //---------------------------------------------------------------------------- HRESULT CGlyph::Init () { HRESULT hr = S_OK; TCHAR szBuffer[256]; _XMLStack = new CList; if (!_XMLStack) { hr = E_OUTOFMEMORY; goto Cleanup; } _gHashTable = new CPtrBagCi<CGlyphTreeType *>(TRUE); if (!_gHashTable) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = _pDoc->GetEditingString(IDS_BEGIN_DELIMITER , szBuffer, ARRAY_SIZE(szBuffer)); if (hr) goto Cleanup; _pchBeginDelimiter = new TCHAR[_tcslen(szBuffer)+1]; if (!_pchBeginDelimiter) { hr = E_OUTOFMEMORY ; goto Cleanup; } _tcscpy(_pchBeginDelimiter , szBuffer); hr = _pDoc->GetEditingString(IDS_END_DELIMITER , szBuffer, ARRAY_SIZE(szBuffer)); if (hr) goto Cleanup; _pchEndDelimiter = new TCHAR[_tcslen(szBuffer)+1]; if (!_pchEndDelimiter) { hr = E_OUTOFMEMORY ; goto Cleanup; } _tcscpy(_pchEndDelimiter , szBuffer); hr = _pDoc->GetEditingString(IDS_END_LINE_DELIMITER , szBuffer, ARRAY_SIZE(szBuffer)); if (hr) goto Cleanup; _pchEndLineDelimiter = new TCHAR[_tcslen(szBuffer)+1]; if (!_pchEndLineDelimiter) { hr = E_OUTOFMEMORY ; goto Cleanup; } _tcscpy(_pchEndLineDelimiter , szBuffer); hr = ConstructResourcePath (szBuffer); if (hr) goto Cleanup; _tcscat (szBuffer, DEFAULT_IMG_NAME); _pchDefaultImgURL = new TCHAR [_tcslen(szBuffer)+1]; if (!_pchDefaultImgURL) { hr = E_OUTOFMEMORY; goto Cleanup; } _tcscpy (_pchDefaultImgURL, szBuffer); Cleanup: RRETURN (hr); } HRESULT CGlyph::ConstructResourcePath (TCHAR szBuffer []) { HRESULT hr = S_OK; HINSTANCE hResourceLibrary = NULL; hr = _pDoc->GetEditResourceLibrary(&hResourceLibrary); if (hr) goto Cleanup; _tcscpy(szBuffer, _T("res://")); if (!GetModuleFileName( hResourceLibrary, szBuffer + _tcslen(szBuffer), pdlUrlLen - _tcslen(szBuffer) - 1)) { hr = GetLastWin32Error(); goto Cleanup; } #ifdef UNIX { TCHAR* p = _tcsrchr(szBuffer, _T('/')); if (p) { int iLen = _tcslen(++p); memmove(szBuffer + 6, p, sizeof(TCHAR) * iLen); szBuffer[6 + iLen] = _T('\0'); } } #endif _tcscat (szBuffer, _T("/")); Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::~CGlyph() // // Synopsis: First deletes the contents of the hash table, which is in // charge of keeping track of glyphs for XML tags. Then, // deletes the hash table, and finally iterates through the // static array which keeps track of all the identified // tags and deletes the contents of that as well. // // Note: The sole putpose of _XMLStack is in fact to keep // track of the information entered into the hash // table, because this implementation of a hash table // does not have a handy way of iterating through it. // //---------------------------------------------------------------------------- CGlyph::~CGlyph() { RemoveGlyphTableContents (); delete _pchBeginDelimiter; delete _pchEndDelimiter; delete _pchEndLineDelimiter; delete _pchDefaultImgURL; delete _gHashTable; delete _XMLStack; } //+--------------------------------------------------------------------------- // // Member: CGlyph::RemoveGlyphTableContents () // // Synopsis: This method deletes all of the CGlyphTreeType structures // that we have. It begins by popping the entire stack // of data that is contained in the hash table, and then // iterates through the static array which is reserved for // the known tags. // //---------------------------------------------------------------------------- HRESULT CGlyph::RemoveGlyphTableContents () { CGlyphTreeType * XMLTree; int count; if (_XMLStack) { _XMLStack->Pop ((void**) &XMLTree); while (XMLTree) { delete XMLTree; _XMLStack->Pop ((void**) &XMLTree); } } for (count = 0; count <= ETAG_LAST; count++) { if ( _gIdentifiedTagArray [count] != NULL ) { delete _gIdentifiedTagArray [count]; _gIdentifiedTagArray [count] = NULL; } } return (S_OK); } //+--------------------------------------------------------------------------- // // Member: CGlyph::ReplaceGlyphTableContents // // Synopsis: This public method is called to purge the glyph information // and reconstruct the new data given a BSTR input. // //---------------------------------------------------------------------------- HRESULT CGlyph::ReplaceGlyphTableContents (BSTR inputStream) { HRESULT hr; hr = THR( RemoveGlyphTableContents () ); if (FAILED (hr)) RRETURN (hr); hr = THR( ParseGlyphTable (inputStream, TRUE) ); RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::AddToGlyphTable // // Synopsis: This public method is used to insert new information // using a table formatted in a BSTR // //---------------------------------------------------------------------------- HRESULT CGlyph::AddToGlyphTable (BSTR inputStream) { return ( ParseGlyphTable (inputStream, TRUE) ); } //+--------------------------------------------------------------------------- // // Member: CGlyph::RemoveFromGlyphTable // // Synopsis: This public method is used to delete a rule from the table. // If this rule is not found ERROR_NOT_FOUND is returned. // //---------------------------------------------------------------------------- HRESULT CGlyph::RemoveFromGlyphTable (BSTR inputStream) { return ( ParseGlyphTable (inputStream, FALSE) ); } HRESULT CGlyph::AddSynthesizedRule (const TCHAR imgName [], ELEMENT_TAG eTag, GLYPH_STATE_TYPE eState, GLYPH_POSITION_TYPE ePos, GLYPH_ALIGNMENT_TYPE eAlign, GLYPH_ORIENTATION_TYPE eOrient, PTCHAR tagName ) { HRESULT hr = S_OK; CGlyphInfoType * gInfo = NULL; TCHAR pchImgURL [256]; hr = ConstructResourcePath(pchImgURL); if (hr) goto Cleanup; _tcscat (pchImgURL, imgName); gInfo = new CGlyphInfoType; if (gInfo == NULL) { hr = E_OUTOFMEMORY; goto Cleanup; } gInfo->pImageContext = NULL; gInfo->width = gInfo->height = gInfo->offsetX = gInfo->offsetY = DEFAULT_GLYPH_SIZE; gInfo->pchImgURL = new TCHAR [_tcslen(pchImgURL)+1]; if (!gInfo->pchImgURL) { hr = E_OUTOFMEMORY; goto Cleanup; } _tcscpy (gInfo->pchImgURL, pchImgURL); if (tagName == NULL) { hr = THR( InsertIntoTable (gInfo, eTag, eState, eAlign, ePos, eOrient, TRUE) ); } else { hr = THR( InsertIntoTable (gInfo, tagName, eState, eAlign, ePos, eOrient, TRUE) ); } if (FAILED (hr)) { delete gInfo; goto Cleanup; } Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::Exec // // Synopsis: This method is used to implement various IDM command executions. // Nothing too complicated, except that it also takes charge of // informing text whether it has shifted from a no-info state // to a state where CGlyph needs to be querried for glyph info. // //---------------------------------------------------------------------------- HRESULT CGlyph::Exec( GUID * pguidCmdGroup, UINT idm, DWORD nCmdexecopt, VARIANTARG * pvarargIn, VARIANTARG * pvarargOut) { HRESULT hr = S_OK; switch (idm) { case IDM_SHOWALLTAGS: AddSynthesizedRule (_T("unknown.gif"), ETAG_NULL); hr = Exec (pguidCmdGroup, IDM_SHOWUNKNOWNTAGS, nCmdexecopt, pvarargIn, pvarargOut); if ( FAILED(hr) ) break; case IDM_SHOWMISCTAGS: hr = Exec (pguidCmdGroup, IDM_SHOWALIGNEDSITETAGS, nCmdexecopt, pvarargIn, pvarargOut); if ( FAILED(hr) ) break; hr = Exec (pguidCmdGroup, IDM_SHOWSCRIPTTAGS, nCmdexecopt, pvarargIn, pvarargOut); if ( FAILED(hr) ) break; hr = Exec (pguidCmdGroup, IDM_SHOWSTYLETAGS, nCmdexecopt, pvarargIn, pvarargOut); if ( FAILED(hr) ) break; hr = Exec (pguidCmdGroup, IDM_SHOWCOMMENTTAGS, nCmdexecopt, pvarargIn, pvarargOut); if ( FAILED(hr) ) break; hr = Exec (pguidCmdGroup, IDM_SHOWAREATAGS, nCmdexecopt, pvarargIn, pvarargOut); if ( FAILED(hr) ) break; hr = Exec (pguidCmdGroup, IDM_SHOWUNKNOWNTAGS, nCmdexecopt, pvarargIn, pvarargOut); if ( FAILED(hr) ) break; hr = Exec (pguidCmdGroup, IDM_SHOWWBRTAGS, nCmdexecopt, pvarargIn, pvarargOut); if ( FAILED(hr) ) break; AddSynthesizedRule (_T("abspos.gif"), ETAG_NULL, GST_DEFAULT, GPT_ABSOLUTE, GAT_DEFAULT, GOT_DEFAULT); break; case IDM_SHOWALIGNEDSITETAGS: AddSynthesizedRule (_T("leftalign.gif"), ETAG_NULL, GST_DEFAULT, GPT_DEFAULT, GAT_LEFT, GOT_DEFAULT); AddSynthesizedRule (_T("centeralign.gif"), ETAG_NULL, GST_DEFAULT, GPT_DEFAULT, GAT_CENTER, GOT_DEFAULT); AddSynthesizedRule (_T("rightalign.gif"), ETAG_NULL, GST_DEFAULT, GPT_DEFAULT, GAT_RIGHT, GOT_DEFAULT); break; case IDM_SHOWSCRIPTTAGS: AddSynthesizedRule (_T("script.gif"), ETAG_SCRIPT); break; case IDM_SHOWSTYLETAGS: AddSynthesizedRule (_T("style.gif"), ETAG_STYLE); break; case IDM_SHOWCOMMENTTAGS: AddSynthesizedRule (_T("comment.gif"), ETAG_COMMENT); AddSynthesizedRule (_T("comment.gif"), ETAG_RAW_COMMENT); break; case IDM_SHOWAREATAGS: AddSynthesizedRule (_T("area.gif"), ETAG_AREA); break; case IDM_SHOWUNKNOWNTAGS: AddSynthesizedRule (_T("unknown.gif"), ETAG_NULL, GST_DEFAULT, GPT_DEFAULT, GAT_DEFAULT, GOT_DEFAULT, DEFAULT_XML_TAG_NAME); break; case IDM_SHOWWBRTAGS: AddSynthesizedRule (_T("wordbreak.gif"), ETAG_WBR); AddSynthesizedRule (_T("br.gif"), ETAG_BR); break; case IDM_EMPTYGLYPHTABLE: { hr = THR(RemoveGlyphTableContents ()); break; } case IDM_ADDTOGLYPHTABLE: if (!pvarargIn->bstrVal) break; hr = THR( AddToGlyphTable (pvarargIn->bstrVal) ); break; case IDM_REMOVEFROMGLYPHTABLE: if (!pvarargIn->bstrVal) break; hr = THR( RemoveFromGlyphTable (pvarargIn->bstrVal) ); break; case IDM_REPLACEGLYPHCONTENTS: if (!pvarargIn->bstrVal) break; hr = THR( ReplaceGlyphTableContents (pvarargIn->bstrVal) ); break; default: hr = OLECMDERR_E_NOTSUPPORTED; } RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::ParseGlyphTable // // Synopsis: This is the main method in the glyph table parsing from // a BSTR. It begins by setting a PTCHAR that will walk // down the BSTR as we are parsing it. Then, it enters a // while loop until it runs into the end of the BSTR. // Within the While loop, we first need to decide whether the // first entry is a tag ID or a tag name. If the first entry // consists only of decimals, we conclude that is is a tag ID, // Then, we dispatch the parsing of the rest of the rule // accordingly. // //---------------------------------------------------------------------------- HRESULT CGlyph::ParseGlyphTable (BSTR inputStream, BOOL addToTable) { PTCHAR pchInStream = inputStream; PTCHAR pchThisSection; HRESULT hr = S_OK; if (_tcslen (pchInStream) < _tcslen (_pchBeginDelimiter)) goto Cleanup; pchInStream = _tcsstr (pchInStream, _pchBeginDelimiter); while (pchInStream) { GetThisSection (pchInStream, pchThisSection); if (pchThisSection == NULL) //If the tag ID/name field is empty, we make it default { pchThisSection = new TCHAR [5]; if (!pchThisSection) { hr = E_OUTOFMEMORY; goto Cleanup; } _itot (ETAG_UNKNOWN, pchThisSection, 10); } if (_tcsspn (pchThisSection, DECIMALS) == _tcsclen(pchThisSection)) //If this rule specifies a tag ID { IDParse (pchInStream, pchThisSection, addToTable); } else //If this rule specifies a tag name { XMLParse (pchInStream, pchThisSection, addToTable); } delete pchThisSection; // Goto next rule if (pchInStream) pchInStream = _tcsstr (pchInStream, _pchEndLineDelimiter); if (pchInStream) pchInStream = pchInStream + _tcsclen (_pchEndLineDelimiter); if (pchInStream) pchInStream = _tcsstr (pchInStream, _pchBeginDelimiter); } Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::ParseBasicInfo // // Synopsis: This method parses the basic Glyph info which is common // to both tags with identified ID's and others (i.e. XML's). // //---------------------------------------------------------------------------- HRESULT CGlyph::ParseBasicInfo (PTCHAR & pchInStream, BasicGlyphInfoType & newRule) { HRESULT hr = S_OK; LONG temp; //Initialize the Fields newRule.eState = GST_DEFAULT; newRule.eAlign = GAT_DEFAULT; newRule.ePos = GPT_DEFAULT; newRule.eOrient = GOT_DEFAULT; newRule.width = newRule.height = newRule.offsetX = newRule.offsetY = DEFAULT_GLYPH_SIZE; GetThisSection (pchInStream, newRule.pchImgURL); if (newRule.pchImgURL == NULL) { newRule.pchImgURL = new TCHAR [_tcsclen(_pchDefaultImgURL)+1]; if (!newRule.pchImgURL) { hr = E_OUTOFMEMORY; goto Cleanup; } _tcscpy(newRule.pchImgURL, _pchDefaultImgURL); goto Cleanup; } if (!NextIntSection (pchInStream, temp)) goto Cleanup; newRule.eState = (GLYPH_STATE_TYPE) temp; if (!NextIntSection (pchInStream, temp)) goto Cleanup; newRule.eAlign = (GLYPH_ALIGNMENT_TYPE) temp; if (!NextIntSection (pchInStream, temp)) goto Cleanup; newRule.ePos = (GLYPH_POSITION_TYPE) temp; if (!NextIntSection (pchInStream, temp)) goto Cleanup; newRule.eOrient = (GLYPH_ORIENTATION_TYPE) temp; if (!NextIntSection (pchInStream, newRule.width)) goto Cleanup; if (!NextIntSection (pchInStream, newRule.height)) goto Cleanup; if (!NextIntSection (pchInStream, newRule.offsetX)) goto Cleanup; if (!NextIntSection (pchInStream, newRule.offsetY)) goto Cleanup; Cleanup: return (S_OK); } //+--------------------------------------------------------------------------- // // Member: CGlyph::IDParse // // Synopsis: This nethod takes care of the parsing of rules where the // tag is identified by its ID. It begins by setting the // correct tag ID, and then parsing the rest of the info // which is common to rules with ID's and names, and finally // enters the information. // //---------------------------------------------------------------------------- HRESULT CGlyph::IDParse (PTCHAR & pchInStream, PTCHAR & pchThisSection, BOOL addToTable) { HRESULT hr; PTCHAR pchTagName; ELEMENT_TAG_ID tagID = (ELEMENT_TAG_ID) _ttol(pchThisSection); extern ELEMENT_TAG ETagFromTagId ( ELEMENT_TAG_ID tagID ); if ( tagID <= TAGID_NULL || tagID == TAGID_UNKNOWN || tagID >= TAGID_COUNT ) { hr = THR( _pDoc->GetNameForTagID (tagID, &pchTagName)); if (hr || !pchTagName) goto Cleanup; hr = THR( XMLParse (pchInStream, pchTagName, addToTable) ); } else { IDGlyphTableType newRule; hr = THR( ParseBasicInfo (pchInStream, newRule.basicInfo) ); if (hr) goto Cleanup; newRule.eTag = ETagFromTagId(tagID); hr = THR( NewEntry (newRule, addToTable) ); } Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::XMLParse // // Synopsis: This nethod takes care of the parsing of rules where the // tag is identified by its name. It begins by setting the // correct tag name, and then parsing the rest of the info // which is common to rules with ID's and names, and finally // enters the information. // //---------------------------------------------------------------------------- HRESULT CGlyph::XMLParse (PTCHAR & pchInStream, PTCHAR & pchThisSection, BOOL addToTable) { XMLGlyphTableType newRule; HRESULT hr; newRule.pchTagName = new TCHAR [_tcsclen(pchThisSection)+1]; if (!newRule.pchTagName) { hr = E_OUTOFMEMORY; goto Cleanup; } _tcscpy(newRule.pchTagName, pchThisSection); hr = THR( ParseBasicInfo (pchInStream, newRule.basicInfo) ); if (hr) goto Cleanup; hr = THR( NewEntry (newRule, addToTable) ); Cleanup: delete newRule.pchTagName; RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::NextIntSection // // Synopsis: This method parses between a _pchBeginDelimiter and _pchEndDelimiter, // expecting to find an integer there. If this section is not // empty, the 'result' parameter is set to the integer // translation of the string, and TRUE is returned. If not, // 'result' is left unchanges, and FALSE is returned. // // Note: Both the return value and the setting of // 'result' are used by 'ParseBasicInfo,' depending // on whether we need to typecase a dummy variable. // //---------------------------------------------------------------------------- BOOL CGlyph::NextIntSection (PTCHAR & pchInStream, LONG & result) { PTCHAR pchThisSection = NULL; BOOL f_rVal = FALSE; if (pchInStream == NULL) // We leave and the default value remains { goto Cleanup; } GetThisSection (pchInStream, pchThisSection); if (pchThisSection == NULL) { goto Cleanup; } result = _ttol(pchThisSection); f_rVal = TRUE; Cleanup: delete pchThisSection; return (f_rVal); } //+--------------------------------------------------------------------------- // // Member: CGlyph::GetThisSection // // Synopsis: This method is used to retrieve a section in the input // stream that we are parsing. What is does is localize the // the next input field, and then constructs a TCHAR string // out of that. // // Note: In case the caller does not need to preserve // 'newString', the latter should be deleted // when no longer need by the caller. // //---------------------------------------------------------------------------- HRESULT CGlyph::GetThisSection (PTCHAR & pchSectionBegin, PTCHAR & pchNewString) { PTCHAR pchSectionEnd; PTCHAR pchRuleEnd; int beginLen; int endLen; HRESULT hr = S_OK; AssertSz(pchSectionBegin, "Parser Should Have Popped Out Before Passing In a Null"); pchNewString = NULL; pchRuleEnd = _tcsstr (pchSectionBegin, _pchEndLineDelimiter); if (!pchRuleEnd) // Messed up syntax - Try to recover cleanly { goto Cleanup; } pchSectionEnd = _tcsstr (pchSectionBegin, _pchBeginDelimiter); if (!pchSectionEnd || pchRuleEnd < pchSectionEnd) // The next non-empty field is for another rule { goto Cleanup; } // Now, we can begin pchSectionBegin = pchSectionEnd; beginLen = _tcsclen(pchSectionBegin); AssertSz (pchSectionBegin && CompareUpTo (pchSectionBegin, _pchBeginDelimiter, _tcsclen(_pchBeginDelimiter)) == 0, "Illegal Input Stream"); pchSectionBegin = pchSectionBegin + _tcsclen (_pchBeginDelimiter); if (!pchSectionBegin) { goto Cleanup; } pchSectionEnd = _tcsstr (pchSectionBegin, _pchEndDelimiter); if (!pchSectionEnd) { goto Cleanup; } beginLen = _tcsclen(pchSectionBegin); endLen = _tcsclen(pchSectionEnd); if (beginLen == endLen) //Check if this field is empty { goto Cleanup; } pchNewString = new TCHAR [beginLen-endLen+1]; if (!pchNewString) { hr = E_OUTOFMEMORY; goto Cleanup; } _tcsncpy (pchNewString, pchSectionBegin, beginLen-endLen); pchNewString[beginLen-endLen] = '\0'; pchSectionBegin = pchSectionEnd + _tcsclen (_pchEndDelimiter); Cleanup: return (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::CompareUpTo // // Synopsis: This method return TRUE or FALSE depending on whether // two strings are identical up to a certain number of // characters. // //---------------------------------------------------------------------------- int CGlyph::CompareUpTo (PTCHAR first, PTCHAR second, int numToComp) { int count; int firstLen = _tcslen (first); int secondLen = _tcslen (second); for (count = 0; count < numToComp; count++) if (((count >= firstLen) || (count >= secondLen)) || (first[count] != second[count])) break; if (count == numToComp) return 0; else return 1; } //+--------------------------------------------------------------------------- // // Member: CGlyph::InitGInfo // // Synopsis: Creates a CGlyphInfoType and sets it to its default values, // specified in basicInfo. // //---------------------------------------------------------------------------- HRESULT CGlyph::InitGInfo (pCGlyphInfoType & gInfo, BasicGlyphInfoType & basicInfo) { HRESULT hr = NOERROR; gInfo = new CGlyphInfoType; if (gInfo == NULL) { hr = E_OUTOFMEMORY; goto Cleanup; } gInfo->pImageContext = NULL; gInfo->pchImgURL = basicInfo.pchImgURL; gInfo->width = basicInfo.width; gInfo->height = basicInfo.height; gInfo->offsetX = basicInfo.offsetX; gInfo->offsetY = basicInfo.offsetY; Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::NewEntry // // Synopsis: This version of NewEntry is used to enter a new struct into // the database of Glyph info, where the name of a tag has been // specified. // //---------------------------------------------------------------------------- HRESULT CGlyph::NewEntry (XMLGlyphTableType & gTableElem, BOOL addToTable ) { HRESULT hr = S_OK; CGlyphInfoType * gInfo; hr = THR( InitGInfo (gInfo, gTableElem.basicInfo) ); if ( FAILED (hr) ) goto Cleanup; hr = THR( InsertIntoTable (gInfo, gTableElem.pchTagName, gTableElem.basicInfo.eState, gTableElem.basicInfo.eAlign, gTableElem.basicInfo.ePos, gTableElem.basicInfo.eOrient, addToTable) ); if (!addToTable) delete gInfo; Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: // // Synopsis: This version of NewEntry is used to enter a new struct into // the database of Glyph info, where the tag is identified // by its tag ID. // //---------------------------------------------------------------------------- HRESULT CGlyph::NewEntry(IDGlyphTableType & gTableElem, BOOL addToTable) { HRESULT hr = NOERROR; CGlyphInfoType * gInfo; hr = THR( InitGInfo (gInfo, gTableElem.basicInfo) ); if ( FAILED (hr) ) goto Cleanup; hr = THR( InsertIntoTable (gInfo, gTableElem.eTag, gTableElem.basicInfo.eState, gTableElem.basicInfo.eAlign, gTableElem.basicInfo.ePos, gTableElem.basicInfo.eOrient, addToTable) ); Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::InsertIntoTable // // Synopsis: This method adds a new entry into the database of // CGlyphInfoTypes when the tag has been identified by its name. // First, if the tag name is empty, or null it is set to the // default value of ETAG_NULL. Next, if we attempt to resolve // this tag name with a tag ID. If we have been able to attach // the tag name with an ID, we enter the new info into the // static array that contains info for tags with identified // ID's. If that is not the case, we enter the info into // the hash table which is reserved for tags that we can // not resolve into an ID. // //---------------------------------------------------------------------------- HRESULT CGlyph::InsertIntoTable (CGlyphInfoType * gInfo, PTCHAR pchTagName, GLYPH_STATE_TYPE eState, GLYPH_ALIGNMENT_TYPE eAlign, GLYPH_POSITION_TYPE ePos, GLYPH_ORIENTATION_TYPE eOrient, BOOL addToTable) { CGlyphTreeType * infoTable; HRESULT hr; ELEMENT_TAG eTag; hr = THR( AttemptToResolveTagName (pchTagName, eTag) ); if (FAILED (hr)) { delete gInfo; goto Cleanup; } if ( !IsGenericTag (eTag) && _tcscmp (pchTagName, DEFAULT_XML_TAG_NAME) != 0 && !(eTag == NULL)) { hr = THR( InsertIntoTable (gInfo, eTag, eState, eAlign, ePos, eOrient, addToTable) ); goto Cleanup; } infoTable = _gHashTable->GetCi(pchTagName); if (infoTable == NULL) { infoTable = new CGlyphTreeType(); if (infoTable == NULL) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = THR( _gHashTable->SetCi (pchTagName, infoTable) ); if (FAILED (hr) ) { delete infoTable; goto Cleanup; } _XMLStack->Push ((void**)infoTable); } if (infoTable != NULL) { hr = THR( infoTable->AddRule (gInfo, eState, eAlign, ePos, eOrient, addToTable, this) ); } Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::InsertIntoTable // // Synopsis: This method enters a CGlyphInfoType struct into the static // array. If ever an unidentified tag ID is passed in, // this entry is ignored. // //---------------------------------------------------------------------------- HRESULT CGlyph::InsertIntoTable (CGlyphInfoType * gInfo, ELEMENT_TAG eTag, GLYPH_STATE_TYPE eState, GLYPH_ALIGNMENT_TYPE eAlign, GLYPH_POSITION_TYPE ePos, GLYPH_ORIENTATION_TYPE eOrient, BOOL addToTable) { CGlyphTreeType * infoTable; HRESULT hr = S_OK; if (eTag >= ETAG_LAST) { delete gInfo; goto Cleanup; } if (_gIdentifiedTagArray[eTag] == NULL) { infoTable = new CGlyphTreeType(); if (infoTable == NULL) { hr = E_OUTOFMEMORY; goto Cleanup; } _gIdentifiedTagArray[eTag] = infoTable; } else { infoTable = _gIdentifiedTagArray[eTag]; } if (infoTable != NULL) { hr = THR( infoTable->AddRule (gInfo, eState, eAlign, ePos, eOrient, addToTable, this) ); } Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CALLBACK OnImgCtxChange // // Synopsis: This is the callback function that is used to invalidate // the page when a new image has finished downloading for the // first time. // //---------------------------------------------------------------------------- void CALLBACK CGlyph::OnImgCtxChange( VOID * pvImgCtx, VOID * pv ) { ((CDoc *)pv)->GetView()->Invalidate(); } //+--------------------------------------------------------------------------- // // Member: CGlyph::InitRenderTagInfo // // Synopsis: None // //---------------------------------------------------------------------------- HRESULT CGlyph::InitRenderTagInfo (CGlyphRenderInfoType * renderTagInfo) { HRESULT hr = S_OK; if (renderTagInfo == NULL) { hr = E_OUTOFMEMORY; goto Cleanup; } renderTagInfo->pImageContext = NULL; renderTagInfo->width = 0; renderTagInfo->height = 0; renderTagInfo->offsetX = 0; renderTagInfo->offsetY = 0; Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::CompleteInfoProcessing // // Synopsis: Once the CGlyphInfoType structure has been found, this method // is used to set up the information to send it back to // rendering. // // Note: This method unfifes the code path for XML and normal // tags. // //---------------------------------------------------------------------------- HRESULT CGlyph::CompleteInfoProcessing (CGlyphInfoType * localInfo, CGlyphRenderInfoType * pTagInfo, void * invalidateInfo) { HRESULT hr = S_OK; AssertSz (localInfo, "This point should only be reached if a valid query was made"); // Bitmap handle has not been loaded yet // i.e. this is the first time this image is requested if (localInfo->pImageContext == NULL) { hr = THR( GetImageContext (localInfo, invalidateInfo, localInfo->pImageContext) ); if (FAILED (hr) ) goto Cleanup; } pTagInfo->pImageContext = localInfo->pImageContext; pTagInfo->width = localInfo->width; pTagInfo->height = localInfo->height; pTagInfo->offsetX = localInfo->offsetX; pTagInfo->offsetY = localInfo->offsetY; Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::AttemptToResolveTagName // // Synopsis: Retrieves that tag info given a tag name. If the tag name // is resolvable into an ID. the the codepath goes to the ID- // identified glyphs. If not, we go on to looking in the hash // table. // // Note: The attempt to resolve tag names into ID's is the // same as the point where new info is entered. // //---------------------------------------------------------------------------- HRESULT CGlyph::AttemptToResolveTagName (PTCHAR pchTagName, ELEMENT_TAG & eTag) { HRESULT hr = S_OK; AssertSz (pchTagName, "Tag name cannot be NULL"); eTag = ETAG_NULL; if (pchTagName == NULL) { eTag = ETAG_UNKNOWN; } else { // // If the name has a colon in it - assume it's an XML namespace tag. // if ( _tcsstr( pchTagName, _T(":") ) > 0 ) { eTag = ETAG_GENERIC; } else eTag = EtagFromName (pchTagName, _tcslen(pchTagName)); } RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::GetTagInfo // // Synopsis: Retrieves that tag info given a ptp. It first searches for // a location in the data where the the ID's resolve (an entry // for the specific tag or an entry for the dafaults). Then, // if we can find the info, the return struct is set. // // Note: The attempt to resolve tag names into ID's is the // same as the point where new info is entered. // //---------------------------------------------------------------------------- HRESULT CGlyph::GetTagInfo (CTreePos * ptp, GLYPH_ALIGNMENT_TYPE eAlign, GLYPH_POSITION_TYPE ePos, GLYPH_ORIENTATION_TYPE eOrient, void * invalidateInfo, CGlyphRenderInfoType * pTagInfo) { CGlyphTreeType * infoTree = NULL; CGlyphInfoType * localInfo = NULL; HRESULT hr = S_OK; ELEMENT_TAG eTag; GLYPH_STATE_TYPE eState; CTreeNode * pNode; pTagInfo->pImageContext = NULL; if ( !ptp || !ptp->IsNode() ) goto Cleanup; pNode = ptp->Branch (); eTag = pNode->Tag(); // // HACKHACK: ETAG_COMMENT can turn into ETAG_RAW_COMMENT. The parser // guys don't understand why but don't want to change it. So, we need to // unify these so that all comments render glyphs (bug 100991) // if (eTag == ETAG_RAW_COMMENT) { eTag = ETAG_COMMENT; } if ( (eTag == ETAG_NULL) || !ptp->IsEdgeScope() || ( ptp->IsEndNode() && pNode->Element()->IsNoScope() ) ) goto Cleanup; eState = (GLYPH_STATE_TYPE)!(ptp->IsBeginElementScope()); if (eTag == ETAG_UNKNOWN || IsGenericTag (eTag)) //. If it is a generic (i.e. known XML tag), we go off to the XML tag search path { hr = THR( GetXMLTagInfo (ptp, eState, eAlign, ePos, eOrient, invalidateInfo, pTagInfo) ); goto Cleanup; } infoTree = _gIdentifiedTagArray[eTag]; // First, we try to see if we have info for this specific tag if (infoTree) { hr = THR( infoTree->GetGlyphInfo (ptp, localInfo, eState, eAlign, ePos, eOrient) ); if (FAILED (hr)) goto Cleanup; } if (!localInfo) // If we don't have info for the specific tag { infoTree = _gIdentifiedTagArray[ETAG_UNKNOWN]; // We first try the ETAG default if (infoTree) { hr = THR( infoTree->GetGlyphInfo (ptp, localInfo, eState, eAlign, ePos, eOrient) ); if (FAILED (hr)) goto Cleanup; } if (!localInfo) { hr = THR( AttemptFinalDefault (ptp, localInfo, eState, eAlign, ePos, eOrient) ); if (FAILED (hr)) goto Cleanup; } } if (!localInfo) goto Cleanup; hr = THR( CompleteInfoProcessing (localInfo, pTagInfo, invalidateInfo) ); Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::GetTagInfo // // Synopsis: Retrieves that tag info given an ptp, and knowing that it // point to a generic tag. // //---------------------------------------------------------------------------- HRESULT CGlyph::GetXMLTagInfo (CTreePos * ptp, GLYPH_STATE_TYPE eState, GLYPH_ALIGNMENT_TYPE eAlign, GLYPH_POSITION_TYPE ePos, GLYPH_ORIENTATION_TYPE eOrient, void * invalidateInfo, CGlyphRenderInfoType * pTagInfo) { CGlyphTreeType * infoTree = NULL; CGlyphInfoType * localInfo = NULL; CElement* pElement; HRESULT hr = S_OK; TCHAR *strLookupName = NULL; size_t strLen; if (!ptp->Branch()) goto Cleanup; pElement = ptp->Branch()->Element(); // // Construct a string that is NameSpace:TagName // if (pElement->Namespace()) { strLen = _tcslen(pElement->Namespace()) + _tcslen(_T(":")) + _tcslen(pElement->TagName()) + 1 /* term */; strLookupName = new TCHAR[strLen]; if (!strLookupName) { hr = E_OUTOFMEMORY; goto Cleanup; } _tcscpy(strLookupName, pElement->Namespace()); _tcscat(strLookupName, _T(":") ); _tcscat(strLookupName, pElement->TagName() ); } else { strLen = _tcslen(pElement->TagName()) + 1 /* term */; strLookupName = new TCHAR[strLen]; if (!strLookupName) { hr = E_OUTOFMEMORY; goto Cleanup; } _tcscpy(strLookupName, pElement->TagName()); } infoTree = _gHashTable->GetCi( strLookupName ); // Attempt to find entry for specific XML tag if (infoTree) { hr = THR( infoTree->GetGlyphInfo (ptp, localInfo, eState, eAlign, ePos, eOrient) ); if (FAILED (hr)) goto Cleanup; } if (!localInfo) // Attempt to find default entry for all XML's { infoTree = _gHashTable->GetCi(DEFAULT_XML_TAG_NAME); if (infoTree) { hr = THR( infoTree->GetGlyphInfo (ptp, localInfo, eState, eAlign, ePos, eOrient) ); if (FAILED (hr)) goto Cleanup; } if (!localInfo) // Attempt final default for all tags (ETAGS and XMLs) { hr = THR( AttemptFinalDefault (ptp, localInfo, eState, eAlign, ePos, eOrient) ); if (FAILED (hr)) goto Cleanup; } } if (!localInfo) goto Cleanup; hr = THR( CompleteInfoProcessing (localInfo, pTagInfo, invalidateInfo) ); Cleanup: if (strLookupName) delete[] strLookupName; RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::AttemptFinalDefault // // Synopsis: This is the final default condition, where we tet if the table // contains an entry for ETAG_NULL, which is the final default // that everything falls through to. // //---------------------------------------------------------------------------- HRESULT CGlyph::AttemptFinalDefault (CTreePos * ptp, pCGlyphInfoType & localInfo, GLYPH_STATE_TYPE eState, GLYPH_ALIGNMENT_TYPE eAlign, GLYPH_POSITION_TYPE ePos, GLYPH_ORIENTATION_TYPE eOrient) { CGlyphTreeType * infoTable = NULL; HRESULT hr = S_OK; infoTable = _gIdentifiedTagArray[ETAG_NULL]; if (infoTable) hr = THR( infoTable->GetGlyphInfo (ptp, localInfo, eState, eAlign, ePos, eOrient) ); RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::GetImageContext // // Synopsis: Creates the image context, and sets the callback function // after having created the invalidation stack and mande the // first entry to it. // // Note: We pass in a pointer to the gInfo into the callback. // This is an elegant way of keeping track of what needs // to be invalidated when an image is done loading, // because whenever we want to display an image and it // is not loaded, we know the CGlyphInfoType, so we // can add the invalidation info in the stack. // //---------------------------------------------------------------------------- HRESULT CGlyph::GetImageContext (CGlyphInfoType * gInfo, void * pvCallback, pIImgCtx & newImageContext) { HRESULT hr = S_OK; newImageContext = NULL; hr = THR( CoCreateInstance(CLSID_IImgCtx, NULL, CLSCTX_INPROC_SERVER, IID_IImgCtx, (LPVOID*)&newImageContext) ); if (SUCCEEDED(hr)) { hr = THR( newImageContext->Load(gInfo->pchImgURL, IMGCHG_COMPLETE) ); if ( SUCCEEDED( hr )) { hr = THR( newImageContext->SetCallback( OnImgCtxChange, _pDoc ) ); } if ( SUCCEEDED( hr )) { hr = THR( newImageContext->SelectChanges( IMGCHG_COMPLETE, 0, TRUE) ); } if ( FAILED( hr )) { newImageContext->Release(); return hr; } } RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::CGlyphTreeType::CGlyphTreeType // // Synopsis: Creates the frst level of the tree and initializes it. // //---------------------------------------------------------------------------- CGlyph::CGlyphTreeType::CGlyphTreeType () { _infoTree = new CTreeList (s_levelSize [0]); if (_infoTree == NULL) { goto Cleanup; } Cleanup: return; } //+--------------------------------------------------------------------------- // // Member: CGlyph::CGlyphTreeType::~CGlyphTreeType // //---------------------------------------------------------------------------- CGlyph::CGlyphTreeType::~CGlyphTreeType () { delete _infoTree; } //+--------------------------------------------------------------------------- // // Member: CGlyph::CGlyphTreeType::TransformInfoToArray // // Synopsis: Converts glyph access information into indexes along the // the various levels of the tree. // // Note: This is one of the only two methods that needs to be changed to // modify the searching priority. // //---------------------------------------------------------------------------- HRESULT CGlyph::CGlyphTreeType::TransformInfoToArray (GLYPH_STATE_TYPE eState, GLYPH_ALIGNMENT_TYPE eAlign, GLYPH_POSITION_TYPE ePos, GLYPH_ORIENTATION_TYPE eOrient, int indexArray []) { indexArray [TREEDEPTH_STATE] = eState; indexArray [TREEDEPTH_POSITIONINING] = ePos; indexArray [TREEDEPTH_ALIGNMENT] = eAlign; indexArray [TREEDEPTH_ORIENTATION] = eOrient; return (S_OK); } //+--------------------------------------------------------------------------- // // Member: CGlyph::CGlyphTreeType::ComputeLevelIndex // // Synopsis: Takes a ptpt and retrieves the specific details that are // are needed to iterate through the next level in the tree. // This allows us to querry for specific info from the // CTreePos only as needed. // //---------------------------------------------------------------------------- HRESULT CGlyph::CGlyphTreeType::ComputeLevelIndex (CTreePos * ptp, int index [], int levelCount) { HRESULT hr = S_OK; CTreeNode * pNode = ptp->Branch (); htmlControlAlign alignment; CFlowLayout * pLayout; LCID curKbd; AssertSz ((levelCount >= 0) && (levelCount < NUM_INFO_LEVELS), "levelCount needs to be within bounds"); AssertSz (index [levelCount] == COMPUTE, "index [levelCount] == COMPUTE is why we called this in the first place"); switch (levelCount) { case TREEDEPTH_STATE : if ( ptp->IsEndElementScope () ) index [levelCount] = GST_CLOSE; else index [levelCount] = GST_OPEN; break; case TREEDEPTH_POSITIONINING : if ( pNode->IsPositionStatic () ) index [levelCount] = GPT_STATIC; else if ( pNode->IsAbsolute () ) index [levelCount] = GPT_ABSOLUTE; else if ( pNode->IsRelative () ) index [levelCount] = GPT_RELATIVE; else index [levelCount] = GPT_DEFAULT; break; case TREEDEPTH_ALIGNMENT: alignment = pNode->GetSiteAlign (); if ( alignment == htmlBlockAlignLeft ) index [levelCount] = GAT_LEFT; else if ( alignment == htmlBlockAlignCenter ) index [levelCount] = GAT_CENTER; else if ( alignment == htmlBlockAlignRight ) index [levelCount] = GAT_RIGHT; else index [levelCount] = GAT_DEFAULT; break; case TREEDEPTH_ORIENTATION: pLayout = pNode->GetFlowLayout(); if (!pLayout) { index [levelCount] = GOT_DEFAULT; break; } curKbd = LOWORD(GetKeyboardLayout(0)); if(IsRtlLCID(curKbd)) // RIGHT-LEFT index [levelCount] = GOT_RIGHT_TO_LEFT; else index [levelCount] = GOT_LEFT_TO_RIGHT; break; default: AssertSz (0, "We should always be at a level that we know about and can resolve"); } return (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::CGlyphTreeType::AddRule // CGlyph::CGlyphTreeType::InsertIntoTree // // Synopsis: This method adds a new rule (CGlyphInfoType struct) into // a tree. It searches for the location, creating levels // if necessary, and inserting the new info. // // Note: Rules that map on to the same location are resolved // by deleting the old rule and replacing it by the new // one. This allows for a handy way of overwriting // a rule. // //---------------------------------------------------------------------------- HRESULT CGlyph::CGlyphTreeType::AddRule (CGlyphInfoType * gInfo, GLYPH_STATE_TYPE eState, GLYPH_ALIGNMENT_TYPE eAlign, GLYPH_POSITION_TYPE ePos, GLYPH_ORIENTATION_TYPE eOrient, BOOL addToTable, CGlyph * glyphTable) { int indexArray [NUM_INFO_LEVELS]; HRESULT hr = S_OK; TransformInfoToArray (eState, eAlign, ePos, eOrient, indexArray); hr = THR( InsertIntoTree (gInfo, indexArray, addToTable, glyphTable) ); if (hr == S_OK) glyphTable->_pDoc->ForceRelayout(); RRETURN (hr); } HRESULT CGlyph::CGlyphTreeType::InsertIntoTree (CGlyphInfoType * gInfo, int index [], BOOL addToTable, CGlyph * glyphTable) { int levelCount; CTreeList * thisLevel = _infoTree; CTreeList * newLevel; HRESULT hr = S_OK; for (levelCount = 0; levelCount < NUM_INFO_LEVELS-1; levelCount ++) { if ((*thisLevel)[index[levelCount]] == NULL) { if (!addToTable) { goto Cleanup; } newLevel = new CTreeList(s_levelSize[levelCount+1]); if (newLevel == NULL) { hr = E_OUTOFMEMORY; goto Cleanup; } (*thisLevel)[index[levelCount]] = newLevel; } else { newLevel = DYNCAST(CTreeList, (*thisLevel)[index[levelCount]]); } thisLevel = newLevel; } // Rule collisions are handled by preserving the last one if ((*thisLevel)[index[levelCount]] != NULL) { delete (*thisLevel)[index[levelCount]]; (*thisLevel)[index[levelCount]] = NULL; } else if (!addToTable) //Tried to delete non-existing rule { goto Cleanup; } if (addToTable) { (*thisLevel)[index[levelCount]] = gInfo; } Cleanup: RRETURN (hr); } //+--------------------------------------------------------------------------- // // Member: CGlyph::CGlyphTreeType::GetGlyphInfo // CGlyph::CGlyphTreeType::GetFromTree // // Synopsis: Retrieves the pointer to a CGlyphInfoType struct from a tree. // The search performed is depth-first. We begin by looking // for the exact rule specified, and as we climb back up // We try each default. // //---------------------------------------------------------------------------- HRESULT CGlyph::CGlyphTreeType::GetGlyphInfo (CTreePos * ptp, pCGlyphInfoType & gInfo, GLYPH_STATE_TYPE eState, GLYPH_ALIGNMENT_TYPE eAlign, GLYPH_POSITION_TYPE ePos, GLYPH_ORIENTATION_TYPE eOrient) { int indexArray [NUM_INFO_LEVELS]; HRESULT hr = S_OK; TransformInfoToArray (eState, eAlign, ePos, eOrient, indexArray); hr = THR( GetFromTree (ptp, gInfo, indexArray) ); RRETURN (hr); } HRESULT CGlyph::CGlyphTreeType::GetFromTree (CTreePos * ptp, pCGlyphInfoType & gInfo, int index []) { int levelCount = 0; CTreeObject * thisLevel = DYNCAST(CTreeList, _infoTree); HRESULT hr = S_OK; CList * traversalStack = new CList; if (!traversalStack) { hr = E_OUTOFMEMORY; goto Cleanup; } gInfo = NULL; while ((levelCount < NUM_INFO_LEVELS) || ((thisLevel==NULL) && levelCount > 0)) { if (index[levelCount] == COMPUTE) { hr = THR( ComputeLevelIndex (ptp, index, levelCount)); } if ( FAILED( hr ) ) goto Cleanup; if (thisLevel == NULL) { traversalStack->Pop((void**)(&thisLevel)); levelCount --; if (thisLevel == NULL) { goto Cleanup; } if (index[levelCount] == s_levelSize[levelCount]-1) { thisLevel = NULL; } else { index[levelCount] = s_levelSize[levelCount]-1; } } else { traversalStack->Push ((void**)thisLevel); thisLevel = ( *DYNCAST(CTreeList, thisLevel) ) [index[levelCount]]; if (thisLevel && thisLevel->IsInfoType ()) { gInfo = DYNCAST(CGlyphInfoType, thisLevel); goto Cleanup; } levelCount ++; } } Cleanup: delete traversalStack; return hr; } CGlyph::CList::CList () { _elemList = NULL; } CGlyph::CList::~CList () { void * dummy; while (_elemList != NULL) { Pop (&dummy); } } HRESULT CGlyph::CList::Push (void * pushed) { ListElemType * newElem = new ListElemType; if (newElem == NULL) return E_OUTOFMEMORY; newElem->elem = pushed; newElem->next = _elemList; _elemList = newElem; return (S_OK); } HRESULT CGlyph::CList::Pop (void ** popped) { ListElemType * toDelete = _elemList; if (_elemList == NULL) { *popped = NULL; goto Cleanup; } *popped = _elemList->elem; _elemList = _elemList->next; delete toDelete; Cleanup: return S_OK; } CGlyph::CTreeList::CTreeList (LONG numObjects) { int count; _numObjects = numObjects; _nextLevel = new CTreeObject * [numObjects]; if (!_nextLevel) return; for (count = 0; count < numObjects; count ++) _nextLevel [count] = NULL; } CGlyph::CTreeList::~CTreeList () { int count; for (count = 0; count < _numObjects; count ++) delete _nextLevel [count]; delete _nextLevel; } CGlyph::CTreeObject * & CGlyph::CTreeList::operator[](int index) { static CTreeObject * s_pNULL = NULL; AssertSz (s_pNULL == NULL, "Invalid Flag Set To NULL"); if ((index >= 0) && (index < _numObjects)) return (_nextLevel [index]); else return s_pNULL; } CGlyph::CGlyphInfoType::~CGlyphInfoType () { ReleaseInterface(pImageContext); delete pchImgURL; }
31.022235
144
0.514523
[ "render" ]
f83e3cf60b66e46e8dab8c03c5731b8c7225cab0
3,933
cpp
C++
Year-1/To others/Course Work Cars/source/MyForm.cpp
Ellanity/university
239b050deb4b35cdd855ab55d793988224190a57
[ "Apache-2.0" ]
null
null
null
Year-1/To others/Course Work Cars/source/MyForm.cpp
Ellanity/university
239b050deb4b35cdd855ab55d793988224190a57
[ "Apache-2.0" ]
null
null
null
Year-1/To others/Course Work Cars/source/MyForm.cpp
Ellanity/university
239b050deb4b35cdd855ab55d793988224190a57
[ "Apache-2.0" ]
null
null
null
#include <set> #include <msclr/marshal_cppstd.h> #include "MyForm.h" #include "CourseWork.h" /* using namespace System; */ /* using namespace System::Windows::Forms; */ /* All cars that were added */ std::set <Car> cars; /* main function, creates window with forms */ [System::STAThreadAttribute] void main(array<System::String^>^ args) { System::Windows::Forms::Application::EnableVisualStyles(); System::Windows::Forms::Application::SetCompatibleTextRenderingDefault(false); CourseWork::MyForm form; System::Windows::Forms::Application::Run(% form); } /* Function to create simple car */ System::Void CourseWork::MyForm::button1_Click(System::Object^ sender, System::EventArgs^ e) { try { /* Check fields before creating car */ std::string name = ""; int speed = -1; /* msclr::interop::marshal_as<std::string> creates from System::String to std::string */ try { name = msclr::interop::marshal_as<std::string>(textBox1->Text); } catch (System::FormatException^ e) { textBox1->Text = "Invalid"; } if (name == "") textBox1->Text = "Invalid"; try { speed = Int32::Parse(textBox2->Text); } catch (System::FormatException^ e) { textBox2->Text = "Invalid"; } if (speed >= 0 && name != "") { /* Object of the Car class, push it to all cars */ Car car(name, speed); cars.insert(car); showInformation(); textBox1->Text = ""; textBox2->Text = ""; } } catch (System::Exception^ e) {} /* Catching exceptions related to forms */ } /* Function to create executive car */ System::Void CourseWork::MyForm::button2_Click(System::Object^ sender, System::EventArgs^ e) { try { std::string name = ""; int speed = -1; try { name = msclr::interop::marshal_as<std::string>(textBox1->Text); } catch (System::FormatException^ e) { textBox1->Text = "Invalid"; } if (name == "") textBox1->Text = "Invalid"; try { speed = Int32::Parse(textBox2->Text); } catch (System::FormatException^ e) { textBox2->Text = "Invalid"; } if (speed >= 0 && name != "") { ExecutiveCar car(name, speed); cars.insert(car); showInformation(); textBox1->Text = ""; textBox2->Text = ""; } } catch (System::Exception^ e) {} } /* Update all cars in the list */ System::Void CourseWork::MyForm::button3_Click(System::Object^ sender, System::EventArgs^ e) { /* New list of all cars */ std::set<Car> newCars; /* Read all cars. Change them depending on their type(simple/executive) */ std::set<Car>::iterator it = cars.begin(); for (int i = 0; it != cars.end(); i++, it++) { /* Creates object of car */ Car car = *it; if (car.getType() == "executive") { /* If type is executive -> create same car (object) of right class (ExecutiveCar) */ ExecutiveCar newCar(car.getName(), car.getSpeed()); newCar.updatingModel(); newCars.insert(newCar); } else { /* If type is simple -> no need to create new object */ car.updatingModel(); newCars.insert(car); } } /* Changing of previous list */ cars = newCars; showInformation(); return System::Void(); } /* Function to show full information about car depending on their type */ void CourseWork::MyForm::showInformation() { textBox3->Text = ""; std::set<Car>::iterator it = cars.begin(); for (int i = 0; it != cars.end(); i++, it++) { Car car = *it; std::string speed, cost; if (car.getType() == "executive") { ExecutiveCar newCar(car.getName(), car.getSpeed()); speed = std::to_string(newCar.getSpeed()); cost = std::to_string(newCar.getCost()); } else { speed = std::to_string(car.getSpeed()); cost = std::to_string(car.getCost()); } /* Format of presentation */ std::string carRow = std::to_string(i + 1) + ") Type: " + car.getType() + " Name: " + car.getName() + " Speed: " + speed + " Cost: " + cost + "\r\n"; /* For new line need to use \r\n */ textBox3->Text += msclr::interop::marshal_as<System::String^>(carRow); } }
26.755102
93
0.635647
[ "object" ]
f83ef754be900097e85a9ac91de22945e7e1fcbe
5,627
hpp
C++
src/Types/Container/List.hpp
aff3ct/cli
67a1ba5474ce195e313086396ae4bca61fb6b9ce
[ "MIT" ]
2
2019-12-23T11:14:12.000Z
2021-05-31T23:30:45.000Z
src/Types/Container/List.hpp
aff3ct/cli
67a1ba5474ce195e313086396ae4bca61fb6b9ce
[ "MIT" ]
1
2020-10-23T00:33:29.000Z
2020-10-29T13:39:12.000Z
src/Types/Container/List.hpp
aff3ct/cli
67a1ba5474ce195e313086396ae4bca61fb6b9ce
[ "MIT" ]
5
2020-10-17T15:08:35.000Z
2022-02-23T22:39:57.000Z
#ifndef ARGUMENT_TYPE_LIST_HPP_ #define ARGUMENT_TYPE_LIST_HPP_ #include <stdexcept> #include <sstream> #include <vector> #include <string> #include <tuple> #include "Types/Argument_type_limited.hpp" #include "Tools/utilities.hpp" #include "Splitter/Splitter.hpp" namespace cli { template <typename T = std::string, class S = Generic_splitter, typename... Ranges> class List_type : public Argument_type_limited<std::vector<T>,Ranges...> { protected: Argument_type* val_type; public: template <typename r, typename... R> explicit List_type(Argument_type* val_type, const r* range, const R*... ranges) : Argument_type_limited<std::vector<T>,Ranges...>(generate_title(val_type), range, ranges...), val_type(val_type) { } explicit List_type(Argument_type* val_type) : Argument_type_limited<std::vector<T>,Ranges...>(generate_title(val_type)), val_type(val_type) { } virtual ~List_type() { if (val_type != nullptr) delete val_type; }; virtual List_type<T, S, Ranges...>* clone() const { auto* clone = new List_type<T, S, Ranges...>(val_type); clone->val_type = val_type->clone(); return dynamic_cast<List_type<T, S, Ranges...>*>(this->clone_ranges(clone)); } template <typename... NewRanges> List_type<T, S, Ranges..., NewRanges...>* clone(NewRanges*... new_ranges) { auto* clone = new List_type<T, S, Ranges..., NewRanges...>(val_type); this->clone_ranges(clone); clone->add_ranges(new_ranges...); return clone; } virtual void check(const std::string& val) const { // separate values: auto list = S::split(val); unsigned i = 0; try { for (; i < list.size(); i++) val_type->check(list[i]); } catch(std::exception& e) { std::stringstream message; message << "has the element " << i << " (" << list[i] << ") not respecting the rules: " << e.what(); throw std::runtime_error(message.str()); } auto list_vals = this->convert(list); this->check_ranges(list_vals); } virtual const std::string get_title() const { auto t = "list of (" + val_type->get_title() + ")"; if (sizeof...(Ranges)) // then add ranges titles to the argument title { t += Argument_type::title_description_separator; this->get_ranges_title(t); } return t; } virtual std::vector<T> convert(const std::string& val) const { return this->convert(S::split(val)); } virtual std::vector<T> convert(const std::vector<std::string>& list) const { std::vector<T> list_T(list.size()); void * p_val = nullptr; for(unsigned i = 0; i < list.size(); i++) { p_val = val_type->get_val(list[i]); if (p_val == nullptr) throw std::runtime_error("Couldn't convert value."); list_T[i] = *(T*)p_val; delete (T*)p_val; } return list_T; } static std::string generate_title(Argument_type* val_type) { std::string str = "list of " + val_type->get_short_title(); return str; } }; template <typename T = std::string, class S = Generic_splitter, typename... Ranges> List_type<T,S,Ranges...>* List(Argument_type* val_type, Ranges*... ranges) { return new List_type<T,S,Ranges...>(val_type, ranges...); } template <typename T = std::string, class S1 = Generic_splitter, class S2 = String_splitter, typename... Ranges1, typename... Ranges2> List_type<std::vector<T>, S1, Ranges1...>* List2D(Argument_type* val_type, const std::tuple<Ranges1*...>& ranges1 = std::tuple<>(), const std::tuple<Ranges2*...>& ranges2 = std::tuple<>()) { Argument_type* listD2 = cli::apply_tuple(List<T,S2,Ranges2...>, std::tuple_cat(std::make_tuple(val_type), ranges2)); return cli::apply_tuple(List<std::vector<T>,S1,Ranges1...>, std::tuple_cat(std::make_tuple(listD2), ranges1)); } template <typename T = std::string, class S1 = Generic_splitter, class S2 = String_splitter, typename... Ranges1, typename... Ranges2> List_type<std::vector<T>, S1, Ranges1...>* List2D(Argument_type* val_type, std::tuple<Ranges1*...>&& ranges1 = std::tuple<>(), std::tuple<Ranges2*...>&& ranges2 = std::tuple<>()) { Argument_type* listD2 = cli::apply_tuple(List<T,S2,Ranges2...>, std::tuple_cat(std::make_tuple(val_type), std::forward<std::tuple<Ranges2*...>>(ranges2))); return cli::apply_tuple(List<std::vector<T>,S1,Ranges1...>, std::tuple_cat(std::make_tuple(listD2), std::forward<std::tuple<Ranges1*...>>(ranges1))); } template <typename T = std::string, typename... Ranges1, typename... Ranges2> List_type<std::vector<T>, Matlab_style_splitter::D1, Ranges1...>* Matlab_vector(Argument_type* val_type, const std::tuple<Ranges1*...>& ranges1 = std::tuple<>(), const std::tuple<Ranges2*...>& ranges2 = std::tuple<>()) { return List2D<T, Matlab_style_splitter::D1, Matlab_style_splitter::D2>(val_type, ranges1, ranges2); } template <typename T = std::string, typename... Ranges1, typename... Ranges2> List_type<std::vector<T>, Matlab_style_splitter::D1, Ranges1...>* Matlab_vector(Argument_type* val_type, std::tuple<Ranges1*...>&& ranges1 = std::tuple<>(), std::tuple<Ranges2*...>&& ranges2 = std::tuple<>()) { return List2D<T, Matlab_style_splitter::D1, Matlab_style_splitter::D2>(val_type, std::forward<std::tuple<Ranges1*...>>(ranges1), std::forward<std::tuple<Ranges2*...>>(ranges2)); } } #endif /* ARGUMENT_TYPE_LIST_HPP_ */
30.416216
131
0.631598
[ "vector" ]
f841226891d1781d6136ee8730026be1c0e6f813
3,164
cc
C++
path-tracer/core/materials/phong.cc
sdao/path-tracer-nacl
abb3eb0a51059e5109b87bafd7de60a8d4055453
[ "BSD-2-Clause" ]
null
null
null
path-tracer/core/materials/phong.cc
sdao/path-tracer-nacl
abb3eb0a51059e5109b87bafd7de60a8d4055453
[ "BSD-2-Clause" ]
null
null
null
path-tracer/core/materials/phong.cc
sdao/path-tracer-nacl
abb3eb0a51059e5109b87bafd7de60a8d4055453
[ "BSD-2-Clause" ]
null
null
null
#include "phong.h" using std::min; using std::max; materials::Phong::Phong(float e, const Vec& c) : scaleBRDF(c * (e + 2.0f) / math::TWO_PI), scaleProb((e + 1.0f) / math::TWO_PI), invExponent(1.0f / (e + 1.0f)), color(c), exponent(e) {} materials::Phong::Phong(const Node& n) : Phong(n.getFloat("exponent"), n.getVec("color")) {} inline Vec materials::Phong::evalBSDFInternal( const Vec& perfectReflect, const Vec& outgoing ) const { float cosAlpha = max(0.0f, outgoing.dot(perfectReflect)); float cosAlphaPow = std::pow(cosAlpha, exponent); return scaleBRDF * cosAlphaPow; } inline float materials::Phong::evalPDFInternal( const Vec& perfectReflect, const Vec& outgoing ) const { float cosAlpha = max(0.0f, outgoing.dot(perfectReflect)); float cosAlphaPow = std::pow(cosAlpha, exponent); return scaleProb * cosAlphaPow; } Vec materials::Phong::evalBSDFLocal( const Vec& incoming, const Vec& outgoing ) const { // See Lafortune & Willems <http://www.graphics.cornell.edu/~eric/Phong.html>. if (!math::localSameHemisphere(incoming, outgoing)) { return Vec(0, 0, 0); } Vec perfectReflect(-incoming.x(), -incoming.y(), incoming.z()); return evalBSDFInternal(perfectReflect, outgoing); } float materials::Phong::evalPDFLocal( const Vec& incoming, const Vec& outgoing ) const { if (!math::localSameHemisphere(incoming, outgoing)) { return 0.0f; } Vec perfectReflect(-incoming.x(), -incoming.y(), incoming.z()); return evalPDFInternal(perfectReflect, outgoing); } void materials::Phong::sampleLocal( Randomness& rng, const Vec& incoming, Vec* outgoingOut, Vec* bsdfOut, float* pdfOut ) const { // See Lafortune & Willems <http://www.graphics.cornell.edu/~eric/Phong.html> // for a derivation of the sampling procedure and PDF. Vec perfectReflect(-incoming.x(), -incoming.y(), incoming.z()); Vec reflectTangent; Vec reflectBinormal; math::coordSystem(perfectReflect, &reflectTangent, &reflectBinormal); /* The below procedure should produce unit vectors. * * Verify using this Mathematica code: * @code * R[a_] := (invExponent = 1/(20+1); * cosTheta = RandomReal[{0, 1}]^invExponent; * sinTheta = Sqrt[1 - cosTheta*cosTheta]; * phi = 2*Pi*RandomReal[{0, 1}]; * {Cos[phi]*sinTheta, cosTheta, Sin[phi]*sinTheta}) * * LenR[a_] := Norm[R[a]] * * ListPointPlot3D[Map[R, Range[1000]], BoxRatios -> Automatic] * * LenR /@ Range[1000] * * @endcode */ float cosTheta = std::pow(rng.nextUnitFloat(), invExponent); float sinTheta = sqrtf(1.0f - cosTheta * cosTheta); float phi = math::TWO_PI * rng.nextUnitFloat(); Vec local(cosf(phi) * sinTheta, sinf(phi) * sinTheta, cosTheta); // Here, "local" being the space of the perfect reflection vector and // "world" being the space of the normal. *outgoingOut = math::localToWorld( local, reflectTangent, reflectBinormal, perfectReflect ); *bsdfOut = evalBSDFInternal(perfectReflect, *outgoingOut); *pdfOut = evalPDFInternal(perfectReflect, *outgoingOut); } bool materials::Phong::shouldDirectIlluminate() const { return true; }
28
80
0.679836
[ "vector" ]
f8439615bbfd9c26320ecf03652fc4462817431a
5,267
hpp
C++
asmd/eita/ScorePerfmMatch_v170503.hpp
00sapo/ASMD
48e021f98d5fbecd09bed1cdd58024d9b471fad4
[ "MIT" ]
6
2021-09-18T08:36:26.000Z
2022-03-25T16:37:04.000Z
asmd/eita/ScorePerfmMatch_v170503.hpp
00sapo/ASMD
48e021f98d5fbecd09bed1cdd58024d9b471fad4
[ "MIT" ]
4
2021-04-22T15:01:26.000Z
2021-04-22T15:01:28.000Z
asmd/eita/ScorePerfmMatch_v170503.hpp
00sapo/ASMD
48e021f98d5fbecd09bed1cdd58024d9b471fad4
[ "MIT" ]
3
2021-07-13T15:11:38.000Z
2021-11-26T07:38:00.000Z
/* Copyright 2019 Eita Nakamura 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 SCOREPERFMMATCH_HPP #define SCOREPERFMMATCH_HPP #include<iostream> #include<fstream> #include<string> #include<sstream> #include<vector> #include<stdio.h> #include<stdlib.h> #include<cmath> #include<iomanip> #include<cassert> #include<algorithm> #define printOn false using namespace std; class ScorePerfmMatchEvt{ public: string ID; double ontime; double offtime; string sitch; int onvel; int offvel; int channel; int matchStatus;//0(with corresponding score time)/1(without corresponding score time; atemporal event)/-1(note match if errorInd=2,3) int stime; string fmt1ID; int errorInd;//0(correct)/1(pitch error)/2(note-wise extra note, &)/3(cluster-wise extra note, *) string skipInd;//0(beginning)/1(resumption point)/- or +(otherwise) ScorePerfmMatchEvt(){}//end ScorePerfmMatchEvt ~ScorePerfmMatchEvt(){}//end ~ScorePerfmMatchEvt };//end class ScorePerfmMatchEvt class MissingNote{ public: int stime; string fmt1ID; MissingNote(){}//end MissingNote ~MissingNote(){}//end ~MissingNote };//end class MissingNote class ScorePerfmMatch{ public: vector<string> comments; vector<ScorePerfmMatchEvt> evts; vector<MissingNote> missingNotes; string version; ScorePerfmMatch(){}//end ScorePerfmMatch ScorePerfmMatch(ScorePerfmMatch const &match){ comments=match.comments; evts=match.evts; missingNotes=match.missingNotes; }//end ScorePerfmMatch ~ScorePerfmMatch(){}//end ~ScorePerfmMatch void ReadFile(string inputFile){ comments.clear(); evts.clear(); missingNotes.clear(); vector<int> v(100); vector<double> d(100); vector<string> s(100); stringstream ss; ScorePerfmMatchEvt evt; ifstream ifs(inputFile.c_str()); if(!ifs.is_open()){cout<<"File not found: "<<inputFile<<endl; assert(false);} while(ifs>>s[0]){ if(s[0][0]=='/'){ if(s[0]=="//Version:"){ ifs>>s[1]; if(s[1]!="ScorePerfmMatch_v170503"){ if(printOn){ cout<<"Warning: File version is not ScorePerfmMatch_v170503: "<<s[1]<<endl; cout<<"Warning: File version will be replcaed when saved"<<endl; }//endif }//endif getline(ifs,s[99]); continue; }else if(s[0].find("Missing")!=string::npos){ MissingNote missingNote; ifs>>missingNote.stime>>missingNote.fmt1ID; missingNotes.push_back(missingNote); getline(ifs,s[99]); continue; }//endif getline(ifs,s[99]); comments.push_back(s[99]); continue; }else if(s[0][0]=='#'){ getline(ifs,s[99]); continue; }//endif evt.ID=s[0]; ifs>>evt.ontime>>evt.offtime>>evt.sitch>>evt.onvel>>evt.offvel>>evt.channel; ifs>>evt.matchStatus>>evt.stime>>evt.fmt1ID>>evt.errorInd>>evt.skipInd; evts.push_back(evt); getline(ifs,s[99]); }//endwhile ifs.close(); }//end ReadFile void ReadOldMissingNotes(string inputFile){ missingNotes.clear(); vector<int> v(100); vector<double> d(100); vector<string> s(100); stringstream ss; ScorePerfmMatchEvt evt; ifstream ifs(inputFile.c_str()); if(!ifs.is_open()){cout<<"File not found: "<<inputFile<<endl; assert(false);} while(ifs>>s[0]){ if(s[0][0]=='#'){ ifs>>s[1]; if(s[1]=="missing"){ MissingNote missingNote; ifs>>missingNote.stime>>missingNote.fmt1ID; missingNotes.push_back(missingNote); getline(ifs,s[99]); continue; }//endif getline(ifs,s[99]); continue; }//endif getline(ifs,s[99]); }//endwhile ifs.close(); }//end ReadOldMissingNotes void WriteFile(string outputFile){ ofstream ofs(outputFile.c_str()); ofs<<"//Version: ScorePerfmMatch_v170503\n"; for(int i=0;i<comments.size();i+=1){ ofs<<"//"<<comments[i]<<"\n"; }//endfor i for(int n=0;n<evts.size();n+=1){ ScorePerfmMatchEvt evt=evts[n]; ofs<<evt.ID<<"\t"<<fixed<<setprecision(6)<<evt.ontime<<"\t"<<evt.offtime<<"\t"<<evt.sitch<<"\t"<<evt.onvel<<"\t"<<evt.offvel<<"\t"<<evt.channel<<"\t"; ofs<<evt.matchStatus<<"\t"<<evt.stime<<"\t"<<evt.fmt1ID<<"\t"<<evt.errorInd<<"\t"<<evt.skipInd<<"\n"; }//endfor n for(int i=0;i<missingNotes.size();i+=1){ ofs<<"//Missing "<<missingNotes[i].stime<<"\t"<<missingNotes[i].fmt1ID<<"\n"; }//endfor i ofs.close(); }//end WriteFile };//end class ScorePerfmMatch #endif // SCOREPERFMMATCH_HPP
31.538922
460
0.700778
[ "vector" ]
f84c20b0fecaa2e3ce1962d29db58d19e18a345e
7,976
cc
C++
src/cx/cursor.cc
dgoffredo/clang-uml
3b0a454e4e85aee06168439660f0fd71dc4b7a75
[ "Apache-2.0" ]
10
2021-11-16T01:08:05.000Z
2022-03-15T23:51:11.000Z
src/cx/cursor.cc
dgoffredo/clang-uml
3b0a454e4e85aee06168439660f0fd71dc4b7a75
[ "Apache-2.0" ]
8
2021-11-16T21:29:41.000Z
2022-03-21T21:22:00.000Z
src/cx/cursor.cc
dgoffredo/clang-uml
3b0a454e4e85aee06168439660f0fd71dc4b7a75
[ "Apache-2.0" ]
2
2021-12-04T20:20:06.000Z
2022-02-08T06:33:27.000Z
/** * src/cx/cursor.cc * * Copyright (c) 2021 Bartek Kryza <bkryza@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 "cx/cursor.h" namespace clanguml::cx { cursor::cursor() : m_cursor{clang_getNullCursor()} { } cursor::cursor(CXCursor &&c) : m_cursor{std::move(c)} { } cursor::cursor(const CXCursor &c) : m_cursor{c} { } cursor::cursor(const cursor &c) : m_cursor{c.get()} { } bool cursor::operator==(const cursor &b) const { return clang_equalCursors(m_cursor, b.get()); } cx::type cursor::type() const { return {clang_getCursorType(m_cursor)}; } std::string cursor::display_name() const { return to_string(clang_getCursorDisplayName(m_cursor)); } std::string cursor::spelling() const { return to_string(clang_getCursorSpelling(m_cursor)); } bool cursor::is_void() const { // Why do I have to do this like this? return spelling() == "void"; } /** * @brief Return fully qualified cursor spelling * * This method generates a fully qualified name for the cursor by * traversing the namespaces upwards. * * TODO: Add caching of this value. * * @return Fully qualified cursor spelling */ std::string cursor::fully_qualified() const { std::list<std::string> res; cursor iterator{m_cursor}; if (iterator.spelling().empty()) return {}; int limit = 100; while (iterator.kind() != CXCursor_TranslationUnit) { auto name = iterator.spelling(); if (!name.empty()) res.push_front(iterator.spelling()); iterator = iterator.semantic_parent(); if (limit-- == 0) throw std::runtime_error(fmt::format( "Generating fully qualified name for '{}' failed at: '{}'", spelling(), fmt::join(res, "::"))); } return fmt::format("{}", fmt::join(res, "::")); } cursor cursor::referenced() const { return cx::cursor{clang_getCursorReferenced(m_cursor)}; } cursor cursor::semantic_parent() const { return {clang_getCursorSemanticParent(m_cursor)}; } cursor cursor::lexical_parent() const { return {clang_getCursorLexicalParent(m_cursor)}; } CXCursorKind cursor::kind() const { return m_cursor.kind; } std::string cursor::kind_spelling() const { return to_string(clang_getCursorKindSpelling(m_cursor.kind)); } cursor cursor::definition() const { return clang_getCursorDefinition(m_cursor); } bool cursor::is_definition() const { return clang_isCursorDefinition(m_cursor); } bool cursor::is_declaration() const { return clang_isDeclaration(kind()); } bool cursor::is_forward_declaration() const { auto definition = clang_getCursorDefinition(m_cursor); if (clang_equalCursors(definition, clang_getNullCursor())) return true; return !clang_equalCursors(m_cursor, definition); } bool cursor::is_invalid_declaration() const { return clang_isInvalidDeclaration(m_cursor); } CXSourceLocation cursor::location() const { return clang_getCursorLocation(m_cursor); } bool cursor::is_reference() const { return clang_isReference(kind()); } bool cursor::is_expression() const { return clang_isExpression(kind()); } bool cursor::is_statement() const { return clang_isStatement(kind()); } bool cursor::is_namespace() const { return kind() == CXCursor_Namespace; } bool cursor::is_attribute() const { return clang_isAttribute(kind()); } bool cursor::has_attrs() const { return clang_Cursor_hasAttrs(m_cursor); } bool cursor::is_invalid() const { return clang_isInvalid(kind()); } bool cursor::is_translation_unit() const { return clang_isTranslationUnit(kind()); } bool cursor::is_preprocessing() const { return clang_isPreprocessing(kind()); } bool cursor::is_method_virtual() const { return clang_CXXMethod_isVirtual(m_cursor); } bool cursor::is_static() const { return clang_Cursor_getStorageClass(m_cursor) == CX_SC_Static; } bool cursor::is_method_static() const { return clang_CXXMethod_isStatic(m_cursor); } bool cursor::is_method_const() const { return clang_CXXMethod_isConst(m_cursor); } bool cursor::is_method_pure_virtual() const { return clang_CXXMethod_isPureVirtual(m_cursor); } bool cursor::is_method_defaulted() const { return clang_CXXMethod_isDefaulted(m_cursor); } bool cursor::is_method_parameter() const { return kind() == CXCursor_ParmDecl; } CXVisibilityKind cursor::visibitity() const { return clang_getCursorVisibility(m_cursor); } CXAvailabilityKind cursor::availability() const { return clang_getCursorAvailability(m_cursor); } CX_CXXAccessSpecifier cursor::cxxaccess_specifier() const { return clang_getCXXAccessSpecifier(m_cursor); } cx::type cursor::underlying_type() const { return clang_getTypedefDeclUnderlyingType(m_cursor); } int cursor::template_argument_count() const { return clang_Cursor_getNumTemplateArguments(m_cursor); } CXTemplateArgumentKind cursor::template_argument_kind(unsigned i) const { return clang_Cursor_getTemplateArgumentKind(m_cursor, i); } cx::type cursor::template_argument_type(unsigned i) const { return clang_Cursor_getTemplateArgumentType(m_cursor, i); } long long cursor::template_argument_value(unsigned i) const { return clang_Cursor_getTemplateArgumentValue(m_cursor, i); } cursor cursor::specialized_cursor_template() const { return clang_getSpecializedCursorTemplate(m_cursor); } CXTranslationUnit cursor::translation_unit() const { return clang_Cursor_getTranslationUnit(m_cursor); } bool cursor::is_template_parameter_variadic() const { const auto &tokens = tokenize(); return tokens.size() > 2 && tokens[1] == "..."; } std::string cursor::usr() const { return to_string(clang_getCursorUSR(m_cursor)); } CXSourceRange cursor::extent() const { return clang_getCursorExtent(m_cursor); } std::vector<std::string> cursor::tokenize() const { auto range = extent(); std::vector<std::string> res; CXToken *toks; unsigned toks_count{0}; auto tu = translation_unit(); clang_tokenize(tu, range, &toks, &toks_count); for (int i = 0; i < toks_count; i++) { res.push_back(to_string(clang_getTokenSpelling(tu, toks[i]))); } return res; } std::string cursor::default_value() const { assert(is_method_parameter()); auto toks = tokenize(); std::string res; auto it = std::find(toks.begin(), toks.end(), "="); if (it != toks.end()) { res = fmt::format("{}", fmt::join(it + 1, toks.end(), "")); } return res; } std::vector<std::string> cursor::tokenize_template_parameters() const { auto toks = tokenize(); std::vector<std::string> res; bool inside_template{false}; bool is_namespace{false}; for (int i = 0; i < toks.size(); i++) { // libclang returns ">..>>" in template as a single token... auto t = toks[i]; if (std::all_of( t.begin(), t.end(), [](const char &c) { return c == '>'; })) { toks[i] = ">"; for (int j = 0; j < t.size() - 1; j++) toks.insert(toks.begin() + i, ">"); } } auto template_start = std::find(toks.begin(), toks.end(), "<"); auto template_end = std::find(toks.rbegin(), toks.rend(), ">"); decltype(res) template_contents( template_start + 1, template_end.base() - 1); return clanguml::util::split( fmt::format("{}", fmt::join(template_contents, "")), ","); } const CXCursor &cursor::get() const { return m_cursor; } }
24.243161
80
0.689694
[ "vector" ]
f859104980569114f2ebed0e24d93b65c8f4ce7a
11,996
cpp
C++
src/qt/giftcardtablemodel.cpp
BraginaT/TriveCoin
08735a1e83ad2ff222d6afe4aa81d07beeccf290
[ "MIT" ]
null
null
null
src/qt/giftcardtablemodel.cpp
BraginaT/TriveCoin
08735a1e83ad2ff222d6afe4aa81d07beeccf290
[ "MIT" ]
null
null
null
src/qt/giftcardtablemodel.cpp
BraginaT/TriveCoin
08735a1e83ad2ff222d6afe4aa81d07beeccf290
[ "MIT" ]
null
null
null
// Copyright 2016 Strength in Numbers Foundation #include "giftcarddatamanager.h" #include "giftcardtablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "ui_interface.h" #include "base58.h" #include <QFont> #include <QColor> extern int VanityGen(int addrtype, char *prefix, char *pubKey, char *privKey); const QString GiftCardTableModel::Gift = "G"; // Amount column is right-aligned it contains numbers static int column_alignments[] = { Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter }; struct GiftCardTableEntry { enum Type { Sending, Receiving, Gift }; Type type; QString label; QString address; QString privkey; QString generated; float balance; GiftCardTableEntry() {} GiftCardTableEntry(Type type, const QString &label, const QString &address, const QString &generated, const float balance): type(type), label(label), address(address), generated(generated), balance(balance) {} }; struct GiftCardTableEntryLessThan { bool operator()(const GiftCardTableEntry &a, const GiftCardTableEntry &b) const { return a.address < b.address; } bool operator()(const GiftCardTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const GiftCardTableEntry &b) const { return a < b.address; } }; // Private implementation class GiftCardTablePriv { public: GiftCardDataManager gcdb; QList<GiftCardTableEntry> cachedGiftCardTable; GiftCardTableModel *parent; GiftCardTablePriv(GiftCardDataManager gcdb, GiftCardTableModel *parent): gcdb(gcdb), parent(parent) {} void refreshAddressTable() { QList<GiftCardDataEntry> cards; cachedGiftCardTable.clear(); if (gcdb.allCards(cards,QString("label"))) { foreach (GiftCardDataEntry entry, cards) { cachedGiftCardTable.append(GiftCardTableEntry(GiftCardTableEntry::Gift,entry.label, entry.pubkey, entry.generated, entry.balance)); // printf("%d | %s | %s\n", entry.id, entry.pubkey.toStdString().c_str(), entry.label.toStdString().c_str()); } qSort(cachedGiftCardTable.begin(), cachedGiftCardTable.end(), GiftCardTableEntryLessThan()); } else OutputDebugStringF("! FAIL gcdb.allCards\n"); } void updateEntry(const QString &address, const QString &label, const QString &generated, const float balance, int status) { GiftCardDataEntry card; // Find address / label in model QList<GiftCardTableEntry>::iterator lower = qLowerBound( cachedGiftCardTable.begin(), cachedGiftCardTable.end(), address, GiftCardTableEntryLessThan()); QList<GiftCardTableEntry>::iterator upper = qUpperBound( cachedGiftCardTable.begin(), cachedGiftCardTable.end(), address, GiftCardTableEntryLessThan()); int lowerIndex = (lower - cachedGiftCardTable.begin()); int upperIndex = (upper - cachedGiftCardTable.begin()); bool inModel = (lower != upper); GiftCardTableEntry::Type newEntryType = GiftCardTableEntry::Gift; switch(status) { case CT_NEW: if(inModel) { OutputDebugStringF("Warning: GiftCardTablePriv::updateEntry: Got CT_NOW, but entry is already in model\n"); break; } gcdb.readCard(address, card); parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedGiftCardTable.insert(lowerIndex, GiftCardTableEntry(newEntryType, label, address, card.generated, 0.0)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { OutputDebugStringF("Warning: GiftCardTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\n"); break; } gcdb.readCard(address, card); lower->type = newEntryType; lower->label = label; lower->generated = card.generated; lower->balance = card.balance; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { OutputDebugStringF("Warning: GiftCardTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\n"); break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedGiftCardTable.erase(lower, upper); parent->endRemoveRows(); parent->emitDataChanged(lowerIndex); break; } } int size() { return cachedGiftCardTable.size(); } GiftCardTableEntry *index(int idx) { if(idx >= 0 && idx < cachedGiftCardTable.size()) { return &cachedGiftCardTable[idx]; } else { return 0; } } }; GiftCardTableModel::GiftCardTableModel(GiftCardDataManager gcdb, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),gcdb(gcdb),priv(0) { columns << tr("Label") << tr("Address") << tr("Generated") << tr("Balance"); priv = new GiftCardTablePriv(gcdb, this); priv->refreshAddressTable(); } GiftCardTableModel::~GiftCardTableModel() { delete priv; } int GiftCardTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int GiftCardTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant GiftCardTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); GiftCardTableEntry *rec = static_cast<GiftCardTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: if(rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; case Generated: return rec->generated; case Balance: return rec->balance; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::bitcoinAddressFont(); } return font; } else if (role == TypeRole) { return Gift; } else if (role == Qt::TextAlignmentRole) return column_alignments[index.column()]; return QVariant(); } bool GiftCardTableModel::setData(const QModelIndex & index, const QVariant & value, int role) { if(!index.isValid()) return false; GiftCardTableEntry *rec = static_cast<GiftCardTableEntry*>(index.internalPointer()); editStatus = OK; if(role == Qt::EditRole) { switch(index.column()) { case Label: case Generated: case Balance: updateEntry(rec->address, value.toString(), rec->generated, rec->balance, CT_UPDATED); break; case Address: // Can't edit addresses / left as placeholder break; } return true; } return false; } QVariant GiftCardTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch(section) { case Label: return tr("Name you assigned to this Gift*"); case Address: return tr("Destination address of funds"); case Generated: return tr("Date / Time this card was (re)generated"); case Balance: return tr("Balance queried from live blockchain"); } } } return QVariant(); } Qt::ItemFlags GiftCardTableModel::flags(const QModelIndex & index) const { if(!index.isValid()) return 0; GiftCardTableEntry *rec = static_cast<GiftCardTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if ((rec->type == GiftCardTableEntry::Gift) && (index.column()==Label)) { // retval |= Qt::ItemIsEditable; } return retval; } QModelIndex GiftCardTableModel::index(int row, int column, const QModelIndex & parent) const { Q_UNUSED(parent); GiftCardTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void GiftCardTableModel::updateEntry(const QString &address, const QString &label, const QString &generated, const float balance, int status) { priv->updateEntry(address, label, generated, balance, status); if (status != CT_DELETED) emitDataChanged(lookupAddress(address)); } QString GiftCardTableModel::addRow(const QString &type, const QString &label, const QString &address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); char strPubKey[256], strPrivKey[256]; editStatus = OK; if (type == Gift) { // Generate a new address to associate with given label VanityGen(39, "Gift", strPubKey, strPrivKey); // printf("Address: %s\tPrivkey: %s\n", strPubKey, strPrivKey); strAddress = std::string(strPubKey); gcdb.addCard(QString::fromStdString(std::string(strPubKey)), QString::fromStdString(std::string(strPrivKey)), label); } else { return QString(); } updateEntry(QString::fromStdString(strAddress), label, QString(""), 0.0, CT_NEW); // strAddress += ":" + std::string(strPrivKey); return QString::fromStdString(strAddress); } bool GiftCardTableModel::removeRows(int row, int count, const QModelIndex & parent) { Q_UNUSED(parent); GiftCardTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == GiftCardTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } updateEntry(rec->address, rec->label, rec->generated, rec->balance, CT_DELETED); return true; } /* Look up label for address in address book, if not found return empty string. */ QString GiftCardTableModel::labelForAddress(const QString &address) const { QString label; if (gcdb.readCardAttVal(address, "label", label)) { return label; } else return QString(); } int GiftCardTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void GiftCardTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); } void GiftCardTableModel::refreshAddressTable(void) { priv->refreshAddressTable(); emit dataChanged(index(0, 0, QModelIndex()), index(priv->size()-1, 0, QModelIndex())); } GiftCardDataManager GiftCardTableModel::giftCardDataBase(void) { return gcdb; }
28.630072
147
0.618123
[ "model" ]
f85c24e77b0996165bb55fd02d08c1e217eada4a
795
hpp
C++
include/Materials/Dielectic.hpp
Ursanon/RayTracing
8cc51b9b7845ccd2ef99704d7cfebc301f36b315
[ "MIT" ]
2
2020-01-06T14:31:16.000Z
2020-01-07T08:15:51.000Z
include/Materials/Dielectic.hpp
Ursanon/RayTracing
8cc51b9b7845ccd2ef99704d7cfebc301f36b315
[ "MIT" ]
null
null
null
include/Materials/Dielectic.hpp
Ursanon/RayTracing
8cc51b9b7845ccd2ef99704d7cfebc301f36b315
[ "MIT" ]
null
null
null
#ifndef DIELECTIC_HPP_ #define DIELECTIC_HPP_ #include "Materials/Material.hpp" namespace rt { namespace materials { class Dielectric : public Material { private: struct refract_data { const Vector3f normal; const float index; const float cosine; }; public: explicit Dielectric(const float& refractive_index); bool refract(const Vector3f& vector, const Vector3f& normal, const float& refractive_index, Vector3f& refracted) const; virtual bool scatter(const Ray& r_in, const HitInfo& hit, Vector3f& attenuation, Ray& scattered) const; private: refract_data calculate_refract_data(Vector3f direction, Vector3f normal) const; private: const float refractive_index_; const Vector3f albedo_; }; } } #endif // !DIELECTIC_HPP_
22.083333
122
0.727044
[ "vector" ]
f85e502ec5ae2785540604309d4ac50ec1845c71
703
hpp
C++
src/core.hpp
KeNaCo/sm-pssm-demo
bb6355b7225d9e6d2cb82271029956b96462272b
[ "MIT" ]
null
null
null
src/core.hpp
KeNaCo/sm-pssm-demo
bb6355b7225d9e6d2cb82271029956b96462272b
[ "MIT" ]
null
null
null
src/core.hpp
KeNaCo/sm-pssm-demo
bb6355b7225d9e6d2cb82271029956b96462272b
[ "MIT" ]
null
null
null
/* * core.h * * Created on: Oct 13, 2014 * Author: kenaco */ #ifndef CORE_H_ #define CORE_H_ #include <SDL.h> #include <SDL_video.h> #include <glbinding/gl/gl.h> #include <assimp/Importer.hpp> #include "renderer.hpp" //#include "handler.hpp" /* * Controller class */ class Core { private: bool quit; // Timing int actTime; int lastTime; int delta; //Controls float v; //View classes SDL_Window* window; Renderer* renderer; //Model class Scene* scene; void updateDelta(); void updateControls(); void updateFpsLog(); public: Core(); Core(std::string filename); virtual ~Core(); void loadAssets(std::string fileName); void renderLoop(); }; #endif /* CORE_H_ */
12.781818
39
0.665718
[ "model" ]
f85e686d18e165a47ce32c97cffebde10a1743ad
1,503
hpp
C++
include/sunspec/utils.hpp
EVerest/libsunspec
64b35a1083f442b8fedb4740c8b74605e704b0bc
[ "Apache-2.0" ]
7
2022-01-31T16:12:59.000Z
2022-03-15T11:54:31.000Z
include/sunspec/utils.hpp
EVerest/libsunspec
64b35a1083f442b8fedb4740c8b74605e704b0bc
[ "Apache-2.0" ]
1
2022-01-11T14:05:49.000Z
2022-01-11T14:05:49.000Z
include/sunspec/utils.hpp
EVerest/libsunspec
64b35a1083f442b8fedb4740c8b74605e704b0bc
[ "Apache-2.0" ]
1
2022-03-13T07:17:00.000Z
2022-03-13T07:17:00.000Z
// SPDX-License-Identifier: Apache-2.0 // Copyright 2020 - 2021 Pionix GmbH and Contributors to EVerest #ifndef SUNSPEC_UTILS_HPP #define SUNSPEC_UTILS_HPP #include <string> #include <vector> #include <cstdint> #include <cmath> #include <nlohmann/json.hpp> #include <modbus/modbus_client.hpp> #include <sunspec/commons.hpp> #include <sunspec/types.hpp> using json = nlohmann::json; namespace everest { namespace sunspec { namespace utils { std::string bytevector_to_string(const std::vector<uint8_t>& bytearray); uint16_t bytevector_to_uint16(const std::vector<uint8_t>& bytevector); int16_t bytevector_to_int16(const std::vector<uint8_t>& bytevector); bool is_sunspec_identifier(const std::string& str); bool is_sunspec_identifier(const std::vector<uint8_t>& bytearray); bool is_zero_length_model(uint16_t model_id, uint16_t model_length); bool is_common_model(uint16_t model_id); template <typename IterableType> std::string iterable_to_string(const IterableType& iterable); json json_from_model_id(const uint16_t model_id); bool json_contains(const json& json_, const std::string& key); types::ModbusReadFunction make_modbus_read_function(const everest::modbus::ModbusClient& modbus_client, const uint8_t& unit_id); template <typename T> float apply_scale_factor(T point_value, int16_t scale_factor) { return point_value * pow(10, scale_factor); } } // namespace utils } // namespace sunspec } // namespace everest #endif
34.159091
132
0.762475
[ "vector" ]
f85ec985f15ea769d60aa04a05efaee74fcb55d7
7,270
cc
C++
Engine/addons/resource/DXTextureDecompress.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
26
2015-01-15T12:57:40.000Z
2022-02-16T10:07:12.000Z
Engine/addons/resource/DXTextureDecompress.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
null
null
null
Engine/addons/resource/DXTextureDecompress.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
17
2015-02-18T07:51:31.000Z
2020-06-01T01:10:12.000Z
/**************************************************************************** Copyright (c) 2006 Simon Brown si@sjbrown.co.uk Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn 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 "resource/resource_stdneb.h" #include "DXTextureDecompress.h" namespace Resources { DXTextureDecompress::DXTextureDecompress(void) { } DXTextureDecompress::~DXTextureDecompress(void) { } //------------------------------------------------------------------------ void DXTextureDecompress::DecompressImage (uint32* destData, const int imageW, const int imageH, const uint32* srcData, int flags) { // fix any bad flags //flags = FixFlags( flags ); // initialise the block input output squish::u8 const* sourceBlock = reinterpret_cast< squish::u8 const* >( srcData ); squish::u8* rgba = reinterpret_cast< squish::u8* >(destData); int bytesPerBlock = ( ( flags & squish::kDxt1 ) != 0 ) ? 8 : 16; // loop over blocks for( int y = 0; y < imageH; y += 4 ) { for( int x = 0; x < imageW; x += 4 ) { // decompress the block squish::u8 targetRgba[4*16]; squish::Decompress( targetRgba, sourceBlock, flags ); // write the decompressed pixels to the correct image locations squish::u8 const* sourcePixel = targetRgba; for( int py = 0; py < 4; ++py ) { for( int px = 0; px < 4; ++px ) { // get the target location int sx = x + px; int sy = y + py; if( sx < imageW && sy < imageH ) { squish::u8* targetPixel = rgba + 4*( imageW*sy + sx ); // copy the rgba value for( int i = 0; i < 4; ++i ) *targetPixel++ = *sourcePixel++; } else { // skip this pixel as its outside the image sourcePixel += 4; } } } // advance sourceBlock += bytesPerBlock; } } } //------------------------------------------------------------------------ } namespace squish { void Decompress( u8* rgba, void const* block, int flags ) { // fix any bad flags //flags = FixFlags( flags ); // get the block locations void const* colourBlock = block; void const* alphaBock = block; if( ( flags & ( kDxt3 | kDxt5 ) ) != 0 ) colourBlock = reinterpret_cast< u8 const* >( block ) + 8; // decompress colour DecompressColour( rgba, colourBlock, ( flags & kDxt1 ) != 0 ); // decompress alpha separately if necessary if( ( flags & kDxt3 ) != 0 ) DecompressAlphaDxt3( rgba, alphaBock ); else if( ( flags & kDxt5 ) != 0 ) DecompressAlphaDxt5( rgba, alphaBock ); } static int Unpack565( u8 const* packed, u8* colour ) { // build the packed value int value = ( int )packed[0] | ( ( int )packed[1] << 8 ); // get the components in the stored range u8 red = ( u8 )( ( value >> 11 ) & 0x1f ); u8 green = ( u8 )( ( value >> 5 ) & 0x3f ); u8 blue = ( u8 )( value & 0x1f ); // scale up to 8 bits colour[0] = ( red << 3 ) | ( red >> 2 ); colour[1] = ( green << 2 ) | ( green >> 4 ); colour[2] = ( blue << 3 ) | ( blue >> 2 ); colour[3] = 255; // return the value return value; } //------------------------------------------------------------------------ void DecompressColour( u8* rgba, void const* block, bool isDxt1 ) { // get the block bytes u8 const* bytes = reinterpret_cast< u8 const* >( block ); // unpack the endpoints u8 codes[16]; int a = Unpack565( bytes, codes ); int b = Unpack565( bytes + 2, codes + 4 ); // generate the midpoints for( int i = 0; i < 3; ++i ) { int c = codes[i]; int d = codes[4 + i]; if( isDxt1 && a <= b ) { codes[8 + i] = ( u8 )( ( c + d )/2 ); codes[12 + i] = 0; } else { codes[8 + i] = ( u8 )( ( 2*c + d )/3 ); codes[12 + i] = ( u8 )( ( c + 2*d )/3 ); } } // fill in alpha for the intermediate values codes[8 + 3] = 255; codes[12 + 3] = ( isDxt1 && a <= b ) ? 0 : 255; // unpack the indices u8 indices[16]; for( int i = 0; i < 4; ++i ) { u8* ind = indices + 4*i; u8 packed = bytes[4 + i]; ind[0] = packed & 0x3; ind[1] = ( packed >> 2 ) & 0x3; ind[2] = ( packed >> 4 ) & 0x3; ind[3] = ( packed >> 6 ) & 0x3; } // store out the colours for( int i = 0; i < 16; ++i ) { u8 offset = 4*indices[i]; for( int j = 0; j < 4; ++j ) rgba[4*i + j] = codes[offset + j]; } } //------------------------------------------------------------------------ void DecompressAlphaDxt3( u8* rgba, void const* block ) { u8 const* bytes = reinterpret_cast< u8 const* >( block ); // unpack the alpha values pairwise for( int i = 0; i < 8; ++i ) { // quantise down to 4 bits u8 quant = bytes[i]; // unpack the values u8 lo = quant & 0x0f; u8 hi = quant & 0xf0; // convert back up to bytes rgba[8*i + 3] = lo | ( lo << 4 ); rgba[8*i + 7] = hi | ( hi >> 4 ); } } //------------------------------------------------------------------------ void DecompressAlphaDxt5( u8* rgba, void const* block ) { // get the two alpha values u8 const* bytes = reinterpret_cast< u8 const* >( block ); int alpha0 = bytes[0]; int alpha1 = bytes[1]; // compare the values to build the codebook u8 codes[8]; codes[0] = ( u8 )alpha0; codes[1] = ( u8 )alpha1; if( alpha0 <= alpha1 ) { // use 5-alpha codebook for( int i = 1; i < 5; ++i ) codes[1 + i] = ( u8 )( ( ( 5 - i )*alpha0 + i*alpha1 )/5 ); codes[6] = 0; codes[7] = 255; } else { // use 7-alpha codebook for( int i = 1; i < 7; ++i ) codes[1 + i] = ( u8 )( ( ( 7 - i )*alpha0 + i*alpha1 )/7 ); } // decode the indices u8 indices[16]; u8 const* src = bytes + 2; u8* dest = indices; for( int i = 0; i < 2; ++i ) { // grab 3 bytes int value = 0; for( int j = 0; j < 3; ++j ) { int byte = *src++; value |= ( byte << 8*j ); } // unpack 8 3-bit values from it for( int j = 0; j < 8; ++j ) { int index = ( value >> 3*j ) & 0x7; *dest++ = ( u8 )index; } } // write out the indexed codebook values for( int i = 0; i < 16; ++i ) rgba[4*i + 3] = codes[indices[i]]; } }
26.925926
85
0.53879
[ "3d" ]
f86451488a6945086cb1479e572e4d6646c6fea0
1,452
cpp
C++
CTN_05_Hardware_3D_DirectX/src/HorizontalBlurPass.cpp
TheUnicum/CTN_05_Hardware_3D_DirectX
39940fb0466ff5b419d7f7c4cf55ee1f90784baa
[ "Apache-2.0" ]
null
null
null
CTN_05_Hardware_3D_DirectX/src/HorizontalBlurPass.cpp
TheUnicum/CTN_05_Hardware_3D_DirectX
39940fb0466ff5b419d7f7c4cf55ee1f90784baa
[ "Apache-2.0" ]
null
null
null
CTN_05_Hardware_3D_DirectX/src/HorizontalBlurPass.cpp
TheUnicum/CTN_05_Hardware_3D_DirectX
39940fb0466ff5b419d7f7c4cf55ee1f90784baa
[ "Apache-2.0" ]
null
null
null
#include "HorizontalBlurPass.h" #include "PixelShader.h" #include "RenderTarget.h" #include "Sink.h" #include "Source.h" #include "Blender.h" #include "Sampler.h" #include "ConstantBuffersEx.h" using namespace Bind; namespace Rgph { HorizontalBlurPass::HorizontalBlurPass(std::string name, Graphics& gfx, unsigned int fullWidth, unsigned int fullHeight) : FullscreenPass(std::move(name), gfx) { AddBind(PixelShader::Resolve(gfx, "ShaderBins\\BlurOutline_PS.cso")); AddBind(Blender::Resolve(gfx, false)); AddBind(Sampler::Resolve(gfx, Sampler::Type::Point, true)); AddBindSink<Bind::RenderTarget>("scratchIn"); AddBindSink<Bind::CachingPixelConstantBufferEx>("kernel"); RegisterSink(DirectBindableSink<CachingPixelConstantBufferEx>::Make("direction", direction)); // the renderTarget is internally sourced and then exported as a Bindable renderTarget = std::make_shared<Bind::ShaderInputRenderTarget>(gfx, fullWidth / 2, fullHeight / 2, 0u); RegisterSource(DirectBindableSource<RenderTarget>::Make("scratchOut", renderTarget)); } // this override is necessary because we cannot (yet) link input bindables directly into // the container of bindables (mainly because vector growth buggers references) void HorizontalBlurPass::Execute(Graphics& gfx) const noxnd { auto buf = direction->GetBuffer(); buf["isHorizontal"] = true; direction->SetBuffer(buf); direction->Bind(gfx); FullscreenPass::Execute(gfx); } }
33.767442
121
0.758264
[ "vector" ]
d38265cf95636c75daa2e2da2ad4819b4b2ba02e
15,562
cpp
C++
src/tiled/tmx_reader.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/tiled/tmx_reader.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/tiled/tmx_reader.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
/* Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <sstream> #include <boost/lexical_cast.hpp> #include "asserts.hpp" #include "base64.hpp" #include "compress.hpp" #include "filesystem.hpp" #include "tmx_reader.hpp" #include "Util.hpp" namespace tiled { using namespace boost::property_tree; namespace { void display_ptree(ptree const& pt) { for(auto& v : pt) { LOG_DEBUG(v.first << ": " << v.second.get_value<std::string>()); display_ptree( v.second ); } } const uint32_t flipped_horizontally_bit = 0x80000000U; const uint32_t flipped_vertically_bit = 0x40000000U; const uint32_t flipped_diagonally_bit = 0x20000000U; const uint32_t flip_mask = ~(flipped_horizontally_bit | flipped_vertically_bit | flipped_diagonally_bit); Orientation convert_orientation(const std::string& o) { if(o == "orthogonal") { return Orientation::ORTHOGONAL; } else if(o == "isometric") { return Orientation::ISOMETRIC; } else if(o == "staggered") { return Orientation::STAGGERED; } else if(o == "hexagonal") { return Orientation::HEXAGONAL; } ASSERT_LOG(false, "Unrecognised value for orientation: " << o); return Orientation::ORTHOGONAL; } RenderOrder convert_renderorder(const std::string& ro) { if(ro == "right-down") { return RenderOrder::RIGHT_DOWN; } else if(ro == "right-up") { return RenderOrder::RIGHT_UP; } else if(ro == "left-down") { return RenderOrder::LEFT_DOWN; } else if(ro == "left-up") { return RenderOrder::LEFT_UP; } ASSERT_LOG(false, "Unrecognised value for renderorder: " << ro); return RenderOrder::RIGHT_DOWN; } ImageFormat convert_image_format(const std::string& fmt) { if(fmt == "png") { return ImageFormat::PNG; } else if(fmt == "bmp") { return ImageFormat::BMP; } else if(fmt == "jpg") { return ImageFormat::JPEG; } else if(fmt == "gif") { return ImageFormat::GIF; } ASSERT_LOG(false, "Unrecognised value for image format: " << fmt); return ImageFormat::NONE; } inline uint32_t make_uint32_le(char n3, char n2, char n1, char n0) { return (static_cast<uint32_t>(static_cast<uint8_t>(n3)) << 24) | (static_cast<uint32_t>(static_cast<uint8_t>(n2)) << 16) | (static_cast<uint32_t>(static_cast<uint8_t>(n1)) << 8) | static_cast<uint32_t>(static_cast<uint8_t>(n0)); } } TmxReader::TmxReader(MapPtr map) : map_(map) { } void TmxReader::parseFile(const std::string& filename) { parseString(sys::read_file(filename)); } void TmxReader::parseString(const std::string& str) { ptree pt; try { std::stringstream ss; ss << str; read_xml(ss, pt); for(auto& v : pt) { if(v.first == "map") { parseMapElement(v.second); } } } catch(xml_parser_error &e) { ASSERT_LOG(false, "Failed to read TMX file " << e.what()); } catch(...) { ASSERT_LOG(false, "Failed to read TMX file with unknown error"); } } void TmxReader::parseMapElement(const boost::property_tree::ptree& pt) { auto attributes = pt.get_child_optional("<xmlattr>"); ASSERT_LOG(attributes, "map elements must have a minimum number of attributes: 'version', 'orientation', 'width', 'height', 'tilewidth', 'tileheight'"); auto version = attributes->get_child("version").data(); auto orientation = attributes->get_child("orientation").data(); map_->setOrientation(convert_orientation(orientation)); auto width = attributes->get<int>("width"); auto height = attributes->get<int>("height"); map_->setDimensions(width, height); auto tilewidth = attributes->get<int>("tilewidth"); auto tileheight = attributes->get<int>("tileheight"); map_->setTileDimensions(tilewidth, tileheight); auto backgroundcolor = attributes->get_child_optional("backgroundcolor"); if(backgroundcolor) { map_->setBackgroundColor(KRE::Color(backgroundcolor->data())); } auto renderorder = attributes->get_child_optional("renderorder"); if(renderorder) { map_->setRenderOrder(convert_renderorder(renderorder->data())); } auto staggerindex = attributes->get_child_optional("staggerindex"); if(staggerindex) { map_->setStaggerIndex(staggerindex->data() == "even" ? StaggerIndex::EVEN : StaggerIndex::ODD); } auto staggerdir = attributes->get_child_optional("staggerdirection"); if(staggerdir) { map_->setStaggerDirection(staggerdir->data() == "rows" ? StaggerDirection::ROWS : StaggerDirection::COLS); } auto hexsidelength = attributes->get_optional<int>("hexsidelength"); if(hexsidelength) { map_->setHexsideLength(*hexsidelength); } for(auto& v : pt) { if(v.first == "properties") { LOG_DEBUG("parse map properties"); auto props = parseProperties(v.second); map_->setProperties(&props); } else if(v.first == "tileset") { parseTileset(v.second); } else if(v.first == "objectgroup") { //parseObjectGroup(v.second); } else if(v.first == "imagelayer") { //parseImageLayer(v.second); } } // parse layer's after other since we might parse tileset's out of order. for(auto& v : pt) { if(v.first == "layer") { map_->addLayer(parseLayerElement(v.second)); } } } void TmxReader::parseTileset(const boost::property_tree::ptree& pt) { auto attributes = pt.get_child_optional("<xmlattr>"); ASSERT_LOG(attributes, "tileset elements must have a minimum number of attributes: 'firstgid'"); int firstgid = attributes->get<int>("firstgid"); TileSet ts(firstgid); auto source = attributes->get_child_optional("source"); if(source) { ASSERT_LOG(false, "read and process tileset data from file: " << source->data()); } auto name = attributes->get_child_optional("name"); if(name) { ts.setName(name->data()); } int max_tile_width = -1; int max_tile_height = -1; auto tilewidth = attributes->get_child_optional("tilewidth"); if(tilewidth) { max_tile_width = tilewidth->get_value<int>(); } auto tileheight = attributes->get_child_optional("tileheight"); if(tileheight) { max_tile_height = tileheight->get_value<int>(); } if(max_tile_width != -1 || max_tile_height != -1) { ts.setTileDimensions(max_tile_width, max_tile_height); } auto spacing = attributes->get_child_optional("spacing"); if(spacing) { ts.setSpacing(spacing->get_value<int>()); } auto margin = attributes->get_child_optional("margin"); if(margin) { ts.setMargin(margin->get_value<int>()); } for(auto& v : pt) { if(v.first == "properties") { auto props = parseProperties(v.second); map_->setProperties(&props); } else if(v.first == "tileoffset") { auto to_attributes = v.second.get_child("<xmlattr>"); int x = to_attributes.get<int>("x"); int y = to_attributes.get<int>("y"); ts.setTileOffset(x, y); } else if(v.first == "image") { ts.setImage(parseImageElement(v.second)); } else if(v.first == "terraintypes") { ts.setTerrainTypes(parseTerrainTypes(v.second)); } else if(v.first == "tile") { ts.addTile(parseTileElement(ts, v.second)); } } map_->addTileSet(ts); } std::vector<Property> TmxReader::parseProperties(const boost::property_tree::ptree& pt) { std::vector<Property> res; // No attributes are expected for(auto& v : pt) { if(v.first == "property") { auto prop = v.second.get_child_optional("<xmlattr>"); if(prop) { auto name = prop->get_child("name").data(); auto value = prop->get_child("value").data(); res.emplace_back(name, value); } } else { LOG_WARN("Ignoring element '" << v.first << "' as child of 'properties' element"); } } return res; } TileImage TmxReader::parseImageElement(const boost::property_tree::ptree& pt) { auto attributes = pt.get_child("<xmlattr>"); TileImage image; auto source = attributes.get_child_optional("source"); if(source) { image.setSource(source->data()); } auto width = attributes.get_child_optional("width"); if(width) { image.setWidth(width->get_value<int>()); } auto height = attributes.get_child_optional("height"); if(height) { image.setHeight(height->get_value<int>()); } auto trans = attributes.get_child_optional("trans"); if(trans) { image.setTransparentColor(KRE::Color(trans->data())); LOG_DEBUG("transparent color set to: " << trans->data() << " : " << KRE::Color(trans->data())); } auto format = attributes.get_child_optional("format"); if(format && !source) { auto img_data = parseImageDataElement(pt.get_child("data")); ASSERT_LOG(!img_data.empty(), "No image data found and no source tag given"); image.setImageData(convert_image_format(format->data()), img_data); } return image; } std::vector<char> TmxReader::parseImageDataElement(const boost::property_tree::ptree& pt) { std::vector<char> res; auto attributes = pt.get_child_optional("<xmlattr>"); if(attributes) { auto encoding = attributes->get_child_optional("encoding"); // really only one type of encoding is specified. if(encoding && encoding->data() == "base64") { std::vector<char> data(pt.data().begin(), pt.data().end()); return base64::b64decode(data); } } return res; } std::vector<uint32_t> TmxReader::parseDataElement(const boost::property_tree::ptree& pt) { std::vector<uint32_t> res; bool is_compressed_zlib = false; bool is_compressed_gzip = false; bool is_base64_encoded = false; bool is_csv_encoded = false; auto attributes = pt.get_child_optional("<xmlattr>"); if(attributes) { auto encoding = attributes->get_child_optional("encoding"); if(encoding && encoding->data() == "base64") { is_base64_encoded = true; } else if(encoding && encoding->data() == "csv") { is_csv_encoded = true; } auto compression = attributes->get_child_optional("compression"); if(compression && compression->data() == "gzip") { ASSERT_LOG(false, "gzip compression not currently supported, use zlib."); is_compressed_gzip = true; } else if(compression && compression->data() == "zlib") { is_compressed_zlib = true; } } if(is_base64_encoded) { std::vector<char> data(pt.data().begin(), pt.data().end()); auto unencoded = base64::b64decode(data); if(is_compressed_zlib) { auto uncompressed = zip::decompress(unencoded); res.reserve(uncompressed.size() / 4); ASSERT_LOG(uncompressed.size() % 4 == 0, "Uncompressed data size must be a multiple of 4, found: " << uncompressed.size()); for(int n = 0; n != uncompressed.size(); n += 4) { res.emplace_back(make_uint32_le(uncompressed[n+3], uncompressed[n+2], uncompressed[n+1], uncompressed[n+0])); } } else if(is_compressed_gzip) { // XXX } } else if(is_csv_encoded) { // CSV encoded. auto& data = pt.data(); for(auto& tile : Util::split(data, ",\r\n")) { try { int value = boost::lexical_cast<int>(tile); res.emplace_back(value); } catch(boost::bad_lexical_cast& e) { ASSERT_LOG(false, "Couldn't convert '" << tile << " to integer value: " << e.what()); } } } else { // is encoded in <tile> elements. for(auto& v : pt) { if(v.first == "tile") { auto tile_attribute = v.second.get_child("<xlmattr>"); uint32_t gid = static_cast<uint32_t>(tile_attribute.get<int>("gid")); res.emplace_back(gid); } else { LOG_WARN("Expected 'tile' child elements, found: " << v.first); } } } return res; } std::vector<Terrain> TmxReader::parseTerrainTypes(const boost::property_tree::ptree& pt) { std::vector<Terrain> res; for(auto& v : pt) { if(v.first == "terrain") { auto name = v.second.get_child("<xmlattr>.name").data(); auto tile_id = v.second.get<int>("<xmlattr>.tile"); res.emplace_back(name, tile_id); } else { LOG_WARN("Expected 'terrain' child elements, found: " << v.first); } } return res; } TileDefinition TmxReader::parseTileElement(const TileSet& ts, const boost::property_tree::ptree& pt) { auto attributes = pt.get_child("<xmlattr>"); uint32_t local_id = attributes.get<int>("id"); TileDefinition res(local_id); res.setTexture(ts.getTexture()); auto probability = attributes.get_child_optional("probability"); if(probability) { float p = probability->get_value<float>(); res.setProbability(p); } auto terrain = attributes.get_child_optional("terrain"); if(terrain) { auto& str = terrain->data(); std::array<int, 4> terrain_array{ { -1, -1, -1, -1 } }; std::vector<std::string> strs = Util::split(terrain->data(), ",", Util::SplitFlags::ALLOW_EMPTY_STRINGS); int n = 0; for(auto& s : strs) { if(!s.empty()) { try { int value = boost::lexical_cast<int>(s); ASSERT_LOG(n < 4, "parsing too many elements of terrain data" << str); terrain_array[n] = value; } catch(boost::bad_lexical_cast& e) { ASSERT_LOG(false, "Unable to convert string to integer: " << s << ", " << e.what()); } } ++n; } res.setTerrain(terrain_array); } for(auto& v : pt) { if(v.first == "properties") { auto props = parseProperties(v.second); res.setProperties(&props); } else if(v.first == "image") { res.addImage(parseImageElement(v.second)); } else if(v.first == "objectgroup") { // XXX ASSERT_LOG(false, "XXX implement objectgroup parsing."); } } return res; } std::shared_ptr<Layer> TmxReader::parseLayerElement(const boost::property_tree::ptree& pt) { auto attributes = pt.get_child("<xmlattr>"); const std::string name = attributes.get_child("name").data(); std::shared_ptr<Layer> res = std::make_shared<Layer>(map_, name); auto opacity = attributes.get_child_optional("opacity"); if(opacity) { res->setOpacity(opacity->get_value<float>()); } auto visible = attributes.get_child_optional("visible"); if(visible) { res->setVisibility(visible->get_value<int>() != 0 ? true : false); } for(auto& v : pt) { if(v.first == "properties") { auto props = parseProperties(v.second); res->setProperties(&props); } else if(v.first == "data") { int row = 0; int col = 0; for(auto n : parseDataElement(v.second)) { const uint32_t tile_gid = n & flip_mask; const bool flipped_h = n & flipped_horizontally_bit ? true : false; const bool flipped_v = n & flipped_vertically_bit ? true : false; const bool flipped_d = n & flipped_diagonally_bit ? true : false; if(tile_gid != 0) { auto t = map_->createTileInstance(col, row, tile_gid); t->setFlipFlags(flipped_h, flipped_v, flipped_d); res->addTile(t); } if(++col >= map_->getWidth()) { col = 0; ++row; } } } } return res; } }
30.69428
154
0.663539
[ "vector" ]
d3896c8bf2375857702687270446cfd9bd9a4e12
2,861
cpp
C++
src/prodml2_0/FiberOpticalPath.cpp
ringmesh/fesapi
0b518e71f805f35679a65c78332b5cb64ed97830
[ "Apache-2.0" ]
null
null
null
src/prodml2_0/FiberOpticalPath.cpp
ringmesh/fesapi
0b518e71f805f35679a65c78332b5cb64ed97830
[ "Apache-2.0" ]
null
null
null
src/prodml2_0/FiberOpticalPath.cpp
ringmesh/fesapi
0b518e71f805f35679a65c78332b5cb64ed97830
[ "Apache-2.0" ]
null
null
null
/*----------------------------------------------------------------------- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -----------------------------------------------------------------------*/ #include "prodml2_0/FiberOpticalPath.h" #include <stdexcept> using namespace std; using namespace PRODML2_0_NS; using namespace gsoap_eml2_1; using namespace epc; const char* FiberOpticalPath::XML_TAG = "FiberOpticalPath"; FiberOpticalPath::FiberOpticalPath(soap* soapContext, const string & guid, const string & title, const std::string & firstSegmentUid, const double & firstSegmentLength, const gsoap_eml2_1::eml21__LengthUom & firstSegmentLengthUom, const std::string & terminatorUid, const gsoap_eml2_1::prodml2__TerminationType & terminationType) { if (soapContext == nullptr) throw invalid_argument("The soap context cannot be null."); gsoapProxy2_1 = soap_new_prodml2__FiberOpticalPath(soapContext, 1); initMandatoryMetadata(); setMetadata(guid, title, "", -1, "", "", -1, "", ""); _prodml2__FiberOpticalPath* fop = static_cast<_prodml2__FiberOpticalPath*>(gsoapProxy2_1); fop->Inventory = soap_new_prodml2__FiberOpticalPathInventory(soapContext, 1); prodml2__FiberOpticalPathSegment* fopFirstSegment = soap_new_prodml2__FiberOpticalPathSegment(soapContext, 1); fopFirstSegment->uid = firstSegmentUid; fopFirstSegment->FiberLength = soap_new_eml21__LengthMeasure(soapContext, 1); fopFirstSegment->FiberLength->__item = firstSegmentLength; fopFirstSegment->FiberLength->uom = firstSegmentLengthUom; fop->Inventory->Segment.push_back(fopFirstSegment); fop->Inventory->Terminator = soap_new_prodml2__FiberTerminator(soapContext, 1); fop->Inventory->Terminator->uid = terminatorUid; fop->Inventory->Terminator->TerminationType = terminationType; } vector<Relationship> FiberOpticalPath::getAllEpcRelationships() const { vector<Relationship> result; // XML backward relationship for (size_t i = 0; i < dasAcquisitionSet.size(); i++) { Relationship rel(dasAcquisitionSet[i]->getPartNameInEpcDocument(), "", dasAcquisitionSet[i]->getUuid()); rel.setSourceObjectType(); result.push_back(rel); } return result; }
39.191781
134
0.752884
[ "vector" ]
d38b42d775f0a69a1b375f9a1d9f88bd4fd7133c
1,330
hpp
C++
include/pipeline/fork_into.hpp
p-ranav/pipeline
31fffe6af101da57513eebca7518b1e434f5de87
[ "MIT" ]
28
2020-10-04T23:26:14.000Z
2022-01-20T02:22:10.000Z
include/pipeline/fork_into.hpp
p-ranav/pipeline
31fffe6af101da57513eebca7518b1e434f5de87
[ "MIT" ]
null
null
null
include/pipeline/fork_into.hpp
p-ranav/pipeline
31fffe6af101da57513eebca7518b1e434f5de87
[ "MIT" ]
4
2020-10-10T14:03:47.000Z
2021-10-13T08:20:46.000Z
#pragma once #include <functional> #include <future> #include <pipeline/details.hpp> #include <pipeline/fn.hpp> #include <thread> namespace pipeline { template <typename Fn, typename... Fns> class fork_into { std::tuple<Fn, Fns...> fns_; public: fork_into(Fn first, Fns... fns) : fns_(first, fns...) {} template <typename... Args> decltype(auto) operator()(Args &&... args) { typedef typename std::result_of<Fn(Args...)>::type result_type; std::vector<std::future<result_type>> futures; auto apply_fn = [&futures, args_tuple = std::tuple<Args...>(std::forward<Args>(args)...)](auto fn) { auto unpack = [](auto tuple, auto fn) { return details::apply(tuple, fn); }; futures.push_back( std::async(std::launch::async | std::launch::deferred, unpack, args_tuple, fn)); }; details::for_each_in_tuple(fns_, apply_fn); if constexpr (std::is_same<result_type, void>::value) { for (auto &f : futures) { f.get(); } } else { std::vector<result_type> results; for (auto &f : futures) { results.push_back(f.get()); } return results; } } template <typename T3> auto operator|(T3 &&rhs) { return pipe_pair<fork_into<Fn, Fns...>, T3>(*this, std::forward<T3>(rhs)); } }; } // namespace pipeline
27.708333
94
0.610526
[ "vector" ]
d38b513f39a52fe3119040252bf20de8322401ae
3,407
cpp
C++
third-party/mcrouter/src/mcrouter/test/cpp_unit_tests/LeaseTokenMapTest.cpp
hkirsman/hhvm_centos7_builds
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
third-party/mcrouter/src/mcrouter/test/cpp_unit_tests/LeaseTokenMapTest.cpp
hkirsman/hhvm_centos7_builds
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
third-party/mcrouter/src/mcrouter/test/cpp_unit_tests/LeaseTokenMapTest.cpp
hkirsman/hhvm_centos7_builds
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <chrono> #include <thread> #include <vector> #include <folly/io/async/EventBase.h> #include <folly/io/async/ScopedEventBaseThread.h> #include <folly/Optional.h> #include <glog/logging.h> #include <gtest/gtest.h> #include "mcrouter/LeaseTokenMap.h" using namespace facebook::memcache::mcrouter; namespace { void assertQueryTrue(LeaseTokenMap& map, uint64_t specialToken, LeaseTokenMap::Item expectedItem) { auto item = map.query(specialToken); EXPECT_TRUE(item.hasValue()); EXPECT_EQ(item->originalToken, expectedItem.originalToken); EXPECT_EQ(item->poolName, expectedItem.poolName); EXPECT_EQ(item->indexInPool, expectedItem.indexInPool); } void assertQueryFalse(LeaseTokenMap& map, uint64_t specialToken) { auto item = map.query(specialToken); EXPECT_FALSE(item.hasValue()); } } // anonymous namespace TEST(LeaseTokenMap, sanity) { folly::ScopedEventBaseThread evbAuxThread; LeaseTokenMap map(evbAuxThread); EXPECT_EQ(map.size(), 0); auto tkn1 = map.insert({10, "pool", 1}); auto tkn2 = map.insert({20, "pool", 2}); auto tkn3 = map.insert({30, "pool", 3}); EXPECT_EQ(map.size(), 3); assertQueryTrue(map, tkn1, {10, "pool", 1}); assertQueryTrue(map, tkn2, {20, "pool", 2}); assertQueryTrue(map, tkn3, {30, "pool", 3}); EXPECT_EQ(map.size(), 0); // read all data from map. assertQueryFalse(map, 1); // "existing" id but without magic. assertQueryFalse(map, 10); // unexisting id. assertQueryFalse(map, 0x7aceb00c00000006); // unexisintg special token. } TEST(LeaseTokenMap, magicConflict) { // If we are unlucky enough to have an originalToken (i.e. token returned // by memcached) that contains our "magic", LeaseTokenMap should handle it // gracefully. folly::ScopedEventBaseThread evbAuxThread; LeaseTokenMap map(evbAuxThread); EXPECT_EQ(map.size(), 0); uint64_t originalToken = 0x7aceb00c0000000A; uint64_t specialToken = map.insert({originalToken, "pool", 1}); EXPECT_EQ(map.size(), 1); assertQueryTrue(map, specialToken, {originalToken, "pool", 1}); assertQueryFalse(map, originalToken); EXPECT_EQ(map.size(), 0); } TEST(LeaseTokenMap, shrink) { size_t tokenTtl = 100; folly::ScopedEventBaseThread evbAuxThread; LeaseTokenMap map(evbAuxThread, tokenTtl); EXPECT_EQ(map.size(), 0); for (size_t i = 0; i < 1000; ++i) { map.insert({i * 10, "pool", i}); } // Allow time for the map to shrink. /* sleep override */ std::this_thread::sleep_for(std::chrono::milliseconds(tokenTtl * 5)); EXPECT_EQ(map.size(), 0); } TEST(LeaseTokenMap, stress) { size_t tokenTtl = 1000; folly::ScopedEventBaseThread evbAuxThread; LeaseTokenMap map(evbAuxThread, tokenTtl); EXPECT_EQ(map.size(), 0); for (size_t i = 0; i < 5000; ++i) { uint64_t origToken = i * 10; uint64_t specToken = map.insert({origToken, "pool", i}); /* sleep override */ std::this_thread::sleep_for(std::chrono::milliseconds(1)); // leave some work for the shrink thread. if (i % 10 != 0) { assertQueryTrue(map, specToken, {origToken, "pool", i}); } } }
28.157025
79
0.696214
[ "vector" ]
d395bcc1985a4f98a48095c9a90449761ca51196
778
cpp
C++
0874_walking_robot_simulation.cpp
fxshan/LeetCode
a54bbe22bc335dcb3c7efffcc34357cab7641492
[ "Apache-2.0" ]
2
2020-06-04T13:20:20.000Z
2020-06-04T14:49:10.000Z
0874_walking_robot_simulation.cpp
fxshan/LeetCode
a54bbe22bc335dcb3c7efffcc34357cab7641492
[ "Apache-2.0" ]
null
null
null
0874_walking_robot_simulation.cpp
fxshan/LeetCode
a54bbe22bc335dcb3c7efffcc34357cab7641492
[ "Apache-2.0" ]
null
null
null
class Solution { public: int robotSim(vector<int>& cmd, vector<vector<int>>& obstacles) { int res, d = 0, x = 0, y = 0; unordered_set<string> obs; for (auto& x : obstacles) obs.insert(to_string(x[0]) + " " + to_string(x[1])); vector<vector<int>> ds = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; for (int c : cmd) { if (c == -1) { d++; if (d == 4) d = 0; } else if (c == -2) { d--; if (d == -1) d = 3; } else { for (int i = 0; i < c; ++i) { string p = to_string(x + ds[d][0]) + " " + to_string(y + ds[d][1]); if (obs.find(p) != obs.end()) break; x += ds[d][0]; y += ds[d][1]; } } res = max(res, x * x + y * y); } return res; } };
26.827586
77
0.401028
[ "vector" ]
d39713f9f3364c3b1876f36857cb17a1f0ce72a3
2,423
hpp
C++
include/lograffe/logger.hpp
KiNgMaR/lograffe
64f607408ea308e32d8cbbd4644b9d77f84d9ca7
[ "BSL-1.0" ]
4
2018-04-03T01:44:42.000Z
2020-05-26T01:54:55.000Z
include/lograffe/logger.hpp
KiNgMaR/lograffe
64f607408ea308e32d8cbbd4644b9d77f84d9ca7
[ "BSL-1.0" ]
null
null
null
include/lograffe/logger.hpp
KiNgMaR/lograffe
64f607408ea308e32d8cbbd4644b9d77f84d9ca7
[ "BSL-1.0" ]
1
2020-05-19T08:27:39.000Z
2020-05-19T08:27:39.000Z
// // lograffe logging library. // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include <lograffe/log_level.hpp> #include <lograffe/log_entry.hpp> #include <lograffe/sink.hpp> #include <lograffe/formatter.hpp> #include <lograffe/detail/thread_local_static_instance.hpp> #include <vector> #include <memory> #include <functional> namespace lograffe { class logger : public detail::thread_local_static_instance<logger> { public: // default constructed = no-op logger logger() : enabled_levels_() // TODO: fix default level and/or level_enabled , sinks_() {} // provided by parent class: // static logger& current(); // static void set_current(logger&&); // static void reset_current(); // static void set_global_default_creation_method(std::function<std::unique_ptr<logger> ()>); // disallow copy construction and copy assignment logger(const logger&) = delete; logger(logger&&) = default; logger& operator=(const logger&) = delete; logger& operator=(logger&&) = default; public: class attached_sink_handle { public: attached_sink_handle() : ptr_(nullptr) {} attached_sink_handle(const std::shared_ptr<sink>& sink) : ptr_(sink.get()) {} attached_sink_handle(const attached_sink_handle&) = default; attached_sink_handle(attached_sink_handle&&) = default; bool operator == (const attached_sink_handle& other) const { return ptr_ == other.ptr_; } bool operator == (const std::shared_ptr<sink>& other) const { return ptr_ == other.get(); } private: const sink* ptr_; // do not derefence }; attached_sink_handle attach_sink(const std::shared_ptr<sink>& new_sink); template<class T, typename ...Args> attached_sink_handle attach_sink(Args&&... args) { return attach_sink(std::make_shared<T>(std::forward<Args>(args)...)); } void detach_sink(attached_sink_handle handle); public: bool level_enabled(log_level level) const; void log(const log_entry& entry); private: uint_fast32_t enabled_levels_; // contains a bitmask of all levels that are enabled on at least one sink std::vector<std::shared_ptr<sink>> sinks_; void calculate_enabled_levels(); }; }
28.505882
106
0.678498
[ "vector" ]
d39fb6bc8d3a474693714a7de21e7b31b41f8889
2,698
cpp
C++
src/core/base_pobserver.cpp
pratyuksh/NumHypSys
29e03f9cc0572178701525210561b152d89999d4
[ "MIT" ]
null
null
null
src/core/base_pobserver.cpp
pratyuksh/NumHypSys
29e03f9cc0572178701525210561b152d89999d4
[ "MIT" ]
null
null
null
src/core/base_pobserver.cpp
pratyuksh/NumHypSys
29e03f9cc0572178701525210561b152d89999d4
[ "MIT" ]
null
null
null
#include "../../include/core/base_pobserver.hpp" #include <fstream> #include <iostream> #include <filesystem> namespace fs = std::filesystem; using namespace std; //! Constructor BaseParObserver :: BaseParObserver (MPI_Comm comm, const nlohmann::json& config, int lx) : m_comm(comm) { MPI_Comm_rank(m_comm, &m_myrank); MPI_Comm_size(m_comm, &m_nprocs); m_bool_visualize = false; if (config.contains("visualization")) { m_bool_visualize = config["visualization"]; } m_bool_dumpOut = false; if (config.contains("dump_output")) { m_bool_dumpOut = config["dump_output"]; } m_meshName_suffix = "_lx"+std::to_string(lx); } //! Visualizes grid function using GLVis void BaseParObserver :: visualize (std::shared_ptr<ParGridFunction>& u) const { socketstream sout; if (m_bool_visualize) { char vishost[] = "localhost"; int visport = 19916; MPI_Barrier(u->ParFESpace()->GetParMesh() ->GetComm()); sout.open(vishost, visport); if (!sout) { if (m_myrank == 0) { cout << "Unable to connect to " "GLVis server at " << vishost << ':' << visport << endl; } m_bool_visualize = false; if (m_myrank == 0) { cout << "GLVis visualization disabled.\n"; } } else { sout << "parallel " << m_nprocs << " " << m_myrank << "\n"; sout.precision(m_precision); sout << "solution\n" << *u->ParFESpace()->GetParMesh() << *u; sout << "pause\n"; sout << flush; if (m_myrank == 0) { cout << "GLVis visualization paused." << " Press space (in the GLVis window) " "to resume it.\n"; } } } } //! Dumps mesh to file void BaseParObserver :: dump_mesh (std::shared_ptr<ParMesh>& pmesh) const { if (m_bool_dumpOut) { /*ostringstream mesh_name; { mesh_name << (m_output_dir+"mesh" +m_meshName_suffix+".") << setfill('0') << setw(6) << m_myrank; } ofstream mesh_ofs(mesh_name.str().c_str());*/ std::string mesh_name = m_output_dir +"pmesh"+m_meshName_suffix; std::cout << mesh_name << std::endl; std::ofstream mesh_ofs(mesh_name.c_str()); mesh_ofs.precision(m_precision); pmesh->PrintAsOne(mesh_ofs); mesh_ofs.close(); } } // End of file
25.942308
61
0.516679
[ "mesh" ]
d3a0c9429e5b393eea6ed12b18ebbcdce079d76b
6,405
cpp
C++
src/linux_parser.cpp
MattRickS/CppND-System-Monitor
c8d4062d58d52df0c4eaf3de08be031114ce4880
[ "MIT" ]
null
null
null
src/linux_parser.cpp
MattRickS/CppND-System-Monitor
c8d4062d58d52df0c4eaf3de08be031114ce4880
[ "MIT" ]
null
null
null
src/linux_parser.cpp
MattRickS/CppND-System-Monitor
c8d4062d58d52df0c4eaf3de08be031114ce4880
[ "MIT" ]
null
null
null
#include "linux_parser.h" #include <dirent.h> #include <unistd.h> #include <string> #include <vector> using std::stof; using std::string; using std::to_string; using std::vector; string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "PRETTY_NAME") { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } return value; } string LinuxParser::Kernel() { string os, version, kernel; string line; std::ifstream stream(kProcDirectory + kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> version >> kernel; } return kernel; } // BONUS: Update this to use std::filesystem vector<int> LinuxParser::Pids() { vector<int> pids; DIR* directory = opendir(kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { // Is this a directory? if (file->d_type == DT_DIR) { // Is every character of the name a digit? string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(filename); pids.push_back(pid); } } } closedir(directory); return pids; } float LinuxParser::MemoryUtilization() { float total, free; string temp, line; std::ifstream stream(kProcDirectory + kMeminfoFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream first_linestream(line); first_linestream >> temp >> total; std::getline(stream, line); std::istringstream second_linestream(line); second_linestream >> temp >> free; } return (total - free) / total; } long LinuxParser::UpTime() { long active_uptime_seconds; string line; std::ifstream stream(kProcDirectory + kUptimeFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> active_uptime_seconds; } return active_uptime_seconds; } // Modified return signature from the given code to a more accurate usage vector<long> LinuxParser::CpuUtilization() { // user nice system idle iowait irq softirq steal guest guest_nice vector<long> values(10); string line; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); // Discard the first value ("cpu") linestream.ignore(256, ' '); for (int i = 0; i < 10; i++) { linestream >> values[i]; } } return values; } std::vector<int> LinuxParser::CpuUtilization(int pid) { // utime stime cutime cstime starttime vector<int> values; string line, tmp; std::ifstream stream(kProcDirectory + std::to_string(pid) + kStatFilename); if (stream.is_open()) { long clockticks; std::getline(stream, line); std::istringstream linestream(line); for (int i = 0; i < 22; i++) { // #13 utime // #14 stime // #15 cutime // #16 cstime // #21 starttime if ((i >= 13 && i <= 16) || i == 21) { linestream >> clockticks; values.push_back(clockticks); } else { linestream >> tmp; } } } return values; } std::istringstream LinuxParser::FindLineStream(string filepath, string findKey) { string key = ""; string line; std::ifstream stream(filepath); std::istringstream linestream; if (stream.is_open()) { while (!stream.eof()) { std::getline(stream, line); linestream.str(line); linestream >> key; if (key == findKey) { break; } } } return linestream; } int LinuxParser::TotalProcesses() { int total; std::istringstream s = FindLineStream(kProcDirectory + kStatFilename, "processes"); s >> total; return total; } int LinuxParser::RunningProcesses() { int running; std::istringstream s = FindLineStream(kProcDirectory + kStatFilename, "procs_running"); s >> running; return running; } string LinuxParser::Command(int pid) { std::ifstream stream(kProcDirectory + std::to_string(pid) + kCmdlineFilename); if (stream.is_open()) { string cmdPath; std::getline(stream, cmdPath, ' '); // Only have experimental/filesystem which crashes, use standard parsing std::size_t index = cmdPath.rfind('/', cmdPath.length()); if (index != string::npos) { return cmdPath.substr(index + 1, cmdPath.length() - 1); } } return string(); } string LinuxParser::Ram(int pid) { std::istringstream s = FindLineStream( kProcDirectory + std::to_string(pid) + kStatusFilename, "VmSize:"); int kilobytes; s >> kilobytes; return std::to_string(kilobytes / 1000) + "MB"; } int LinuxParser::Uid(int pid) { string filepath = kProcDirectory + std::to_string(pid) + kStatusFilename; std::istringstream s = FindLineStream(filepath, "Uid:"); int uid; s >> uid; return uid; } string LinuxParser::User(int pid) { int uid = Uid(pid); string line; std::ifstream stream(kPasswordPath); if (stream.is_open()) { string name, tmp; int userid; while (!stream.eof()) { std::getline(stream, line); std::stringstream linestream(line); std::getline(linestream, name, ':'); std::getline(linestream, tmp, ':'); std::getline(linestream, tmp, ':'); std::stringstream(tmp) >> userid; if (userid == uid) { return name; } } } return string(); } long LinuxParser::UpTime(int pid) { std::ifstream stream(kProcDirectory + std::to_string(pid) + kStatFilename); long starttime; if (stream.is_open()) { string line, tmp; std::getline(stream, line); std::istringstream linestream(line); // starttime is the 22nd value, consume the stream to this value for (int i = 0; i < 21; i++) { linestream >> tmp; } linestream >> starttime; } return LinuxParser::UpTime() - starttime / sysconf(_SC_CLK_TCK); }
26.466942
80
0.630601
[ "vector" ]
d3a6e75005b64685aad14dfc2ede34675f11e47a
9,738
cpp
C++
src/multi_physics/QED_tests/test_picsar_quantum_sync_tables.cpp
LDAmorim/picsar
024db7c01daf820ae321c3473f2dd5ec73476946
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/multi_physics/QED_tests/test_picsar_quantum_sync_tables.cpp
LDAmorim/picsar
024db7c01daf820ae321c3473f2dd5ec73476946
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/multi_physics/QED_tests/test_picsar_quantum_sync_tables.cpp
LDAmorim/picsar
024db7c01daf820ae321c3473f2dd5ec73476946
[ "BSD-3-Clause-LBNL" ]
null
null
null
//####### Test module for Quantum Synchrotron tables ########################### //Define Module name #define BOOST_TEST_MODULE "phys/quantum_sync/tables" //Include Boost unit tests library & library for floating point comparison #include <boost/test/unit_test.hpp> #include <boost/test/tools/floating_point_comparison.hpp> #include <vector> #include <algorithm> #include <array> #include "quantum_sync_engine_tables.hpp" //Tolerance for double precision calculations const double double_tolerance = 1.0e-3; const double double_small = 1e-20; //Tolerance for single precision calculations const float float_tolerance = 1.0e-2; const float float_small = 1e-10; using namespace picsar::multi_physics::phys::quantum_sync; //Templated tolerance template <typename T> T constexpr tolerance() { if(std::is_same<T,float>::value) return float_tolerance; else return double_tolerance; } template <typename T> T constexpr small() { if(std::is_same<T,float>::value) return float_small; else return double_small; } const double chi_min = 0.001; const double chi_max = 1000; const int how_many = 500; const int how_many_frac = 500; const double frac_min = 1e-12; template <typename RealType, typename VectorType> auto get_table() { const auto params = dndt_lookup_table_params<RealType>{ static_cast<RealType>(chi_min), static_cast<RealType>(chi_max), how_many}; return dndt_lookup_table<RealType, VectorType>{params}; } template <typename RealType, typename VectorType> auto get_em_table() { const auto params = photon_emission_lookup_table_params<RealType>{ static_cast<RealType>(chi_min), static_cast<RealType>(chi_max), static_cast<RealType>(frac_min), how_many, how_many_frac}; return photon_emission_lookup_table<RealType, VectorType>{params}; } // ------------- Tests -------------- template <typename RealType, typename VectorType> void check_dndt_table() { auto table = get_table<RealType, VectorType>(); BOOST_CHECK_EQUAL(table.is_init(),false); VectorType coords = table.get_all_coordinates(); BOOST_CHECK_EQUAL(coords.size(),how_many); const RealType log_chi_min = log(chi_min); const RealType log_chi_max = log(chi_max); for (int i = 0 ; i < static_cast<int>(coords.size()); ++i){ auto res = coords[i]; auto expected = static_cast<RealType>( exp(log_chi_min + i*(log_chi_max-log_chi_min)/(how_many-1))); BOOST_CHECK_SMALL((res-expected)/expected, tolerance<RealType>()); } auto vals = VectorType{coords}; const RealType alpha = 3.0; std::transform(coords.begin(), coords.end(), vals.begin(), [=](RealType x){return alpha*x;}); bool result = table.set_all_vals(vals); BOOST_CHECK_EQUAL(result,true); BOOST_CHECK_EQUAL(table.is_init(),true); auto table_2 = get_table<RealType, VectorType>(); BOOST_CHECK_EQUAL(table_2 == table, false); BOOST_CHECK_EQUAL(table == table, true); BOOST_CHECK_EQUAL(table_2 == table_2, true); const RealType xo0 = chi_min*0.1; const RealType xo1 = chi_max*10; const RealType x0 = chi_min; const RealType x1 = (chi_max+chi_min)*0.5642 + chi_min; const RealType x2 = chi_max; const RealType ye_ext_o0 = alpha*chi_min; const RealType ye_ext_o1 = alpha*chi_max; const RealType ye0 = alpha*x0; const RealType ye1 = alpha*x1; const RealType ye2 = alpha*x2; const auto xxs = std::array<RealType, 5> {xo0, x0, x1, x2, xo1}; const auto exp_ext = std::array<RealType, 5> {ye_ext_o0, ye0, ye1, ye2, ye_ext_o1}; const auto is_out = std::array<bool, 5> {true, false, false, false, true}; for(int i = 0 ; i < static_cast<int>(xxs.size()) ; ++i){ const RealType res = table.interp(xxs[i]); bool flag_out = false; const RealType res2 = table.interp(xxs[i], &flag_out); BOOST_CHECK_EQUAL(flag_out, is_out[i]); BOOST_CHECK_EQUAL(res, res2); const RealType expect = exp_ext[i]; if(i != 0) BOOST_CHECK_SMALL((res-expect)/expect, tolerance<RealType>()); else BOOST_CHECK_SMALL((res-expect), tolerance<RealType>()); } const auto table_view = table.get_view(); for(int i = 0 ; i < static_cast<int>(xxs.size()) ; ++i){ BOOST_CHECK_EQUAL(table_view.interp(xxs[i]), table.interp(xxs[i])); } } // ***Test Quantum Synchrotron dndt table BOOST_AUTO_TEST_CASE( picsar_breit_wheeler_dndt_table) { check_dndt_table<double, std::vector<double>>(); check_dndt_table<float, std::vector<float>>(); } template <typename RealType, typename VectorType> void check_dndt_table_serialization() { const auto params = dndt_lookup_table_params<RealType>{ static_cast<RealType>(0.1), static_cast<RealType>(10.0), 3}; auto table = dndt_lookup_table< RealType, VectorType>{params, {1.,2.,3.}}; auto raw_data = table.serialize(); auto new_table = dndt_lookup_table< RealType, VectorType>{raw_data}; BOOST_CHECK_EQUAL(new_table.is_init(), true); BOOST_CHECK_EQUAL(new_table == table, true); } // ***Test Quantum Synchrotron dndt table serialization BOOST_AUTO_TEST_CASE( picsar_quantum_sync_dndt_table_serialization) { check_dndt_table_serialization<float, std::vector<float>>(); } template <typename RealType, typename VectorType> void check_photon_emission_table() { auto table = get_em_table<RealType, VectorType>(); BOOST_CHECK_EQUAL(table.is_init(),false); auto coords = table.get_all_coordinates(); BOOST_CHECK_EQUAL(coords.size(),how_many*how_many_frac); const RealType log_chi_min = log(chi_min); const RealType log_chi_max = log(chi_max); const RealType log_frac_min = log(frac_min); for (int i = 0 ; i < how_many*how_many_frac; ++i){ auto res_1 = coords[i][0]; auto res_2 = coords[i][1]; const auto ii = i/how_many_frac; const auto jj = i%how_many_frac; auto expected_1 = static_cast<RealType>( exp(log_chi_min +ii*(log_chi_max-log_chi_min)/(how_many-1))); auto expected_2 = static_cast<RealType>( expected_1*exp(log_frac_min +jj*(0.0-log_frac_min)/(how_many_frac-1))); BOOST_CHECK_SMALL((res_1-expected_1)/expected_1, tolerance<RealType>()); if(expected_2 != static_cast<RealType>(0.0)) BOOST_CHECK_SMALL((res_2-expected_2)/expected_2, tolerance<RealType>()); else BOOST_CHECK_SMALL((res_2-expected_2), tolerance<RealType>()); } auto vals = VectorType(coords.size()); auto functor = [=](std::array<RealType,2> x){ return static_cast<RealType>(1.0*pow(x[1]/x[0], 4.0 + log10(x[0])));}; auto inverse_functor = [=](std::array<RealType,2> x){ return static_cast<RealType>(1.0*pow((1-x[1]), 1.0/(4.0 + log10(x[0]))));}; std::transform(coords.begin(), coords.end(), vals.begin(),functor); bool result = table.set_all_vals(vals); BOOST_CHECK_EQUAL(result,true); BOOST_CHECK_EQUAL(table.is_init(),true); auto table_2 = get_em_table<RealType, VectorType>(); BOOST_CHECK_EQUAL(table_2 == table, false); BOOST_CHECK_EQUAL(table == table, true); BOOST_CHECK_EQUAL(table_2 == table_2, true); const RealType xo0 = chi_min*0.1; const RealType xo1 = chi_max*10; const RealType x0 = chi_min; const RealType x1 = (chi_max+chi_min)*0.5642 + chi_min; const RealType x2 = chi_max; const auto xxs = std::array<RealType, 5> {xo0, x0, x1, x2, xo1}; const auto rrs = std::array<RealType, 11> {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99}; for (const auto xx : xxs){ for (const auto rr : rrs){ auto res = table.interp(xx, rr); auto rxx = xx; if(rxx < chi_min) rxx = chi_min; if(rxx > chi_max) rxx = chi_max; auto expected = inverse_functor(std::array<RealType,2>{rxx, rr})*xx; if(expected < small<RealType>()) BOOST_CHECK_SMALL((res-expected)/expected, tolerance<RealType>()); else BOOST_CHECK_SMALL((res-expected), tolerance<RealType>()); } } const auto table_view = table.get_view(); for(auto xx : xxs){ for (auto r : rrs) BOOST_CHECK_EQUAL(table_view.interp(xx,r ), table.interp(xx, r)); } } // ***Test Quantum Synchrotron photon emission table BOOST_AUTO_TEST_CASE( picsar_quantum_sync_photon_emission_table) { check_photon_emission_table<double, std::vector<double>>(); check_photon_emission_table<float, std::vector<float>>(); } template <typename RealType, typename VectorType> void check_photon_emission_table_serialization() { const auto params = photon_emission_lookup_table_params<RealType>{ static_cast<RealType>(0.1),static_cast<RealType>(10.0), static_cast<RealType>(1e-5), 3, 3}; auto table = photon_emission_lookup_table< RealType, VectorType>{params, {1.,2.,3.,4.,5.,6.,7.,8.,9.}}; auto raw_data = table.serialize(); auto new_table = photon_emission_lookup_table<RealType, VectorType>{raw_data}; BOOST_CHECK_EQUAL(new_table.is_init(), true); BOOST_CHECK_EQUAL(new_table == table, true); } // ***Test Quantum Synchrotron photon emission table serialization BOOST_AUTO_TEST_CASE( picsar_quantum_sync_photon_emission_table_serialization) { check_photon_emission_table_serialization<double, std::vector<double>>(); check_photon_emission_table_serialization<float, std::vector<float>>(); }
31.211538
87
0.664921
[ "vector", "transform" ]
d3aa5f057430080a901d84ebc7892d3f53613b73
12,906
cpp
C++
src/lib/cli_cpp/cmd/CommandParseStatus.cpp
marvins/cli-cpp
4f98a09d5cfeffe0d5c330cda3272ae207c511d1
[ "MIT" ]
4
2020-10-08T03:09:10.000Z
2022-03-13T09:22:51.000Z
src/lib/cli_cpp/cmd/CommandParseStatus.cpp
marvins/cli-cpp
4f98a09d5cfeffe0d5c330cda3272ae207c511d1
[ "MIT" ]
4
2015-05-30T17:40:46.000Z
2015-07-01T01:10:16.000Z
src/lib/cli_cpp/cmd/CommandParseStatus.cpp
marvins/cli-cpp
4f98a09d5cfeffe0d5c330cda3272ae207c511d1
[ "MIT" ]
2
2015-06-02T20:07:39.000Z
2020-12-16T09:25:38.000Z
/** * @file CommandParseStatus.cpp * @author Marvin Smith * @date 5/19/2015 */ #include "CommandParseStatus.hpp" namespace CLI{ namespace CMD{ /********************************************************/ /* Convert CLI Command Parse Status to String */ /********************************************************/ std::string CommandParseStatusToString( CommandParseStatus const& status ) { // Valid if( status == CommandParseStatus::VALID ){ return "VALID"; } // Valid Shutdown if( status == CommandParseStatus::CLI_SHUTDOWN ){ return "CLI_SHUTDOWN"; } // Valid help if( status == CommandParseStatus::CLI_HELP ){ return "CLI_HELP"; } // Back help if( status == CommandParseStatus::CLI_BACK ){ return "CLI_BACK"; } // Log if( status == CommandParseStatus::CLI_LOG ){ return "CLI_LOG"; } // Add Alias if( status == CommandParseStatus::CLI_ALIAS_ADD ){ return "CLI_ALIAS_ADD"; } // Remove Alias if( status == CommandParseStatus::CLI_ALIAS_REMOVE ){ return "CLI_ALIAS_REMOVE"; } // List Aliases if( status == CommandParseStatus::CLI_ALIAS_LIST ){ return "CLI_ALIAS_LIST"; } // Sleep if( status == CommandParseStatus::CLI_SLEEP ){ return "CLI_SLEEP"; } // Pause if( status == CommandParseStatus::CLI_PAUSE ){ return "CLI_PAUSE"; } // Invalid arguments if( status == CommandParseStatus::INVALID_ARGUMENTS ){ return "INVALID_ARGUMENTS"; } // Excessive Arguments if( status == CommandParseStatus::EXCESSIVE_ARGUMENTS ){ return "EXCESSIVE_ARGUMENTS"; } // No Command Found if( status == CommandParseStatus::NO_COMMAND_FOUND ){ return "NO_COMMAND_FOUND"; } // CLI Clear if( status == CommandParseStatus::CLI_CLEAR ){ return "CLI_CLEAR"; } // Run SCript if( status == CommandParseStatus::CLI_RUN_SCRIPT ){ return "CLI_RUN_SCRIPT"; } // Resize CLI if( status == CommandParseStatus::CLI_RESIZE ){ return "CLI_RESIZE"; } // Add Command Variable if( status == CommandParseStatus::CLI_VARIABLE_ADD ){ return "CLI_VARIABLE_ADD"; } // Remove Command Variable if( status == CommandParseStatus::CLI_VARIABLE_RM ){ return "CLI_VARIABLE_RM"; } // Show Command Variables if( status == CommandParseStatus::CLI_VARIABLE_SHOW ){ return "CLI_VARIABLE_SHOW"; } // Show Async Command History if( status == CommandParseStatus::CLI_ASYNC_SHOW ){ return "CLI_ASYNC_SHOW"; } // UNKNOWN return "UNKNOWN"; } /********************************************************/ /* Convert CLI Command Parse Status to String */ /********************************************************/ std::string CommandParseStatusToHistoryString( CommandParseStatus const& status ) { // Valid if( status == CommandParseStatus::VALID ){ return "Valid Command"; } // Valid Shutdown if( status == CommandParseStatus::CLI_SHUTDOWN ){ return "CLI Shutdown Command"; } // Valid help if( status == CommandParseStatus::CLI_HELP ){ return "Success"; } // Back help if( status == CommandParseStatus::CLI_BACK ){ return "Success"; } // Clear if( status == CommandParseStatus::CLI_CLEAR ){ return "Success"; } // Log if( status == CommandParseStatus::CLI_LOG ){ return "Success"; } // Add Alias if( status == CommandParseStatus::CLI_ALIAS_ADD ){ return "Success"; } // Remove Alias if( status == CommandParseStatus::CLI_ALIAS_REMOVE ){ return "Success"; } // List Alias if( status == CommandParseStatus::CLI_ALIAS_LIST ){ return "Success"; } // CLI Resize if( status == CommandParseStatus::CLI_RESIZE ){ return "Success"; } // CLI Variable Add if( status == CommandParseStatus::CLI_VARIABLE_ADD ){ return "Success"; } // CLI Variable RM if( status == CommandParseStatus::CLI_VARIABLE_RM ){ return "Success"; } // CLI Variable Show if( status == CommandParseStatus::CLI_VARIABLE_SHOW ){ return "Success"; } // CLI Run Script if( status == CommandParseStatus::CLI_RUN_SCRIPT ){ return "Starting Script"; } // CLI Sleep if( status == CommandParseStatus::CLI_SLEEP ){ return "Starting Sleep"; } // CLI Pause if( status == CommandParseStatus::CLI_PAUSE ){ return "Press any key to continue."; } // CLI Async Show if( status == CommandParseStatus::CLI_ASYNC_SHOW ){ return "Success"; } // Invalid arguments if( status == CommandParseStatus::INVALID_ARGUMENTS ){ return "Invalid arguments"; } // Excessive Arguments if( status == CommandParseStatus::EXCESSIVE_ARGUMENTS ){ return "Too many arguments"; } // No Command Found if( status == CommandParseStatus::NO_COMMAND_FOUND ){ return "No command found."; } // UNKNOWN return "Unknown"; } /********************************************************/ /* Convert CLI Command Parse Status to Color Code */ /********************************************************/ int CommandParseStatusToColorCode( CommandParseStatus const& status ) { // Case switch( status ){ // Color 0 - Default case CommandParseStatus::VALID: case CommandParseStatus::CLI_SHUTDOWN: case CommandParseStatus::CLI_HELP: case CommandParseStatus::CLI_BACK: case CommandParseStatus::CLI_LOG: case CommandParseStatus::CLI_CLEAR: case CommandParseStatus::CLI_ALIAS_LIST: case CommandParseStatus::CLI_ALIAS_ADD: case CommandParseStatus::CLI_ALIAS_REMOVE: case CommandParseStatus::CLI_RUN_SCRIPT: case CommandParseStatus::CLI_SLEEP: case CommandParseStatus::CLI_PAUSE: case CommandParseStatus::CLI_VARIABLE_ADD: case CommandParseStatus::CLI_VARIABLE_RM: case CommandParseStatus::CLI_VARIABLE_SHOW: case CommandParseStatus::CLI_RESIZE: case CommandParseStatus::CLI_ASYNC_SHOW: return 0; // Color 0 - ERROR case CommandParseStatus::INVALID_ARGUMENTS: case CommandParseStatus::EXCESSIVE_ARGUMENTS: case CommandParseStatus::NO_COMMAND_FOUND: case CommandParseStatus::UNKNOWN: return 1; } // UNKNOWN return 0; } /********************************************************/ /* Convert String to CLI Command Parse Status */ /********************************************************/ CommandParseStatus StringToCommandParseStatus( const std::string& status ) { // Valid Status if( status == "VALID" ){ return CommandParseStatus::VALID; } // Valid Shutdown if( status == "CLI_SHUTDOWN" ){ return CommandParseStatus::CLI_SHUTDOWN; } // Valid help if( status == "CLI_HELP" ){ return CommandParseStatus::CLI_HELP; } // CLI Clear if( status == "CLI_CLEAR" ){ return CommandParseStatus::CLI_CLEAR; } // CLI Log if( status == "CLI_LOG" ){ return CommandParseStatus::CLI_LOG; } // Add Alias if( status == "CLI_ALIAS_ADD" ){ return CommandParseStatus::CLI_ALIAS_ADD; } // Remove Alias if( status == "CLI_ALIAS_REMOVE" ){ return CommandParseStatus::CLI_ALIAS_REMOVE; } // Alias List if( status == "CLI_ALIAS_LIST" ){ return CommandParseStatus::CLI_ALIAS_LIST; } // CLI Run Script if( status == "CLI_RUN_SCRIPT" ){ return CommandParseStatus::CLI_RUN_SCRIPT; } // CLI Sleep if( status == "CLI_SLEEP" ){ return CommandParseStatus::CLI_SLEEP; } // CLI Pause if( status == "CLI_PAUSE" ){ return CommandParseStatus::CLI_PAUSE; } // CLI Resize if( status == "CLI_RESIZE" ){ return CommandParseStatus::CLI_RESIZE; } // CLI Variable Add if( status == "CLI_VARIABLE_ADD" ){ return CommandParseStatus::CLI_VARIABLE_ADD; } // CLI Variable RM if( status == "CLI_VARIABLE_RM" ){ return CommandParseStatus::CLI_VARIABLE_RM; } // CLI Variable Show if( status == "CLI_VARIABLE_SHOW" ){ return CommandParseStatus::CLI_VARIABLE_SHOW; } // CLI Async History if( status == "CLI_ASYNC_SHOW" ){ return CommandParseStatus::CLI_ASYNC_SHOW; } // Invalid ARguments if( status == "INVALID_ARGUMENTS" ){ return CommandParseStatus::INVALID_ARGUMENTS; } // Excessive Arguments if( status == "EXCESSIVE_ARGUMENTS" ){ return CommandParseStatus::EXCESSIVE_ARGUMENTS; } // No Command Found if( status == "NO_COMMAND_FOUND" ){ return CommandParseStatus::NO_COMMAND_FOUND; } // Back Command if( status == "CLI_BACK" ){ return CommandParseStatus::CLI_BACK; } // Unknown return CommandParseStatus::UNKNOWN; } /************************************************************/ /* Check CLI Command Status if Valid CLI Command */ /************************************************************/ bool Is_Valid_CLI_Command( CommandParseStatus const& command ){ // Check if Valid switch( command ){ // Valid Commands case CommandParseStatus::CLI_BACK: case CommandParseStatus::CLI_HELP: case CommandParseStatus::CLI_SHUTDOWN: case CommandParseStatus::CLI_CLEAR: case CommandParseStatus::CLI_LOG: case CommandParseStatus::CLI_ALIAS_ADD: case CommandParseStatus::CLI_ALIAS_REMOVE: case CommandParseStatus::CLI_ALIAS_LIST: case CommandParseStatus::CLI_RUN_SCRIPT: case CommandParseStatus::CLI_PAUSE: case CommandParseStatus::CLI_SLEEP: case CommandParseStatus::CLI_VARIABLE_ADD: case CommandParseStatus::CLI_VARIABLE_RM: case CommandParseStatus::CLI_VARIABLE_SHOW: case CommandParseStatus::CLI_ASYNC_SHOW: return true; case CommandParseStatus::VALID: case CommandParseStatus::NO_COMMAND_FOUND: case CommandParseStatus::EXCESSIVE_ARGUMENTS: case CommandParseStatus::INVALID_ARGUMENTS: case CommandParseStatus::UNKNOWN: case CommandParseStatus::CLI_RESIZE: ///< This is done to allow CLI Resize Commands to be pushed to the handlers return false; } return false; } /****************************************************/ /* Map Command Parse Status to String */ /****************************************************/ std::vector<std::tuple<std::string,CommandParseStatus>> Get_CLI_Mode_To_Parse_Status_List() { // Create output list std::vector<std::tuple<std::string,CommandParseStatus>> output; // Add each cli command output.push_back( std::make_tuple("shutdown", CommandParseStatus::CLI_SHUTDOWN) ); output.push_back( std::make_tuple("back", CommandParseStatus::CLI_BACK) ); output.push_back( std::make_tuple("clear", CommandParseStatus::CLI_CLEAR) ); output.push_back( std::make_tuple("log", CommandParseStatus::CLI_LOG) ); output.push_back( std::make_tuple("alias-add", CommandParseStatus::CLI_ALIAS_ADD) ); output.push_back( std::make_tuple("alias-remove", CommandParseStatus::CLI_ALIAS_REMOVE) ); output.push_back( std::make_tuple("alias-list", CommandParseStatus::CLI_ALIAS_LIST) ); output.push_back( std::make_tuple("run-script", CommandParseStatus::CLI_RUN_SCRIPT) ); output.push_back( std::make_tuple("pause", CommandParseStatus::CLI_PAUSE) ); output.push_back( std::make_tuple("sleep", CommandParseStatus::CLI_SLEEP) ); output.push_back( std::make_tuple("var-add", CommandParseStatus::CLI_VARIABLE_ADD) ); output.push_back( std::make_tuple("var-rm", CommandParseStatus::CLI_VARIABLE_RM) ); output.push_back( std::make_tuple("var-show", CommandParseStatus::CLI_VARIABLE_SHOW)); output.push_back( std::make_tuple("async-show", CommandParseStatus::CLI_ASYNC_SHOW) ); output.push_back( std::make_tuple("help", CommandParseStatus::VALID) ); ///< CLI Help Commands should be treated like normal commands. output.push_back( std::make_tuple("cli-resize", CommandParseStatus::VALID) ); ///< CLI Resize Commands should be treated like normal commands. // return output return output; } } // End of CMD Namespace } // End of CLI Namespace
28.179039
160
0.598326
[ "vector" ]
d3adbbeda2b2ce08cb26cd3861d0a4edf6108acd
5,800
hpp
C++
cuarma/meta/tag_of.hpp
yangxianpku/cuarma
404f20b5b3fa74e5e27338e89343450f8853024c
[ "X11", "MIT" ]
null
null
null
cuarma/meta/tag_of.hpp
yangxianpku/cuarma
404f20b5b3fa74e5e27338e89343450f8853024c
[ "X11", "MIT" ]
null
null
null
cuarma/meta/tag_of.hpp
yangxianpku/cuarma
404f20b5b3fa74e5e27338e89343450f8853024c
[ "X11", "MIT" ]
null
null
null
#pragma once /* ========================================================================= Copyright (c) 2015-2017, COE of Peking University, Shaoqiang Tang. ----------------- cuarma - COE of Peking University, Shaoqiang Tang. ----------------- Author Email yangxianpku@pku.edu.cn Code Repo https://github.com/yangxianpku/cuarma License: MIT (X11) License ============================================================================= */ /** @file tag_of.hpp @brief Dispatch facility for distinguishing between ublas, STL and cuarma types */ #include <vector> #include <map> #include "cuarma/forwards.h" #ifdef CUARMA_WITH_UBLAS #include <boost/numeric/ublas/matrix_sparse.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/vector.hpp> #endif namespace cuarma { // ---------------------------------------------------- // TAGS // /** @brief A tag class for identifying 'unknown' types. */ struct tag_none {}; /** @brief A tag class for identifying types from uBLAS. */ struct tag_ublas {}; /** @brief A tag class for identifying types from the C++ STL. */ struct tag_stl {}; /** @brief A tag class for identifying types from cuarma. */ struct tag_cuarma {}; namespace traits { // ---------------------------------------------------- // GENERIC BASE // /** @brief Generic base for wrapping other linear algebra packages * * Maps types to tags, e.g. cuarma::vector to tag_cuarma, ublas::vector to tag_ublas * if the matrix type is unknown, tag_none is returned * * This is an internal function only, there is no need for a library user of cuarma to care about it any further * * @tparam T The type to be inspected */ template< typename T, typename Active = void > struct tag_of; /** \cond */ template< typename Sequence, typename Active > struct tag_of { typedef cuarma::tag_none type; }; #ifdef CUARMA_WITH_UBLAS // ---------------------------------------------------- // UBLAS // template< typename T > struct tag_of< boost::numeric::ublas::vector<T> > { typedef cuarma::tag_ublas type; }; template< typename T > struct tag_of< boost::numeric::ublas::matrix<T> > { typedef cuarma::tag_ublas type; }; template< typename T1, typename T2 > struct tag_of< boost::numeric::ublas::matrix_unary2<T1,T2> > { typedef cuarma::tag_ublas type; }; template< typename T1, typename T2 > struct tag_of< boost::numeric::ublas::compressed_matrix<T1,T2> > { typedef cuarma::tag_ublas type; }; #endif // ---------------------------------------------------- // STL types // //vector template< typename T, typename A > struct tag_of< std::vector<T, A> > { typedef cuarma::tag_stl type; }; //dense matrix template< typename T, typename A > struct tag_of< std::vector<std::vector<T, A>, A> > { typedef cuarma::tag_stl type; }; //sparse matrix (vector of maps) template< typename KEY, typename DATA, typename COMPARE, typename AMAP, typename AVEC> struct tag_of< std::vector<std::map<KEY, DATA, COMPARE, AMAP>, AVEC> > { typedef cuarma::tag_stl type; }; // ---------------------------------------------------- // CUARMA // template< typename T, unsigned int alignment > struct tag_of< cuarma::vector<T, alignment> > { typedef cuarma::tag_cuarma type; }; template< typename T, typename F, unsigned int alignment > struct tag_of< cuarma::matrix<T, F, alignment> > { typedef cuarma::tag_cuarma type; }; template< typename T1, typename T2, typename OP > struct tag_of< cuarma::matrix_expression<T1,T2,OP> > { typedef cuarma::tag_cuarma type; }; template< typename T > struct tag_of< cuarma::matrix_range<T> > { typedef cuarma::tag_cuarma type; }; template< typename T, unsigned int I> struct tag_of< cuarma::compressed_matrix<T,I> > { typedef cuarma::tag_cuarma type; }; template< typename T, unsigned int I> struct tag_of< cuarma::coordinate_matrix<T,I> > { typedef cuarma::tag_cuarma type; }; template< typename T, unsigned int I> struct tag_of< cuarma::ell_matrix<T,I> > { typedef cuarma::tag_cuarma type; }; template< typename T, typename I> struct tag_of< cuarma::sliced_ell_matrix<T,I> > { typedef cuarma::tag_cuarma type; }; template< typename T, unsigned int I> struct tag_of< cuarma::hyb_matrix<T,I> > { typedef cuarma::tag_cuarma type; }; // ---------------------------------------------------- } // end namespace traits /** @brief Meta function which checks whether a tag is tag_ublas * * This is an internal function only, there is no need for a library user of cuarma to care about it any further */ template<typename Tag> struct is_ublas { enum { value = false }; }; /** \cond */ template<> struct is_ublas< cuarma::tag_ublas > { enum { value = true }; }; /** \endcond */ /** @brief Meta function which checks whether a tag is tag_ublas * * This is an internal function only, there is no need for a library user of cuarma to care about it any further */ template<typename Tag> struct is_stl { enum { value = false }; }; /** \cond */ template<> struct is_stl< cuarma::tag_stl > { enum { value = true }; }; /** \endcond */ /** @brief Meta function which checks whether a tag is tag_cuarma * * This is an internal function only, there is no need for a library user of cuarma to care about it any further */ template<typename Tag> struct is_cuarma { enum { value = false }; }; /** \cond */ template<> struct is_cuarma< cuarma::tag_cuarma > { enum { value = true }; }; /** \endcond */ } // end namespace cuarma
23.2
114
0.598448
[ "vector" ]
d3b1acfa6e209e73d190ddecb60d29804cb56303
12,231
cpp
C++
Mango/app/chunk.cpp
jonomango/Mango
05c78be87eec4f103346da222b16865311ab7c27
[ "MIT" ]
1
2019-10-19T20:38:57.000Z
2019-10-19T20:38:57.000Z
Mango/app/chunk.cpp
jonomango/Mango
05c78be87eec4f103346da222b16865311ab7c27
[ "MIT" ]
null
null
null
Mango/app/chunk.cpp
jonomango/Mango
05c78be87eec4f103346da222b16865311ab7c27
[ "MIT" ]
null
null
null
#include "chunk.h" uint64_t PackChunk(int x, int z) { uint64_t packed_chunk; *reinterpret_cast<int32_t*>(uintptr_t(&packed_chunk)) = int32_t(x); *reinterpret_cast<int32_t*>(uintptr_t(&packed_chunk) + 4) = int32_t(z); return packed_chunk; } void UnpackChunk(uint64_t chunk, int& x, int& z) { x = *reinterpret_cast<int32_t*>(uintptr_t(&chunk)); z = *reinterpret_cast<int32_t*>(uintptr_t(&chunk) + 4); } void Chunk::Setup(int x, int z) { m_x = x; m_z = z; m_blocks = new Block[WIDTH * HEIGHT * DEPTH]; memset(m_blocks, 0, sizeof(Block) * WIDTH * HEIGHT * DEPTH); m_model.Setup(GL_TRIANGLES, 0, GL_UNSIGNED_INT, nullptr); m_model.AddVBO().Setup(0, nullptr); m_model.AddVBO().Setup(0, nullptr); m_model.AddVBO().Setup(0, nullptr); } void Chunk::Release() { if (!m_blocks) return; m_model.Release(); delete[] m_blocks; m_blocks = nullptr; } bool Chunk::Update(std::unordered_map<uint64_t, std::shared_ptr<Chunk>>& chunks, const BlockMap& block_map) { if (!m_needs_update) return false; m_needs_update = false; std::vector<float> vertices; std::vector<float> tex_coords; std::vector<BLOCK_ID> block_ids; std::vector<unsigned int> indices; const auto MakeBlock = [&vertices, &tex_coords, &block_ids, &indices, &chunks, &block_map, this](int x, int y, int z, int block_id) -> void { if (!GetBlock(x, y, z).m_is_active) return; const auto FindChunk = [&chunks](int chunk_x, int chunk_z) -> Chunk* { if (auto it = chunks.find(PackChunk(chunk_x, chunk_z)); it != chunks.end()) return &*it->second; return nullptr; }; const auto IsBlockActive = [FindChunk, this](int x, int y, int z, bool bx, bool bz) -> bool { const int chunk_x = m_x, chunk_z = m_z; // false = draw // true = dont draw if (bx) { if (x < 0) { auto chunk = FindChunk(chunk_x - 1, chunk_z); if (!chunk) return false; return chunk->GetBlock(WIDTH - 1, y, z).m_is_active; } else if (x >= WIDTH) { //return false; auto chunk = FindChunk(chunk_x + 1, chunk_z); if (!chunk) return false; return chunk->GetBlock(0, y, z).m_is_active; } else return GetBlock(x, y, z).m_is_active; } else if (bz) { if (z < 0) { auto chunk = FindChunk(chunk_x, chunk_z - 1); if (!chunk) return false; return chunk->GetBlock(x, y, DEPTH - 1).m_is_active; } else if (z >= WIDTH) { //return false; auto chunk = FindChunk(chunk_x, chunk_z + 1); if (!chunk) return false; return chunk->GetBlock(x, y, 0).m_is_active; } else return GetBlock(x, y, z).m_is_active; } return true; }; const float f_x = float(x), f_y = float(y), f_z = float(z); const auto block_element = block_map.GetBlock(block_id); // front face if (!IsBlockActive(x, y, z + 1, false, true)) { const unsigned int start = vertices.size() / 3; vertices.push_back(f_x); vertices.push_back(f_y); vertices.push_back(f_z + 1.f); tex_coords.push_back(0.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[0]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y); vertices.push_back(f_z + 1.f); tex_coords.push_back(1.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[0]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y + 1.f); vertices.push_back(f_z + 1.f); tex_coords.push_back(1.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[0]); vertices.push_back(f_x); vertices.push_back(f_y + 1.f); vertices.push_back(f_z + 1.f); tex_coords.push_back(0.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[0]); indices.push_back(start + 0); indices.push_back(start + 1); indices.push_back(start + 2); indices.push_back(start + 0); indices.push_back(start + 2); indices.push_back(start + 3); } // back if (!IsBlockActive(x, y, z - 1, false, true)) { const unsigned int start = vertices.size() / 3; vertices.push_back(f_x); vertices.push_back(f_y); vertices.push_back(f_z); tex_coords.push_back(1.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[1]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y); vertices.push_back(f_z); tex_coords.push_back(0.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[1]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y + 1.f); vertices.push_back(f_z); tex_coords.push_back(0.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[1]); vertices.push_back(f_x); vertices.push_back(f_y + 1.f); vertices.push_back(f_z); tex_coords.push_back(1.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[1]); indices.push_back(start + 1); indices.push_back(start + 0); indices.push_back(start + 3); indices.push_back(start + 1); indices.push_back(start + 3); indices.push_back(start + 2); } // right if (!IsBlockActive(x + 1, y, z, true, false)) { const unsigned int start = vertices.size() / 3; vertices.push_back(f_x + 1.f); vertices.push_back(f_y); vertices.push_back(f_z + 1.f); tex_coords.push_back(0.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[2]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y); vertices.push_back(f_z); tex_coords.push_back(1.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[2]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y + 1.f); vertices.push_back(f_z); tex_coords.push_back(1.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[2]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y + 1.f); vertices.push_back(f_z + 1.f); tex_coords.push_back(0.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[2]); indices.push_back(start + 0); indices.push_back(start + 1); indices.push_back(start + 2); indices.push_back(start + 0); indices.push_back(start + 2); indices.push_back(start + 3); } // left if (!IsBlockActive(x - 1, y, z, true, false)) { const unsigned int start = vertices.size() / 3; vertices.push_back(f_x); vertices.push_back(f_y); vertices.push_back(f_z); tex_coords.push_back(0.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[3]); vertices.push_back(f_x); vertices.push_back(f_y); vertices.push_back(f_z + 1.f); tex_coords.push_back(1.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[3]); vertices.push_back(f_x); vertices.push_back(f_y + 1.f); vertices.push_back(f_z + 1.f); tex_coords.push_back(1.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[3]); vertices.push_back(f_x); vertices.push_back(f_y + 1.f); vertices.push_back(f_z); tex_coords.push_back(0.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[3]); indices.push_back(start + 0); indices.push_back(start + 1); indices.push_back(start + 2); indices.push_back(start + 0); indices.push_back(start + 2); indices.push_back(start + 3); } // top if (y >= HEIGHT - 1 || !GetBlock(x, y + 1, z).m_is_active) { const unsigned int start = vertices.size() / 3; vertices.push_back(f_x); vertices.push_back(f_y + 1.f); vertices.push_back(f_z + 1.f); tex_coords.push_back(0.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[4]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y + 1.f); vertices.push_back(f_z + 1.f); tex_coords.push_back(1.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[4]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y + 1.f); vertices.push_back(f_z); tex_coords.push_back(1.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[4]); vertices.push_back(f_x); vertices.push_back(f_y + 1.f); vertices.push_back(f_z); tex_coords.push_back(0.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[4]); indices.push_back(start + 0); indices.push_back(start + 1); indices.push_back(start + 2); indices.push_back(start + 0); indices.push_back(start + 2); indices.push_back(start + 3); } // bottom (dont draw the bottom face of the bottom blocks in the world) if (y > 0 && !GetBlock(x, y - 1, z).m_is_active) { const unsigned int start = vertices.size() / 3; vertices.push_back(f_x); vertices.push_back(f_y); vertices.push_back(f_z); tex_coords.push_back(0.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[5]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y); vertices.push_back(f_z); tex_coords.push_back(1.f); tex_coords.push_back(0.f); block_ids.push_back(block_element.m_face_indices[5]); vertices.push_back(f_x + 1.f); vertices.push_back(f_y); vertices.push_back(f_z + 1.f); tex_coords.push_back(1.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[5]); vertices.push_back(f_x); vertices.push_back(f_y); vertices.push_back(f_z + 1.f); tex_coords.push_back(0.f); tex_coords.push_back(1.f); block_ids.push_back(block_element.m_face_indices[5]); indices.push_back(start + 0); indices.push_back(start + 1); indices.push_back(start + 2); indices.push_back(start + 0); indices.push_back(start + 2); indices.push_back(start + 3); } }; for (int x = 0; x < WIDTH; x++) { for (int y = 0; y < HEIGHT; y++) { for (int z = 0; z < DEPTH; z++) { MakeBlock(x, y, z, GetBlock(x, y, z).m_block_id); } } } // empty if (indices.empty()) return false; auto positions_buffer = &m_model.GetVBOs()[0]; auto tex_coords_buffer = &m_model.GetVBOs()[1]; auto block_id_buffer = &m_model.GetVBOs()[2]; auto index_buffer = &m_model.GetIBO(); m_model.GetVAO().Bind(); // index buffer index_buffer->Bind(); index_buffer->SetCount(indices.size()); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), indices.data(), GL_DYNAMIC_DRAW); // positions positions_buffer->Bind(); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), vertices.data(), GL_DYNAMIC_DRAW); Mango::VertexArray::EnableAttribute(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, 0); // tex_coords tex_coords_buffer->Bind(); glBufferData(GL_ARRAY_BUFFER, tex_coords.size() * sizeof(float), tex_coords.data(), GL_DYNAMIC_DRAW); Mango::VertexArray::EnableAttribute(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0); // block ids block_id_buffer->Bind(); glBufferData(GL_ARRAY_BUFFER, block_ids.size() * sizeof(BLOCK_ID), block_ids.data(), GL_DYNAMIC_DRAW); Mango::VertexArray::EnableAttributeInt(2, 1, GL_UNSIGNED_SHORT, sizeof(BLOCK_ID), 0); Mango::VertexArray::Unbind(); return true; } int Chunk::PositionXToChunk(int x) { return (x >= 0) ? (x / WIDTH) : ((x + 1) / WIDTH - 1); } int Chunk::PositionZToChunk(int z) { return (z >= 0) ? (z / DEPTH) : ((z + 1) / DEPTH - 1); } uint32_t Chunk::PackBlock(int x, int y, int z) { uint32_t block; *reinterpret_cast<uint8_t*>(uintptr_t(&block)) = uint8_t(x); *reinterpret_cast<uint8_t*>(uintptr_t(&block) + 1) = uint8_t(z); *reinterpret_cast<uint16_t*>(uintptr_t(&block) + 2) = uint16_t(y); return block; } void Chunk::UnpackBlock(uint32_t block, int& x, int& y, int& z) { x = int(*reinterpret_cast<uint8_t*>(uintptr_t(&block))); z = int(*reinterpret_cast<uint8_t*>(uintptr_t(&block) + 1)); y = int(*reinterpret_cast<uint16_t*>(uintptr_t(&block) + 2)); } void Chunk::SetBlock(int x, int y, int z, const Block& block) { m_needs_update = true; m_blocks[x + (y * WIDTH) + (z * WIDTH * HEIGHT)] = block; } Block Chunk::GetBlock(int x, int y, int z) { return m_blocks[x + (y * WIDTH) + (z * WIDTH * HEIGHT)]; }
26.134615
140
0.672063
[ "vector" ]
d3b5695734e1b22d397c168329107ed159e232da
4,577
cpp
C++
src/game/shared/tf2/weapon_combat_basegrenade.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/shared/tf2/weapon_combat_basegrenade.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/shared/tf2/weapon_combat_basegrenade.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Base class for hand-thrown grenades that work with the handheld shield // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "basetfplayer_shared.h" #include "weapon_combat_basegrenade.h" #include "weapon_combatshield.h" #include "in_buttons.h" LINK_ENTITY_TO_CLASS( weapon_combat_basegrenade, CWeaponCombatBaseGrenade ); IMPLEMENT_NETWORKCLASS_ALIASED( WeaponCombatBaseGrenade, DT_WeaponCombatBaseGrenade ) BEGIN_NETWORK_TABLE( CWeaponCombatBaseGrenade, DT_WeaponCombatBaseGrenade ) #if !defined( CLIENT_DLL ) SendPropTime( SENDINFO( m_flStartedThrowAt ) ), #else RecvPropTime( RECVINFO( m_flStartedThrowAt ) ), #endif END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CWeaponCombatBaseGrenade ) DEFINE_PRED_FIELD_TOL( m_flStartedThrowAt, FIELD_FLOAT, FTYPEDESC_INSENDTABLE, TD_MSECTOLERANCE ), END_PREDICTION_DATA() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWeaponCombatBaseGrenade::CWeaponCombatBaseGrenade( void ) { m_flStartedThrowAt = 0; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CWeaponCombatBaseGrenade::GetFireRate( void ) { return 2.0; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponCombatBaseGrenade::ItemPostFrame( void ) { CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); if (!pOwner) return; AllowShieldPostFrame( !m_flStartedThrowAt ); // Look for button downs if ( (pOwner->m_nButtons & IN_ATTACK) && GetShieldState() == SS_DOWN && !m_flStartedThrowAt && (m_flNextPrimaryAttack <= gpGlobals->curtime) ) { m_flStartedThrowAt = gpGlobals->curtime; SendWeaponAnim( ACT_VM_DRAW ); } // Look for button ups if ( (pOwner->m_afButtonReleased & IN_ATTACK) && (m_flNextPrimaryAttack <= gpGlobals->curtime) && m_flStartedThrowAt ) { m_flNextPrimaryAttack = gpGlobals->curtime; PrimaryAttack(); m_flStartedThrowAt = 0; } // No buttons down? if ( !((pOwner->m_nButtons & IN_ATTACK) || (pOwner->m_nButtons & IN_ATTACK2) || (pOwner->m_nButtons & IN_RELOAD)) ) { WeaponIdle( ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponCombatBaseGrenade::PrimaryAttack( void ) { CBasePlayer *pPlayer = dynamic_cast<CBasePlayer*>( GetOwner() ); if ( !pPlayer ) return; if ( !ComputeEMPFireState() ) return; // player "shoot" animation PlayAttackAnimation( ACT_VM_THROW ); ThrowGrenade(); // Setup for refire m_flNextPrimaryAttack = gpGlobals->curtime + 1.0; CheckRemoveDisguise(); // If I'm now out of ammo, switch away if ( !HasPrimaryAmmo() ) { pPlayer->SelectLastItem(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponCombatBaseGrenade::ThrowGrenade( void ) { CBasePlayer *pPlayer = dynamic_cast<CBasePlayer*>( GetOwner() ); if ( !pPlayer ) return; BaseClass::WeaponSound(WPN_DOUBLE); // Calculate launch velocity (3 seconds for max distance) float flThrowTime = MIN( (gpGlobals->curtime - m_flStartedThrowAt), 3.0 ); float flSpeed = 650 + (175 * flThrowTime); // If the player's crouched, roll the grenade if ( pPlayer->GetFlags() & FL_DUCKING ) { // Launch the grenade Vector vecForward; QAngle vecAngles = pPlayer->EyeAngles(); // Throw it up just a tad vecAngles.x = -1; AngleVectors( vecAngles, &vecForward, NULL, NULL); Vector vecOrigin; VectorLerp( pPlayer->EyePosition(), pPlayer->GetAbsOrigin(), 0.25f, vecOrigin ); vecOrigin += (vecForward * 16); vecForward = vecForward * flSpeed; CreateGrenade(vecOrigin, vecForward, pPlayer ); } else { // Launch the grenade Vector vecForward; QAngle vecAngles = pPlayer->EyeAngles(); AngleVectors( vecAngles, &vecForward, NULL, NULL); Vector vecOrigin = pPlayer->EyePosition(); vecOrigin += (vecForward * 16); vecForward = vecForward * flSpeed; CreateGrenade(vecOrigin, vecForward, pPlayer ); } pPlayer->RemoveAmmo( 1, m_iPrimaryAmmoType ); }
29.915033
143
0.587503
[ "vector" ]
d3be26ce9daafbfb1fe8b2b06429f0a65e3ed7c3
1,234
cpp
C++
simu_planning/heuristic_grids/src/heuristic_grids_server.cpp
mathsg/ROS_initiation
09a8e9e5f9836ea8ed8261d694e2ef14768a9c5b
[ "BSD-3-Clause" ]
null
null
null
simu_planning/heuristic_grids/src/heuristic_grids_server.cpp
mathsg/ROS_initiation
09a8e9e5f9836ea8ed8261d694e2ef14768a9c5b
[ "BSD-3-Clause" ]
null
null
null
simu_planning/heuristic_grids/src/heuristic_grids_server.cpp
mathsg/ROS_initiation
09a8e9e5f9836ea8ed8261d694e2ef14768a9c5b
[ "BSD-3-Clause" ]
null
null
null
#include <algorithm> #include <math.h> #include <vector> #include "ros/ros.h" //The messages #include <visualization_msgs/MarkerArray.h> float control_frequency = 10.0; class RobotVisualization { public: ros::NodeHandle n; ros::Subscriber pose_sub; ros::Publisher robot_visu_pub. RobotVisualization() { // Parameters // n.param<double>("/heuristic_grids_server/grid_square_size", grid_square_size, 0.02); //The different subscribes pose_sub = n.subscribe("/kinematics/robot_pose", 1, &RobotVisualization::pose_callback, this); //The different publishers robot_visu_pub = n.advertise<visualization_msgs::marker_array>("/visualization/robot_visualization/the_robot", 1); } private: void pose_callback(const pose_msgs::RobotPose::ConstPtr &msg) { the_robot_pose = *msg; } simu_msgs::RobotPose the_robot_pose; }; int main(int argc, char **argv) { ros::init(argc, argv, "robot visualization"); RobotVisualization robot_visualization_; ros::Rate loop_rate(control_frequency); ROS_INFO("Heuristic grids server running"); while (robot_visualization_.n.ok()) { robot_visualization_.updateRobot(); ros::spinOnce(); loop_rate.sleep(); } ros::spin(); return 0; }
18.984615
116
0.725284
[ "vector" ]
d3d315b139b077b38ba6a6b0bec7976630c43c7e
860
cpp
C++
allosphere.node/src/phasespace.cpp
donghaoren/AllofwModule
4367327cda0605aad53469294ed8751f8befbdc3
[ "Unlicense" ]
3
2016-05-04T23:23:48.000Z
2021-08-03T21:48:07.000Z
allosphere.node/src/phasespace.cpp
donghaoren/AllofwModule
4367327cda0605aad53469294ed8751f8befbdc3
[ "Unlicense" ]
null
null
null
allosphere.node/src/phasespace.cpp
donghaoren/AllofwModule
4367327cda0605aad53469294ed8751f8befbdc3
[ "Unlicense" ]
2
2016-01-31T04:06:51.000Z
2016-09-30T16:38:36.000Z
#include "phasespace/phasespace/Phasespace.hpp" #include "phasespace.h" namespace allofw { class PhasespaceImpl : public Phasespace { public: PhasespaceImpl() { tracker = ::Phasespace::master(); } // Get marker positions. virtual void getMarkers(Vector3* positions, int* last_seens, int start, int count) { vector<Vec3f> pos(count); tracker->getMarkers(&pos[0], last_seens, start, count); for(int i = 0; i < count; i++) { positions[i].x = pos[i].x; positions[i].y = pos[i].y; positions[i].z = pos[i].z; } } virtual void start() { tracker->start(); } virtual ~PhasespaceImpl() { tracker->stop(); delete tracker; } ::Phasespace* tracker; }; Phasespace* Phasespace::Create() { return new PhasespaceImpl(); } }
20.97561
88
0.577907
[ "vector" ]
d3d5d688282e49e341dc298d6adc240d5012c96e
34,906
cpp
C++
source/cscript/lib/CCLib_UI.cpp
chromaScript/chroma.io
c484354df6f3c84a049ffadfe37c677c0ccb6390
[ "MIT" ]
null
null
null
source/cscript/lib/CCLib_UI.cpp
chromaScript/chroma.io
c484354df6f3c84a049ffadfe37c677c0ccb6390
[ "MIT" ]
null
null
null
source/cscript/lib/CCLib_UI.cpp
chromaScript/chroma.io
c484354df6f3c84a049ffadfe37c677c0ccb6390
[ "MIT" ]
null
null
null
#include "../../include/cscript/CCallable.h" #include "../../include/cscript/CCallable_Lib.h" #include "../../include/cscript/lib/CCLib_UI.h" #include "../../include/cscript/ChromaScript.h" #include "../../include/cscript/CForward.h" #include "../../include/cscript/CLiteral.h" #include "../../include/cscript/CExpr.h" #include "../../include/cscript/CStmt.h" #include "../../include/cscript/CEnvironment.h" #include "../../include/cscript/CInterpreter.h" #include "../../include/cscript/CEnums.h" #include "../../include/clayout/LEnums.h" #include "../../include/cscript/CObject.h" #include "../../include/cscript/CToken.h" #include "../../include/entities/widgets/WidgetStyle.h" #include "../../include/Application.h" #include "../../include/entities/UserInterface.h" #include "../../include/tool/Toolbox.h" #include "../../include/entities/widgets/Widget.h" #include "../../include/input/keys.h" #include <glm.hpp> #include <GLFW/glfw3.h> #include <string> #include <vector> #include <iostream> #include <variant> #include <map> extern std::shared_ptr<Application> chromaIO; //////////////////////////////////////////////////////////////////////////////////////////////// // // CStd_Ui // //////////////////////////////////////////////////////////////////////////////////////////////// CStd_cUi::CStd_cUi(std::shared_ptr<CEnvironment> classEnv, std::shared_ptr<Application> app) { this->name = "Ui"; this->type = CCallableTypes::_CStd_cUi; this->classEnv = classEnv; this->superClass = nullptr; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CStmt>> methods; this->classEnv.get()->define( "checkWidgetIDTable", std::make_shared<CObject>(CCallableTypes::_CStd_cfCheckWidgetIDTable, classEnv.get()->lookupEnvironment("checkWidgetIDTable", true))); this->classEnv.get()->define( "moveRootToFront", std::make_shared<CObject>(CCallableTypes::_CStd_cfMoveRootToFront, classEnv.get()->lookupEnvironment("moveRootToFront", true))); this->classEnv.get()->define( "preventBlurCallback", std::make_shared<CObject>(CCallableTypes::_CStd_cfPreventBlurCallback, classEnv.get()->lookupEnvironment("preventBlurCallback", true))); this->classEnv.get()->define( "preventFocusCallback", std::make_shared<CObject>(CCallableTypes::_CStd_cfPreventFocusCallback, classEnv.get()->lookupEnvironment("preventFocusCallback", true))); this->classEnv.get()->define( "setActivePopup", std::make_shared<CObject>(CCallableTypes::_CStd_cfSetActivePopup, classEnv.get()->lookupEnvironment("setActivePopup", true))); this->classEnv.get()->define( "clearPopup", std::make_shared<CObject>(CCallableTypes::_CStd_cfClearPopup, classEnv.get()->lookupEnvironment("clearPopup", true))); this->classEnv.get()->define( "setFocus_byID", std::make_shared<CObject>(CCallableTypes::_CStd_cfSetFocus_byID, classEnv.get()->lookupEnvironment("setFocus_byID", true))); this->classEnv.get()->define( "clearFocus", std::make_shared<CObject>(CCallableTypes::_CStd_cfClearFocus, classEnv.get()->lookupEnvironment("clearFocus", true))); this->classEnv.get()->define( "getWidget_byID", std::make_shared<CObject>(CCallableTypes::_CStd_cfGetWidget_byID, classEnv.get()->lookupEnvironment("getWidget_byID", true))); this->classEnv.get()->define( "deleteWidget_byID", std::make_shared<CObject>(CCallableTypes::_CStd_cfDeleteWidget_byID, classEnv.get()->lookupEnvironment("deleteWidget_byID", true))); this->classEnv.get()->define( "sortTargetWidgetChildren_byMacro", std::make_shared<CObject>(CCallableTypes::_CStd_cfSortTargetWidgetChildren_byMacro, classEnv.get()->lookupEnvironment("sortTargetWidgetChildren_byMacro", true))); this->classEnv.get()->define( "setFGColor_HSL", std::make_shared<CObject>(CCallableTypes::_CStd_cfSetFGColor_HSL, classEnv.get()->lookupEnvironment("setFGColor_HSL", true))); this->classEnv.get()->define( "setBGColor_HSL", std::make_shared<CObject>(CCallableTypes::_CStd_cfSetBGColor_HSL, classEnv.get()->lookupEnvironment("setBGColor_HSL", true))); this->classEnv.get()->define( "resetFGBGColor", std::make_shared<CObject>(CCallableTypes::_CStd_cfResetFGBGColor, classEnv.get()->lookupEnvironment("resetFGBGColor", true))); this->classEnv.get()->define( "swapFGBGColor", std::make_shared<CObject>(CCallableTypes::_CStd_cfSwapFGBGColor, classEnv.get()->lookupEnvironment("swapFGBGColor", true))); this->classEnv.get()->define( "createNewDocument", std::make_shared<CObject>(CCallableTypes::_CStd_cfCreateNewDocument, classEnv.get()->lookupEnvironment("createNewDocument", true))); this->classEnv.get()->define( "closeDocument", std::make_shared<CObject>(CCallableTypes::_CStd_cfCloseDocument, classEnv.get()->lookupEnvironment("closeDocument", true))); for (auto const& item : this->classEnv.get()->values) { std::shared_ptr<CStmt> func = std::get<std::shared_ptr<CFunction>>(item.second.get()->obj).get()->funcDeclaration; methods.push_back(func); } // Build the properties std::vector<std::shared_ptr<CStmt>> properties; // Raw UI Literal Object (Hidden using @) this->classEnv.get()->define("@uiObj", std::make_shared<CObject>(app.get()->getUI())); // Construct the pseudo-CStmt_Class object this->classDeclaration = std::make_shared<CStmt_Class>( scopeStack, // scopeStack (empty) std::make_shared<CToken>(CTokenType::IDENTIFIER, this->name, -1), // name nullptr, // superClass false, // isDeclarationOnly nullptr, // constructor methods, // methods properties // properties ); } std::string CStd_cUi::toString() { return name; } //////////////////////////////////////////////////////////////////////////////////////////////// // // Ui Class Functions // //////////////////////////////////////////////////////////////////////////////////////////////// // // // CStd_cfCheckWidgetIDTable CStd_cfCheckWidgetIDTable::CStd_cfCheckWidgetIDTable(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfCheckWidgetIDTable; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("id"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::BOOL, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "checkWidgetIDTable", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfCheckWidgetIDTable::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Cast Arg 0 as string std::string id = std::get<std::string>(args[0].get()->obj); // Call getWidget_byID on the UI std::weak_ptr<UI> ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj); if (!ui.expired()) { if (ui.lock()->widgetIDTable.count(id) == 0) { return std::make_shared<CObject>(true); } } return std::make_shared<CObject>(false); } std::string CStd_cfCheckWidgetIDTable::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfMoveRootToFront CStd_cfMoveRootToFront::CStd_cfMoveRootToFront(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfMoveRootToFront; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("id"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "moveRootToFront", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfMoveRootToFront::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Cast Arg 0 as string & Arg 1 as Function std::string id = std::get<std::string>(args[0].get()->obj); // Check that the widget id is valid UI* ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get(); std::weak_ptr<Widget> widget = ui->getWidgetByID(id); if (!widget.expired()) { ui->moveRootToFront(widget.lock().get()->getRoot()); } return std::make_shared<CObject>(nullptr); } std::string CStd_cfMoveRootToFront::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfSetActivePopup CStd_cfSetActivePopup::CStd_cfSetActivePopup(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfSetActivePopup; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::BOOL, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::FUNCTION, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("id"); paramsNames.push_back("isBlocking"); paramsNames.push_back("escapeCallback"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "setActivePopup", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfSetActivePopup::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Cast Arg 0 as string & Arg 1 as Function std::string id = std::get<std::string>(args[0].get()->obj); bool isBlocking = std::get<bool>(args[1].get()->obj); std::shared_ptr<CFunction> callback = std::get<std::shared_ptr<CFunction>>(args[2].get()->obj); // Check that the widget id is valid UI* ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get(); std::weak_ptr<Widget> widget = ui->getWidgetByID(id); if (!widget.expired()) { ui->putActivePopupWidget(widget, isBlocking, callback); } return std::make_shared<CObject>(nullptr); } std::string CStd_cfSetActivePopup::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfClearPopup CStd_cfClearPopup::CStd_cfClearPopup(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfClearPopup; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("id"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "clearPopup", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfClearPopup::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Cast Arg 0 as string std::string id = std::get<std::string>(args[0].get()->obj); // Get the UI UI* ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get(); std::weak_ptr<Widget> widget = ui->getWidgetByID(id); if (!widget.expired()) { ui->clearPopupWidget(widget); } return std::make_shared<CObject>(nullptr); } std::string CStd_cfClearPopup::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfPreventBlurCallback CStd_cfPreventBlurCallback::CStd_cfPreventBlurCallback(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfSetFocus_byID; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; std::vector<std::string> paramsNames; this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "preventBlurCallback", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfPreventBlurCallback::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Fetch the UI std::weak_ptr<UI> ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj); if (!ui.expired()) { ui.lock().get()->interruptBlur = true; } return std::make_shared<CObject>(nullptr); } std::string CStd_cfPreventBlurCallback::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfPreventFocusCallback CStd_cfPreventFocusCallback::CStd_cfPreventFocusCallback(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfPreventFocusCallback; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; std::vector<std::string> paramsNames; this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "preventFocusCallback", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfPreventFocusCallback::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Fetch the UI std::weak_ptr<UI> ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj); if (!ui.expired()) { ui.lock().get()->interruptFocus = true; } return std::make_shared<CObject>(nullptr); } std::string CStd_cfPreventFocusCallback::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfSetFocus_byID CStd_cfSetFocus_byID::CStd_cfSetFocus_byID(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfSetFocus_byID; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("id"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "setFocus_byID", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfSetFocus_byID::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Cast Arg 0 as string std::string id = std::get<std::string>(args[0].get()->obj); // Call getWidget_byID on the UI std::weak_ptr<UI> ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj); std::weak_ptr<Widget> widget = ui.lock().get()->getWidgetByID(id); if (!widget.expired()) { ui.lock().get()->updateFocusWidget(widget); } return std::make_shared<CObject>(nullptr); } std::string CStd_cfSetFocus_byID::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfClearFocus CStd_cfClearFocus::CStd_cfClearFocus(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfClearFocus; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; std::vector<std::string> paramsNames; this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "clearFocus", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfClearFocus::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Call getWidget_byID on the UI std::weak_ptr<UI> ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj); ui.lock().get()->clearFocusWidget(); return std::make_shared<CObject>(nullptr); } std::string CStd_cfClearFocus::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfGetWidget_byID CStd_cfGetWidget_byID::CStd_cfGetWidget_byID(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_fSetChildProperty_byID; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("id"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::IDENTIFIER, "Widget", -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "setChildProperty_byID", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfGetWidget_byID::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Cast Arg 0 as string std::string id = std::get<std::string>(args[0].get()->obj); // Call getWidget_byID on the UI std::weak_ptr<Widget> widget = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get()->getWidgetByID(id); if (!widget.expired()) { std::vector<std::shared_ptr<CObject>> instanceArgs; std::shared_ptr<CObject> callee = interpreter.get()->currentEnvironment.get()->get({ "global" }, "Widget"); instanceArgs.push_back(callee); instanceArgs.push_back(args[0]); std::shared_ptr<CObject> returnObj = std::get<std::shared_ptr<CClass>>(callee.get()->obj).get()->call(interpreter, &instanceArgs); std::get<std::shared_ptr<CInstance>>(returnObj.get()->obj).get()->instanceEnv.get()->get("@widgetObj").get()->obj = widget; return returnObj; } return std::make_shared<CObject>(nullptr); } std::string CStd_cfGetWidget_byID::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfDeleteWidget_byID CStd_cfDeleteWidget_byID::CStd_cfDeleteWidget_byID(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfDeleteWidget_byID; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("id"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::BOOL, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "deleteWidget_byID", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfDeleteWidget_byID::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Cast Arg 0 as string std::string id = std::get<std::string>(args[0].get()->obj); // Call getWidget_byID on the UI bool result = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get()->deleteWidget_byID(interpreter, id); return std::make_shared<CObject>(result); } std::string CStd_cfDeleteWidget_byID::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfSortTargetWidgetChildren_byMacro CStd_cfSortTargetWidgetChildren_byMacro::CStd_cfSortTargetWidgetChildren_byMacro(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfSortTargetWidgetChildren_byMacro; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::BOOL, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("id"); paramsNames.push_back("sortProperty"); paramsNames.push_back("macroIDName"); paramsNames.push_back("setVisible"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::BOOL, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "sortTargetWidgetChildren_byMacro", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfSortTargetWidgetChildren_byMacro::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Unpack arguments std::string id = std::get<std::string>(args[0].get()->obj); std::string sortProperty = std::get<std::string>(args[1].get()->obj); std::string macroIDName = std::get<std::string>(args[2].get()->obj); bool setVisible = std::get<bool>(args[3].get()->obj); // Call the function bool result = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get()->sortTargetWidgetChildren( interpreter, id, sortProperty, macroIDName, setVisible); return std::make_shared<CObject>(result); } std::string CStd_cfSortTargetWidgetChildren_byMacro::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfSetFGColor_HSL CStd_cfSetFGColor_HSL::CStd_cfSetFGColor_HSL(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfSetFGColor_HSL; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::NUM, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::NUM, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::NUM, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("hueDegree"); paramsNames.push_back("satPercent"); paramsNames.push_back("valPercent"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "setFGColor_HSL", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfSetFGColor_HSL::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Set the values double degree = abs(std::get<double>(args[0].get()->obj)); float satP = clampf(abs((float)std::get<double>(args[1].get()->obj)), 0.0f, 1.0f); float valP = clampf(abs((float)std::get<double>(args[2].get()->obj)), 0.0f, 1.0f); CColor hsl = HSL_toRGB(glm::dvec3(degree / 360.0, satP, valP)); std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get()->updateFGColor(hsl, 0, 0); return std::make_shared<CObject>(nullptr); } std::string CStd_cfSetFGColor_HSL::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfSetBGColor_HSL CStd_cfSetBGColor_HSL::CStd_cfSetBGColor_HSL(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfSetBGColor_HSL; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::NUM, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::NUM, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::NUM, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("hueDegree"); paramsNames.push_back("satPercent"); paramsNames.push_back("valPercent"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::IDENTIFIER, "Widget", -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "setBGColor_HSL", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfSetBGColor_HSL::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Set the values double degree = abs(std::get<double>(args[0].get()->obj)); float satP = clampf(abs((float)std::get<double>(args[1].get()->obj)), 0.0f, 1.0f); float valP = clampf(abs((float)std::get<double>(args[2].get()->obj)), 0.0f, 1.0f); CColor hsl = HSL_toRGB(glm::dvec3(degree / 360.0, satP, valP)); std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get()->updateBGColor(hsl, 0, 0); return std::make_shared<CObject>(nullptr); } std::string CStd_cfSetBGColor_HSL::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfResetFGBGColor CStd_cfResetFGBGColor::CStd_cfResetFGBGColor(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfResetFGBGColor; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; std::vector<std::string> paramsNames; this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "resetFGBGColor", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfResetFGBGColor::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Set the values std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get()->resetFGBGColor(black, white); return std::make_shared<CObject>(nullptr); } std::string CStd_cfResetFGBGColor::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfSwapFGBGColor CStd_cfSwapFGBGColor::CStd_cfSwapFGBGColor(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfSwapFGBGColor; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; std::vector<std::string> paramsNames; this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::_VOID, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "swapFGBGColor", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfSwapFGBGColor::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Set the values std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get()->swapFGBGColor(); return std::make_shared<CObject>(nullptr); } std::string CStd_cfSwapFGBGColor::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfCreateNewDocument CStd_cfCreateNewDocument::CStd_cfCreateNewDocument(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfCreateNewDocument; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::NUM, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::NUM, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::BOOL, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("id"); paramsNames.push_back("width"); paramsNames.push_back("height"); paramsNames.push_back("setAsActive"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::BOOL, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "createNewDocument", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfCreateNewDocument::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Cast Arg 0 as string std::string name = std::get<std::string>(args[0].get()->obj); int width = (int)std::round(std::get<double>(args[1].get()->obj)); int height = (int)std::round(std::get<double>(args[2].get()->obj)); bool setActive = std::get<bool>(args[3].get()->obj); // Get the UI UI* ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get(); if (ui != nullptr) { ui->newDocument(name, width, height, setActive); return std::make_shared<CObject>(true); } return std::make_shared<CObject>(false); } std::string CStd_cfCreateNewDocument::toString() { return funcDeclaration.get()->name.get()->lexeme; } // // // CStd_cfCreateNewDocument CStd_cfCloseDocument::CStd_cfCloseDocument(std::shared_ptr<CEnvironment> funcEnv) { this->funcEnv = funcEnv; this->type = CCallableTypes::_CStd_cfCloseDocument; std::vector<std::shared_ptr<CToken>> scopeStack; std::vector<std::shared_ptr<CToken>> paramsTypes; paramsTypes.push_back(std::make_shared<CToken>(CTokenType::STRING, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::NUM, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::BOOL, -1)); paramsTypes.push_back(std::make_shared<CToken>(CTokenType::BOOL, -1)); std::vector<std::string> paramsNames; paramsNames.push_back("name"); paramsNames.push_back("ueid"); paramsNames.push_back("closeActive"); paramsNames.push_back("saveBeforeExit"); this->funcDeclaration = std::make_shared<CStmt_Function>( std::make_shared<CToken>(CTokenType::BOOL, -1), // returnType std::make_shared<CToken>(CTokenType::IDENTIFIER, "closeDocument", -1), // name false, // isDeclarationOnly scopeStack, // scope operator (empty) paramsTypes, // paramTypes (empty) paramsNames, // paramNames (empty) nullptr // function body (native, see 'call()') ); } std::shared_ptr<CObject> CStd_cfCloseDocument::call( std::shared_ptr<CInterpreter> interpreter, std::vector<std::shared_ptr<CObject>>* arguments) { // Get Args std::vector<std::shared_ptr<CObject>> args = *arguments; // Cast Arg 0 as string std::string name = std::get<std::string>(args[0].get()->obj); int UEID = (int)std::round(std::get<double>(args[1].get()->obj)); bool closeActive = std::get<bool>(args[2].get()->obj); bool saveBeforeExit = std::get<bool>(args[3].get()->obj); // Get the UI UI* ui = std::get<std::shared_ptr<UI>>( interpreter.get()->currentEnvironment.get()->values.at("@uiObj").get()->obj).get(); if (ui != nullptr) { return std::make_shared<CObject>(ui->closeDocument(name, UEID, closeActive, saveBeforeExit)); } return std::make_shared<CObject>(false); } std::string CStd_cfCloseDocument::toString() { return funcDeclaration.get()->name.get()->lexeme; } //////////////////////////////////////////////////////////////////////////////////////////////// // // CStd_Document // //////////////////////////////////////////////////////////////////////////////////////////////// CStd_cDocument::CStd_cDocument(std::shared_ptr<CEnvironment> classEnv, std::shared_ptr<Application> app) { //this->classDeclaration = classDeclaration; //this->name = name; //this->type = type; //this->classEnv = classEnv; //this->superClass = superClass; } std::string CStd_cDocument::toString() { return name; }
42.106152
164
0.717728
[ "object", "vector" ]
d3d771ba1eaa42ed760b0a7b38f72290b02c3d06
1,440
hpp
C++
include/jcp/x509_encoded_key_spec_impl.hpp
jc-lab/jcp
852755534121bcaac12c49da9cd290c30e149f94
[ "Apache-2.0" ]
null
null
null
include/jcp/x509_encoded_key_spec_impl.hpp
jc-lab/jcp
852755534121bcaac12c49da9cd290c30e149f94
[ "Apache-2.0" ]
null
null
null
include/jcp/x509_encoded_key_spec_impl.hpp
jc-lab/jcp
852755534121bcaac12c49da9cd290c30e149f94
[ "Apache-2.0" ]
null
null
null
// // Created by jichan on 2019-08-21. // #ifndef __JCP_X509_ENCODED_KEY_SPEC_IMPL_HPP__ #define __JCP_X509_ENCODED_KEY_SPEC_IMPL_HPP__ #include "result.hpp" #include "asym_key.hpp" #include <vector> #include <jcp/asn1/asn1_object_identifier.hpp> #include <jcp/internal/asn1_types/Version.h> #include <jcp/internal/asn1_types/PublicKeyInfo.h> #include <jcp/internal/asn1_types/ECParameters.h> #include <jcp/internal/asn1_types/RSAPublicKey.h> namespace jcp { class X509EncodedKeySpecImpl { public: enum KeyAlgorithm { KEY_ALGO_UNKNOWN = 0, KEY_ALGO_RSA, KEY_ALGO_EC }; public: std::vector<unsigned char> raw_data_; PublicKeyInfo_t *asn_public_key_info_ptr; RSAPublicKey_t *rsa_public_key_ptr; asn1::ASN1ObjectIdentifier algo_oid_; KeyAlgorithm key_algo_; std::unique_ptr<jcp::AsymKey> parsed_asym_key_; jcp::Result<void> parseECKey(); jcp::Result<void> parseRSAKey(); public: X509EncodedKeySpecImpl(); ~X509EncodedKeySpecImpl(); jcp::Result<void> decode(const unsigned char *encoded, size_t length); std::unique_ptr<jcp::AsymKey> generateParsedKey() const; KeyAlgorithm getKeyAlgorithm() const { return key_algo_; } const asn1::ASN1ObjectIdentifier &getAlgoOid() const; }; } #endif // __JCP_X509_ENCODED_KEY_SPEC_IMPL_HPP__
26.181818
78
0.6875
[ "vector" ]
d3ea03301fc8874154d4139f6aae0d34c28505a6
8,370
cc
C++
Examples/computational_geometry/polygon.cc
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
null
null
null
Examples/computational_geometry/polygon.cc
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
null
null
null
Examples/computational_geometry/polygon.cc
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; namespace polygon { typedef double ftype; double DEG_to_RAD(double d) { return d * M_PI / 180.0; } double RAD_to_DEG(double r) { return r * 180.0 / M_PI; } struct point2d { ftype x, y; point2d() {} point2d(ftype x, ftype y) : x(x), y(y) {} point2d& operator+=(const point2d& t) { x += t.x; y += t.y; return *this; } point2d& operator-=(const point2d& t) { x -= t.x; y -= t.y; return *this; } point2d& operator*=(ftype t) { x *= t; y *= t; return *this; } point2d& operator/=(ftype t) { x /= t; y /= t; return *this; } point2d operator+(const point2d& t) const { return point2d(*this) += t; } point2d operator-(const point2d& t) const { return point2d(*this) -= t; } point2d operator*(ftype t) const { return point2d(*this) *= t; } point2d operator/(ftype t) const { return point2d(*this) /= t; } point2d rotate(double theta) const { double rad = DEG_to_RAD(theta); return point2d(x * cos(rad) - y * sin(rad), x * sin(rad) + y * cos(rad)); } }; point2d operator*(ftype a, point2d b) { return b * a; } void __print(point2d x) { cerr << "(" << x.x << "," << x.y << ")"; } ftype dot(point2d a, point2d b) { return a.x * b.x + a.y * b.y; } ftype norm(point2d a) { return dot(a, a); } double abs(point2d a) { return sqrt(norm(a)); } double proj(point2d a, point2d b) { return dot(a, b) / abs(b); } double angle(point2d a, point2d b) { return acos(dot(a, b) / abs(a) / abs(b)); } ftype cross(point2d a, point2d b) { return a.x * b.y - a.y * b.x; } point2d intersect(point2d a1, point2d d1, point2d a2, point2d d2) { return a1 + cross(a2 - a1, d2) / cross(d1, d2) * d1; } point2d line_intersetct_segment(point2d p, point2d q, point2d A, point2d B) { // segment p-q nd line A-B double a = B.y - A.y, b = A.x - B.x, c = B.x * A.y - A.x * B.y; double u = fabs(a * p.x + b * p.y + c); double v = fabs(a * q.x + b * q.y + c); return point2d((p.x * v + q.x * u) / (u + v), (p.y * v + q.y * u) / (u + v)); } struct polygon2d { vector<point2d> points; polygon2d() {} polygon2d(vector<point2d> x, const double EPS = 1e-9) : points(x) { if (not points.empty()) { if (abs(points.back() - points.front()) > EPS) points.push_back(points[0]); } } double perimeter() { double ans = 0.0; for (int i = 1; i < static_cast<int>(points.size()); ++i) ans += abs(points[i] - points[i - 1]); return ans; } double area() { double ans = 0.0; for (int i = 1; i < static_cast<int>(points.size()); ++i) ans += cross(points[i - 1], points[i]); return fabs(ans) / 2.0; } bool is_convex(const double EPS = 1e-9) { int N = static_cast<int>(points.size()); if (N <= 3) return false; // point or line bool first_turn = (cross(points[1] - points[0], points[2] - points[0]) > EPS); for (int i = 1; i < N - 1; ++i) { if ((cross(points[i + 1] - points[i], points[(i + 2) == N ? 1 : i + 2] - points[i]) > EPS) != first_turn) return false; } return true; } int inside_polygon(const point2d& p, const double EPS = 1e-9) { // 1 inside // 0 on polygon // -1 outside int N = static_cast<int>(points.size()); if (N <= 3) return -1; bool on_polygon = false; for (int i = 0; i < N - 1; ++i) { if (fabs(abs(p - points[i]) + abs(p - points[i + 1]) - abs(points[i] - points[i + 1])) < EPS) { on_polygon = true; break; } } if (on_polygon) return 0; double sum = 0.0; for (int i = 0; i < N - 1; ++i) { if (cross(points[i] - p, points[i + 1] - p) > EPS) { sum += angle(points[i] - p, points[i + 1] - p); } else { sum -= angle(points[i] - p, points[i + 1] - p); } } return fabs(sum) > M_PI ? 1 : -1; } polygon2d cut_polygon(const point2d& A, const point2d& B, const double EPS = 1e-9) { polygon2d new_polygon; for (int i = 0; i < static_cast<int>(points.size()); ++i) { double left1 = cross(B - A, points[i] - A); double left2 = 0.0; if (i != static_cast<int>(points.size()) - 1) left2 = cross(B - A, points[i + 1] - A); if (left1 > -EPS) new_polygon.points.push_back( points[i]); // points[i] is on the left if (left1 * left2 < -EPS) new_polygon.points.push_back(line_intersetct_segment( points[i], points[i + 1], A, B)); // crosses line AB } if ((not new_polygon.points.empty()) and (abs(new_polygon.points.back() - new_polygon.points.front()) > EPS)) { new_polygon.points.push_back(new_polygon.points.front()); } return new_polygon; } polygon2d convex_hull_graham(const double EPS = 1e-9) { polygon2d hull; vector<point2d> P(points); int N = static_cast<int>(P.size()); if (N <= 3) { if (abs(P[0] - P[N - 1]) > EPS) P.push_back(P[0]); for (auto& p : P) hull.points.push_back(p); return hull; } // find lower corner int P0 = min_element(P.begin(), P.end(), [&](point2d a, point2d b) { if (fabs(a.y - b.y) > EPS) return a.y < b.y; return a.x < b.x; }) - P.begin(); swap(P[0], P[P0]); // sort by pivot point sort(++P.begin(), P.end(), [&](point2d a, point2d b) { return cross(a - P[0], b - P[0]) > EPS; }); // build hull hull.points.push_back(P[N - 1]); hull.points.push_back(P[0]); hull.points.push_back(P[1]); int i = 2; while (i < N) { int j = static_cast<int>(hull.points.size()) - 1; if (cross(hull.points[j] - hull.points[j - 1], P[i] - hull.points[j - 1]) > EPS) hull.points.push_back(P[i++]); else hull.points.pop_back(); } return hull; } polygon2d convex_hull_andrew(const double EPS = 1e-9) { vector<point2d> curr_points = points; int N = static_cast<int>(curr_points.size()); int k = 0; polygon2d hull; hull.points.reserve(2 * N); sort(curr_points.begin(), curr_points.end(), [&](point2d a, point2d b) { if (fabs(a.y - b.y) > EPS) return a.y < b.y; return a.x < b.x; }); // lower hull for (int i = 0; i < N; ++i) { while ((k >= 2) and (cross(hull.points[k - 1] - hull.points[k - 2], curr_points[i] - hull.points[k - 2]) < EPS)) --k; hull.points[k++] = curr_points[i]; } // upper hull for (int i = N - 2, t = k + 1; i >= 0; --i) { while ((k >= t) and (cross(hull.points[k - 1] - hull.points[k - 2], curr_points[i] - hull.points[k - 2]) < EPS)) --k; hull.points[k++] = curr_points[i]; } hull.points.resize(k); return hull; } polygon2d convex_hull(const double EPS = 1e-9) { return convex_hull_andrew(EPS); } polygon2d translate(const point2d& vec) { for (auto& p : points) { p += vec; } return *this; } polygon2d translate(double theta) { double rad = DEG_to_RAD(theta); for (auto& p : points) { double x = p.x; double y = p.y; p = point2d(x * cos(rad) - y * sin(rad), x * sin(rad) + y * cos(rad)); } return *this; } }; }; // namespace polygon int main() { return 0; }
32.44186
80
0.4681
[ "vector" ]
d3ecdfb4581185e54ccc147fe774b64cbbfdffe5
28,540
cpp
C++
src/libutil/argparse.cpp
gbansal2/oiio
6612857298968971eb41171148e76cf9f1aaf18e
[ "BSD-3-Clause" ]
null
null
null
src/libutil/argparse.cpp
gbansal2/oiio
6612857298968971eb41171148e76cf9f1aaf18e
[ "BSD-3-Clause" ]
null
null
null
src/libutil/argparse.cpp
gbansal2/oiio
6612857298968971eb41171148e76cf9f1aaf18e
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2008-present Contributors to the OpenImageIO project. // SPDX-License-Identifier: BSD-3-Clause // https://github.com/OpenImageIO/oiio/blob/master/LICENSE.md #include <cassert> #include <cctype> #include <cstdarg> #include <cstdlib> #include <cstring> #include <iostream> #include <iterator> #include <sstream> #include <string> #include <OpenImageIO/argparse.h> #include <OpenImageIO/dassert.h> #include <OpenImageIO/filesystem.h> #include <OpenImageIO/paramlist.h> #include <OpenImageIO/platform.h> #include <OpenImageIO/strutil.h> #include <OpenImageIO/sysutil.h> OIIO_NAMESPACE_BEGIN class ArgOption final : public ArgParse::Arg { public: typedef int (*callback_t)(int, const char**); ArgOption(ArgParse& ap, const char* argspec); ~ArgOption() {} int initialize(); int nargs() const { return m_count; } void nargs(int n); string_view metavar() const { return Strutil::join(m_prettyargs, " "); } void metavar(string_view name) { m_prettyargs = Strutil::splits(name); m_count = 0; nargs(int(m_prettyargs.size())); compute_prettyformat(); } const std::string& flag() const { return m_flag; } const std::string& name() const { return m_name; } const std::string& dest() const { return m_dest; } const std::string& argspec() const { return m_argspec; } const std::string& prettyformat() const { return m_prettyformat; } void compute_prettyformat() { m_prettyformat = flag(); if (m_prettyargs.size()) { m_prettyformat += " "; m_prettyformat += Strutil::join(m_prettyargs, " "); } } bool is_flag() const { return m_type == Flag; } bool is_reverse_flag() const { return m_type == ReverseFlag; } bool is_sublist() const { return m_type == Sublist; } bool is_regular() const { return m_type == Regular; } bool has_callback() const { return m_has_callback; } void add_parameter(int i, void* p); void set_parameter(int i, const char* argv); int invoke_callback(int argc, const char** argv) const { return m_callback ? m_callback(argc, argv) : 0; } void set_callback(callback_t cb) { m_callback = cb; } void found_on_command_line() { m_repetitions++; } int parsed_count() const { return m_repetitions; } void help(std::string h) { m_help = std::move(h); } const std::string& help() const { return m_help; } bool is_separator() const { return argspec() == "<SEPARATOR>"; } bool hidden() const { return m_hidden; } bool had_error() const { return m_error; } void had_error(bool e) { m_error = e; } ArgParse::ArgAction& action() { return m_action; } private: enum OptionType { None, Regular, Flag, ReverseFlag, Sublist }; std::string m_argspec; // original format string specification std::string m_prettyformat; // human readable format std::string m_flag; // just the -flag_foo part std::string m_name; // just the 'flat_foo' part std::string m_dest; // destination parameter name std::string m_code; // paramter types, eg "df" std::string m_help; OptionType m_type = None; int m_count = 0; // number of parameters std::vector<void*> m_param; // pointers to app data vars std::vector<TypeDesc> m_paramtypes; // Expected param types std::vector<std::string> m_prettyargs; ArgParse::ArgAction m_action = nullptr; callback_t m_callback = nullptr; int m_repetitions = 0; // number of times on cmd line bool m_has_callback = false; // needs a callback? bool m_hidden = false; // hidden? bool m_error = false; // invalid option, had an error friend class ArgParse; friend class ArgParse::Arg; friend class ArgParse::Impl; }; class ArgParse::Impl { public: ArgParse& m_argparse; int m_argc; // a copy of the command line argc const char** m_argv; // a copy of the command line argv mutable std::string m_errmessage; // error message ArgOption* m_global = nullptr; // option for extra cmd line arguments ArgOption* m_preoption = nullptr; // pre-switch cmd line arguments std::string m_intro; std::string m_usage; std::string m_description; std::string m_epilog; std::string m_prog; bool m_print_defaults = false; bool m_add_help = true; bool m_exit_on_error = true; std::vector<std::unique_ptr<ArgOption>> m_option; callback_t m_preoption_help = [](const ArgParse&, std::ostream&) {}; callback_t m_postoption_help = [](const ArgParse&, std::ostream&) {}; ParamValueList m_params; Impl(ArgParse& parent, int argc, const char** argv) : m_argparse(parent) , m_argc(argc) , m_argv(argv) , m_prog(Filesystem::filename(Sysutil::this_program_path())) { } int parse_args(int argc, const char** argv); ArgOption* find_option(const char* name); int found(const char* option); // number of times option was parsed // Error with std::fmt-like formatting template<typename... Args> void errorfmt(const char* fmt, const Args&... args) const { m_errmessage = Strutil::fmt::format(fmt, args...); } // Error with printf-like formatting template<typename... Args> void errorf(const char* fmt, const Args&... args) const { m_errmessage = Strutil::sprintf(fmt, args...); } }; // Constructor. Does not do any parsing or error checking. // Make sure to call initialize() right after construction. // The format may look like this: "%g:FOO", and in that case split // the formatting part (e.g. "%g") from the self-documenting // human-readable argument name ("FOO") ArgOption::ArgOption(ArgParse& ap, const char* argspec) : ArgParse::Arg(ap) { std::vector<std::string> uglyargs; auto args = Strutil::splits(argspec, " "); int i = 0; for (auto&& a : args) { if (i == 0) m_flag = a; auto parts = Strutil::splitsv(a, ":", 2); string_view ug = a, pr = a; if (parts.size() == 2) { ug = parts[0]; pr = parts[1]; } if (i && parts.size() == 1 && ug.size() && ug[0] != '%') ug = "%s"; // If no type spec, just assume string uglyargs.push_back(ug); if (pr == "%L") pr = "%s"; if (pr != "%!" && pr != "%@") if (i) m_prettyargs.push_back(pr); ++i; } m_argspec = Strutil::join(uglyargs, " "); compute_prettyformat(); } // Parses the format string ("-option %s %d %f") to extract the // flag ("-option") and create a code string ("sdf"). After the // code string is created, the param list of void* pointers is // allocated to hold the argument variable pointers. int ArgOption::initialize() { size_t n; const char* s; if (m_argspec.empty() || m_argspec == "%*") { m_type = Sublist; m_count = 1; // sublist callback function pointer m_code = "*"; m_flag = ""; } else if (m_argspec == "%1") { m_type = Sublist; m_count = 1; // sublist callback function pointer m_code = "*"; m_flag = ""; } else if (is_separator()) { } else if (m_argspec[0] != '-') { m_type = Sublist; m_count = 1; // sublist callback function pointer m_code = "*"; m_flag = ""; } else { // extract the flag name s = &m_argspec[0]; assert(*s == '-'); assert(isalpha(s[1]) || (s[1] == '-' && isalpha(s[2]))); s++; if (*s == '-') s++; while (isalnum(*s) || *s == '_' || *s == '-') s++; if (!*s) { m_flag = m_argspec; m_type = Flag; m_count = 1; m_code = "b"; } else { n = s - (&m_argspec[0]); m_flag.assign(m_argspec.begin(), m_argspec.begin() + n); // Parse the scanf-like parameters m_type = Regular; m_code.clear(); while (*s != '\0') { if (*s == '%') { s++; assert(*s != '\0'); m_count++; // adding another parameter switch (*s) { case 'd': // 32bit int case 'g': // float case 'f': // float case 'F': // double case 's': // string case 'L': // vector<string> assert(m_type == Regular); m_code += *s; break; case '!': m_type = ReverseFlag; m_code += *s; break; case '*': assert(m_count == 1); m_type = Sublist; break; case '1': assert(m_count == 1); m_type = Sublist; break; case '@': m_has_callback = true; --m_count; break; default: std::cerr << "Programmer error: Unknown option "; std::cerr << "type string \"" << *s << "\"" << "\n"; abort(); } } s++; } // Catch the case where only a callback was given, it's still // a bool. if (!*s && m_count == 0 && m_has_callback) { m_type = Flag; m_count = 1; m_code = "b"; } } } if (m_argspec[0] == '-') m_name = Strutil::lstrip(m_flag, "-"); else m_name = m_argspec; m_dest = m_name; // Allocate space for the parameter pointers and initialize to NULL m_param.resize(m_count, nullptr); m_paramtypes.resize(m_count, TypeUnknown); return 0; } // Allocate space for the parameter pointers and initialize to NULL void ArgOption::nargs(int n) { if (n == m_count) return; m_param.resize(n, nullptr); m_paramtypes.resize(n, TypeUnknown); m_prettyargs.resize(n, Strutil::upper(m_name)); compute_prettyformat(); for (int i = m_count; i < n; ++i) m_argspec += Strutil::concat(" %s:", m_prettyargs[i]); initialize(); m_count = n; } // Stores the pointer to an argument in the param list and // initializes flag options to FALSE. // FIXME -- there is no such initialization. Bug? void ArgOption::add_parameter(int i, void* p) { assert(i >= 0 && i < m_count); m_param[i] = p; m_paramtypes[i] = TypeUnknown; } // Given a string from argv, set the associated option parameter // at index i using the format conversion code in the code string. void ArgOption::set_parameter(int i, const char* argv) { assert(i < m_count); if (!m_param[i]) // If they passed NULL as the address, return; // don't write anything. switch (m_code[i]) { case 'd': *(int*)m_param[i] = Strutil::stoi(argv); break; case 'f': case 'g': *(float*)m_param[i] = Strutil::stof(argv); break; case 'F': *(double*)m_param[i] = Strutil::stod(argv); break; case 's': *(std::string*)m_param[i] = argv; break; case 'S': *(std::string*)m_param[i] = argv; break; case 'L': ((std::vector<std::string>*)m_param[i])->push_back(argv); break; case 'b': *(bool*)m_param[i] = true; break; case '!': *(bool*)m_param[i] = false; break; case '*': default: abort(); } } ArgParse::ArgParse() : m_impl(new Impl(*this, 0, nullptr)) { } ArgParse::ArgParse(int argc, const char** argv) : m_impl(new Impl(*this, argc, argv)) { } ArgParse::~ArgParse() {} // Top level command line parsing function called after all options // have been parsed and created from the format strings. This function // parses the command line (argc,argv) stored internally in the constructor. // Each command line argument is parsed and checked to see if it matches an // existing option. If there is no match, and error is reported and the // function returns early. If there is a match, all the arguments for // that option are parsed and the associated variables are set. int ArgParse::parse_args(int xargc, const char** xargv) { int r = m_impl->parse_args(xargc, xargv); if (r < 0 && m_impl->m_exit_on_error) { Sysutil::Term term(std::cerr); std::cerr << term.ansi("red") << prog_name() << " error: " << geterror() << term.ansi("default") << std::endl; print_help(); exit(EXIT_FAILURE); } return r; } int ArgParse::Impl::parse_args(int xargc, const char** xargv) { m_argc = xargc; m_argv = xargv; // Add help option if requested if (m_add_help && !find_option("--help")) { m_option.emplace(m_option.begin(), new ArgOption(m_argparse, "--help")); // m_option[0]->m_type = ArgOption::Flag; m_option[0]->m_help = "Print help message"; m_option[0]->m_action = [&](Arg& arg, cspan<const char*> myarg) { this->m_argparse.print_help(); exit(EXIT_SUCCESS); }; m_option[0]->initialize(); } bool any_option_encountered = false; for (int i = 1; i < m_argc; i++) { if (m_argv[i][0] == '-' && (isalpha(m_argv[i][1]) || m_argv[i][1] == '-')) { // flag any_option_encountered = true; // Look up only the part before a ':' std::string argname = m_argv[i]; size_t colon = argname.find_first_of(':'); if (colon != std::string::npos) argname.erase(colon, std::string::npos); ArgOption* option = find_option(argname.c_str()); if (!option) { errorf("Invalid option \"%s\"", m_argv[i]); return -1; } option->found_on_command_line(); if (option->is_flag() || option->is_reverse_flag()) { option->set_parameter(0, nullptr); if (option->has_callback()) option->invoke_callback(1, m_argv + i); if (option->m_action) { option->m_action(*option, { m_argv + i, 1 }); } else { m_params[option->dest()] = option->is_flag() ? 1 : 0; } // else } else { assert(option->is_regular()); int n = option->nargs(); assert(n >= 1); for (int j = 0; j < n; j++) { if (j + i + 1 >= m_argc) { errorf("Missing parameter %d from option \"%s\"", j + 1, option->flag()); return -1; } option->set_parameter(j, m_argv[i + j + 1]); } if (option->has_callback()) option->invoke_callback(1 + n, m_argv + i); if (option->m_action) { option->m_action(*option, { m_argv + i, n + 1 }); } else { m_params[option->dest()] = m_argv[i + 1]; } i += n; } } else { // not an option nor an option parameter, glob onto global list, // or the preoption list if a preoption callback was given and // we haven't encountered any options yet. if (m_preoption && !any_option_encountered) if (m_preoption->m_action) m_preoption->m_action(*m_preoption, { m_argv + i, 1 }); else m_preoption->invoke_callback(1, m_argv + i); else if (m_global) { if (m_global->m_action) m_global->m_action(*m_global, { m_argv + i, 1 }); else m_global->invoke_callback(1, m_argv + i); } else { errorf("Argument \"%s\" does not have an associated option", m_argv[i]); return -1; } } } return 0; } // Primary entry point. This function accepts a set of format strings // and variable pointers. Each string contains an option name and a // scanf-like format string to enumerate the arguments of that option // (eg. "-option %d %f %s"). The format string is followed by a list // of pointers to the argument variables, just like scanf. All format // strings and arguments are parsed to create a list of ArgOption objects. // After all ArgOptions are created, the command line is parsed and // the sublist option callbacks are invoked. int ArgParse::options(const char* intro, ...) { va_list ap; va_start(ap, intro); m_impl->m_description += intro; for (const char* cur = va_arg(ap, char*); cur; cur = va_arg(ap, char*)) { if (m_impl->find_option(cur) && strcmp(cur, "<SEPARATOR>")) { m_impl->errorf("Option \"%s\" is multiply defined", cur); return -1; } // Build a new option and then parse the values std::unique_ptr<ArgOption> option(new ArgOption(*this, cur)); if (option->initialize() < 0) { return -1; } if (cur[0] == '\0' || (cur[0] == '%' && cur[1] == '*' && cur[2] == '\0')) { // set default global option m_impl->m_global = option.get(); } if (cur[0] == '%' && cur[1] == '1' && cur[2] == '\0') { // set default pre-switch option m_impl->m_preoption = option.get(); } if (option->has_callback()) option->set_callback((ArgOption::callback_t)va_arg(ap, void*)); // Grab any parameters and store them with this option for (int i = 0; i < option->nargs(); i++) { void* p = va_arg(ap, void*); option->add_parameter(i, p); if (option.get() == m_impl->m_global || option.get() == m_impl->m_preoption) option->set_callback((ArgOption::callback_t)p); } // Last argument is description option->help((const char*)va_arg(ap, const char*)); if (option->help().empty()) option->hidden(); m_impl->m_option.emplace_back(std::move(option)); } va_end(ap); return 0; } string_view ArgParse::Arg::name() const { return static_cast<const ArgOption*>(this)->name(); } string_view ArgParse::Arg::dest() const { return static_cast<const ArgOption*>(this)->dest(); } ParamValueList& ArgParse::params() { return m_impl->m_params; } const ParamValueList& ArgParse::cparams() const { return m_impl->m_params; } ArgParse::Arg& ArgParse::add_argument(const char* argname) { // Build a new option and then parse the values auto option = new ArgOption(*this, argname); m_impl->m_option.emplace_back(option); option->m_param.resize(option->nargs(), nullptr); option->m_paramtypes.resize(option->nargs(), TypeUnknown); if (option->initialize() < 0) { option->had_error(true); return *static_cast<Arg*>(m_impl->m_option.back().get()); } if (argname[0] == '\0' || (argname[0] == '%' && argname[1] == '*' && argname[2] == '\0')) { // set default global option m_impl->m_global = option; } else if (argname[0] == '%' && argname[1] == '1' && argname[2] == '\0') { // set default pre-switch option m_impl->m_preoption = option; } else if (argname[0] != '-' && argname[0] != '<') { // set default global option m_impl->m_global = option; } return *static_cast<Arg*>(m_impl->m_option.back().get()); } ArgParse::Arg& ArgParse::argx(const char* argname, ...) { va_list ap; va_start(ap, argname); // Build a new option and then parse the values std::unique_ptr<ArgOption> option(new ArgOption(*this, argname)); if (option->initialize() < 0) { option->had_error(true); m_impl->m_option.emplace_back(std::move(option)); va_end(ap); return *static_cast<Arg*>(m_impl->m_option.back().get()); } if (argname[0] == '\0' || (argname[0] == '%' && argname[1] == '*' && argname[2] == '\0')) { // set default global option m_impl->m_global = option.get(); } if (argname[0] == '%' && argname[1] == '1' && argname[2] == '\0') { // set default pre-switch option m_impl->m_preoption = option.get(); } if (option->has_callback()) option->set_callback((ArgOption::callback_t)va_arg(ap, void*)); // Grab any parameters and store them with this option for (int i = 0; i < option->nargs(); i++) { void* p = va_arg(ap, void*); option->add_parameter(i, p); if (option.get() == m_impl->m_global || option.get() == m_impl->m_preoption) option->set_callback((ArgOption::callback_t)p); } m_impl->m_option.emplace_back(std::move(option)); va_end(ap); return *static_cast<Arg*>(m_impl->m_option.back().get()); } ArgParse::Arg& ArgParse::separator(string_view text) { return arg("<SEPARATOR>").help(text); } ArgParse::Arg& ArgParse::Arg::help(string_view help) { static_cast<ArgOption*>(this)->help(help); return *this; } ArgParse::Arg& ArgParse::Arg::nargs(int n) { static_cast<ArgOption*>(this)->nargs(n); return *this; } ArgParse::Arg& ArgParse::Arg::metavar(string_view name) { static_cast<ArgOption*>(this)->metavar(name); return *this; } ArgParse::Arg& ArgParse::Arg::action(ArgAction&& action) { static_cast<ArgOption*>(this)->m_action = std::move(action); return *this; } ArgParse::Arg& ArgParse::Arg::dest(string_view dest) { static_cast<ArgOption*>(this)->m_dest = dest; return *this; } ArgParse::Arg& ArgParse::Arg::hidden() { static_cast<ArgOption*>(this)->m_hidden = true; return *this; } ArgParse::Action ArgParse::do_nothing() { return [](cspan<const char*> myarg) { return true; }; } ArgParse::ArgAction ArgParse::store_true() { return [](Arg& arg, cspan<const char*> myarg) { arg.argparse().params()[arg.dest()] = 1; }; } ArgParse::ArgAction ArgParse::store_false() { return [](Arg& arg, cspan<const char*> myarg) { arg.argparse().params()[arg.dest()] = 0; }; } // Find an option by name in the option vector ArgOption* ArgParse::Impl::find_option(const char* name) { for (auto&& opt : m_option) { const char* optname = opt->flag().c_str(); if (!strcmp(name, optname)) return opt.get(); // Match even if the user mixes up one dash or two if (name[0] == '-' && name[1] == '-' && optname[0] == '-' && optname[1] != '-') if (!strcmp(name + 1, optname)) return opt.get(); if (name[0] == '-' && name[1] != '-' && optname[0] == '-' && optname[1] == '-') if (!strcmp(name, optname + 1)) return opt.get(); } return nullptr; } ArgParse& ArgParse::intro(string_view str) { m_impl->m_intro = str; return *this; } ArgParse& ArgParse::usage(string_view str) { m_impl->m_usage = str; return *this; } ArgParse& ArgParse::description(string_view str) { m_impl->m_description = str; return *this; } ArgParse& ArgParse::epilog(string_view str) { m_impl->m_epilog = str; return *this; } ArgParse& ArgParse::prog(string_view str) { m_impl->m_prog = str; return *this; } ArgParse& ArgParse::print_defaults(bool print) { m_impl->m_print_defaults = print; return *this; } ArgParse& ArgParse::add_help(bool add_help) { m_impl->m_add_help = add_help; return *this; } ArgParse& ArgParse::exit_on_error(bool exit_on_error) { m_impl->m_exit_on_error = exit_on_error; return *this; } int ArgParse::Impl::found(const char* option_name) { ArgOption* option = find_option(option_name); return option ? option->parsed_count() : 0; } std::string ArgParse::geterror() const { std::string e = m_impl->m_errmessage; m_impl->m_errmessage.clear(); return e; } static void println(std::ostream& out, string_view str, int blanklines = 1) { if (str.size()) { out << str; if (str.back() != '\n') out << '\n'; while (blanklines-- > 0) out << '\n'; } } std::string ArgParse::prog_name() const { return m_impl->m_prog; } void ArgParse::print_help() const { const size_t longline = 35; println(std::cout, m_impl->m_intro); if (m_impl->m_usage.size()) { std::cout << "Usage: "; println(std::cout, m_impl->m_usage); } println(std::cout, m_impl->m_description); m_impl->m_preoption_help(*this, std::cout); size_t maxlen = 0; for (auto&& opt : m_impl->m_option) { size_t fmtlen = opt->prettyformat().length(); // Option lists > 40 chars will be split into multiple lines if (fmtlen < longline) maxlen = std::max(maxlen, fmtlen); } // Try to figure out how wide the terminal is, so we can word wrap. int columns = Sysutil::terminal_columns(); for (auto&& opt : m_impl->m_option) { if (!opt->hidden() /*opt->help().length()*/) { size_t fmtlen = opt->prettyformat().length(); if (opt->is_separator()) { std::cout << Strutil::wordwrap(opt->help(), columns - 2, 0) << '\n'; } else { std::cout << " " << opt->prettyformat(); if (fmtlen < longline) std::cout << std::string(maxlen + 2 - fmtlen, ' '); else std::cout << "\n " << std::string(maxlen + 2, ' '); std::string h = opt->help(); if (m_impl->m_print_defaults && cparams().contains(opt->dest())) h += Strutil::sprintf(" (default: %s)", cparams()[opt->dest()].get()); std::cout << Strutil::wordwrap(h, columns - 2, (int)maxlen + 2 + 4 + 2); std::cout << '\n'; } } } m_impl->m_postoption_help(*this, std::cout); println(std::cout, m_impl->m_epilog, 0); } void ArgParse::briefusage() const { println(std::cout, m_impl->m_intro); if (m_impl->m_usage.size()) { std::cout << "Usage: "; println(std::cout, m_impl->m_usage); } // Try to figure out how wide the terminal is, so we can word wrap. int columns = Sysutil::terminal_columns(); std::string pending; for (auto&& opt : m_impl->m_option) { if (!opt->hidden() /*opt->help().length()*/) { if (opt->is_separator()) { if (pending.size()) std::cout << " " << Strutil::wordwrap(pending, columns - 2, 4) << '\n'; pending.clear(); std::cout << Strutil::wordwrap(opt->help(), columns - 2, 0) << '\n'; } else { pending += opt->flag() + " "; } } } if (pending.size()) std::cout << " " << Strutil::wordwrap(pending, columns - 2, 4) << '\n'; } std::string ArgParse::command_line() const { std::string s; for (int i = 0; i < m_impl->m_argc; ++i) { if (strchr(m_impl->m_argv[i], ' ')) { s += '\"'; s += m_impl->m_argv[i]; s += '\"'; } else { s += m_impl->m_argv[i]; } if (i < m_impl->m_argc - 1) s += ' '; } return s; } void ArgParse::set_preoption_help(callback_t callback) { m_impl->m_preoption_help = callback; } void ArgParse::set_postoption_help(callback_t callback) { m_impl->m_postoption_help = callback; } OIIO_NAMESPACE_END
27.129278
80
0.540084
[ "vector" ]
d3ee2da1ea927dcdfa4866a3c797917c1bdfda2e
1,446
cpp
C++
epikjjh/baekjoon/2213.cpp
15ers/Solve_Naively
23ee4a3aedbedb65b9040594b8c9c6d9cff77090
[ "MIT" ]
3
2019-05-19T13:44:39.000Z
2019-07-03T11:15:20.000Z
epikjjh/baekjoon/2213.cpp
15ers/Solve_Naively
23ee4a3aedbedb65b9040594b8c9c6d9cff77090
[ "MIT" ]
7
2019-05-06T02:37:26.000Z
2019-06-29T07:28:02.000Z
epikjjh/baekjoon/2213.cpp
15ers/Solve_Naively
23ee4a3aedbedb65b9040594b8c9c6d9cff77090
[ "MIT" ]
1
2019-07-28T06:24:54.000Z
2019-07-28T06:24:54.000Z
#include <bits/stdc++.h> using namespace std; vector<vector<int>> adj; vector<vector<int>> tree; vector<int> score; vector<int> cands; vector<bool> visited; int dp[10001][2]; void make_tree(int cur){ visited[cur] = true; for(int nxt: adj[cur]){ if(visited[nxt]) continue; tree[cur].push_back(nxt); make_tree(nxt); } } int dfs(int cur, int ispick){ int &ret = dp[cur][ispick]; if(ret!=-1) return ret; ret = ispick ? score[cur] : 0; for(int nxt: tree[cur]){ if(ispick) ret += dfs(nxt,0); else ret += max(dfs(nxt,0),dfs(nxt,1)); } return ret; } void trace(int cur, int ispick){ if(ispick) cands.push_back(cur); for(int nxt: tree[cur]){ if(ispick) trace(nxt,0); else{ if(dp[nxt][0]>=dp[nxt][1]) trace(nxt,0); else trace(nxt,1); } } } int main(){ memset(dp,-1,sizeof(dp)); int n; scanf("%d",&n); adj.resize(n+1); tree.resize(n+1); score.resize(n+1); visited.resize(n+1); for(int i=1;i<=n;i++) scanf("%d",&score[i]); for(int i=1;i<n;i++){ int u,v; scanf("%d %d",&u,&v); adj[u].push_back(v); adj[v].push_back(u); } make_tree(1); tree[0].push_back(1); printf("%d\n",dfs(0,0)); trace(0,0); sort(cands.begin(),cands.end()); for(int &e: cands) printf("%d ",e); printf("\n"); return 0; }
20.657143
54
0.517289
[ "vector" ]
d3f042a6f7b3ab5f1a8de882b876afa12efec693
2,863
hh
C++
src/c++/include/alignment/templateBuilder/FragmentSequencingAdapterClipper.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
13
2018-02-09T22:59:39.000Z
2021-11-29T06:33:22.000Z
src/c++/include/alignment/templateBuilder/FragmentSequencingAdapterClipper.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
17
2018-01-26T11:36:07.000Z
2022-02-03T18:48:43.000Z
src/c++/include/alignment/templateBuilder/FragmentSequencingAdapterClipper.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
4
2018-10-19T20:00:00.000Z
2020-10-29T14:44:06.000Z
/** ** Isaac Genome Alignment Software ** Copyright (c) 2010-2017 Illumina, Inc. ** All rights reserved. ** ** This software is provided under the terms and conditions of the ** GNU GENERAL PUBLIC LICENSE Version 3 ** ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3 ** along with this program. If not, see ** <https://github.com/illumina/licenses/>. ** ** \file FragmentSequencingAdapterClipper.hh ** ** \brief Utility classes for detecting and removing fragment parts that contain ** sequences of the adapters ** ** \author Roman Petrovski **/ #ifndef iSAAC_ALIGNMENT_FRAGMENT_SEQUENCING_ADAPTER_CLIPPER_HH #define iSAAC_ALIGNMENT_FRAGMENT_SEQUENCING_ADAPTER_CLIPPER_HH #include "alignment/SequencingAdapter.hh" #include "alignment/FragmentMetadata.hh" #include "reference/Contig.hh" namespace isaac { namespace alignment { namespace templateBuilder { class FragmentSequencingAdapterClipper: public boost::noncopyable { // percent of mismatching bases below which the flank is assumed // to be too good for the real adapter-containing read. static const unsigned TOO_GOOD_READ_MISMATCH_PERCENT = 40; const SequencingAdapterList &sequencingAdapters_; public: explicit FragmentSequencingAdapterClipper( const SequencingAdapterList &sequencingAdapters): sequencingAdapters_(sequencingAdapters) { } void checkInitStrand( const FragmentMetadata &fragmentMetadata, const reference::Contig &contig); void clip( const reference::Contig &contig, FragmentMetadata &fragment, std::vector<char>::const_iterator &sequenceBegin, std::vector<char>::const_iterator &sequenceEnd) const; private: struct SequencingAdapterRange { SequencingAdapterRange() : initialized_(false), empty_(true), unbounded_(false){} bool initialized_; bool empty_; bool unbounded_; std::vector<char>::const_iterator adapterRangeBegin_; std::vector<char>::const_iterator adapterRangeEnd_; }; struct StrandSequencingAdapterRange { // 0 - forward range, 1 - reverse range templateBuilder::FragmentSequencingAdapterClipper::SequencingAdapterRange strandRange_[2]; }; static const unsigned READS_MAX = 2; StrandSequencingAdapterRange readAdapters_[READS_MAX]; static bool decideWhichSideToClip( const reference::Contig &contig, const int64_t contigPosition, const std::vector<char>::const_iterator sequenceBegin, const std::vector<char>::const_iterator sequenceEnd, const SequencingAdapterRange &adapterRange, bool &clipBackwards); }; } // namespace templateBuilder } // namespace alignment } // namespace isaac #endif // #ifndef iSAAC_ALIGNMENT_FRAGMENT_SEQUENCING_ADAPTER_CLIPPER_HH
30.784946
98
0.729305
[ "vector" ]
1094f74bc956b861870d4a6f7255a92380d55ae3
28,900
cpp
C++
src/kmrandgen.cpp
MarcAntoine-Arnaud/asdcplib
067c114b37e5bbc4ba8ff456de3b981beef2dcf9
[ "OpenSSL" ]
6
2015-12-06T10:21:11.000Z
2019-10-27T01:13:01.000Z
src/kmrandgen.cpp
MarcAntoine-Arnaud/asdcplib
067c114b37e5bbc4ba8ff456de3b981beef2dcf9
[ "OpenSSL" ]
6
2018-05-31T05:29:28.000Z
2021-01-13T07:32:52.000Z
src/kmrandgen.cpp
MarcAntoine-Arnaud/asdcplib
067c114b37e5bbc4ba8ff456de3b981beef2dcf9
[ "OpenSSL" ]
5
2015-10-08T14:25:19.000Z
2022-01-27T06:09:52.000Z
/* Copyright (c) 2005-2009, John Hurst All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*! \file kmrandgen.cpp \version $Id: kmrandgen.cpp,v 1.10 2017/11/10 19:25:12 jhurst Exp $ \brief psuedo-random number generation utility */ #include "AS_DCP.h" #include <KM_fileio.h> #include <KM_prng.h> #include <ctype.h> using namespace Kumu; const ui32_t RandBlockSize = 16; const char* PROGRAM_NAME = "kmrandgen"; // Increment the iterator, test for an additional non-option command line argument. // Causes the caller to return if there are no remaining arguments or if the next // argument begins with '-'. #define TEST_EXTRA_ARG(i,c) if ( ++i >= argc || argv[(i)][0] == '-' ) \ { \ fprintf(stderr, "Argument not found for option -%c.\n", (c)); \ return; \ } static const char* _letterwords_list[] = { "Alfa", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", "Whiskey", "X-ray", "Yankee", "Zulu" }; static const char* _word_list[] = { "ABED", "ABET", "ABEY", "ABLE", "ABUT", "ACE", "ACHE", "ACID", "ACME", "ACRE", "ACT", "ACTS", "ADD", "ADDS", "ADO", "ADRY", "AEON", "AERO", "AFAR", "AFRO", "AGAR", "AGE", "AGED", "AGIO", "AGO" , "AHEM", "AHOY", "AID", "AIDE", "AIL", "AIM", "AIR", "AIRY", "AJAR", "AKIN", "ALAS", "ALCO", "ALE", "ALF", "ALFA", "ALL" , "ALLY", "ALMA", "ALMS", "ALOE", "ALOW", "ALSO", "ALT", "ALTO", "ALUM", "AM", "AMES", "AMID", "AN", "AND", "ANEW", "ANT" , "ANTE", "ANY", "APE", "APEX", "APT", "AQUA", "ARC", "ARCH", "ARE", "AREA", "ARGO", "ARID", "ARK", "ARM", "ARMS", "ART" , "ARTS", "ARTY", "AS", "ASH", "ASK", "ASKS", "ASP", "AT" , "ATE", "ATOM", "ATOP", "AUNT", "AURA", "AUTO", "AVER", "AVID", "AVOW", "AWAY", "AWE", "AWL", "AXE", "AXED", "AXES", "AXIS", "AXLE", "AXON", "AYE", "BABE", "BABU", "BABY", "BACK", "BAD" , "BADE", "BAG", "BAIL", "BAIT", "BAKE", "BALD", "BALE", "BALK", "BALL", "BALM", "BAM", "BAN", "BAND", "BANE", "BANG", "BANK", "BAR", "BARB", "BARD", "BARE", "BARK", "BARM", "BARN", "BARU", "BASE", "BASH", "BASK", "BASS", "BAT", "BATH", "BATS", "BAWL", "BAY", "BE", "BEAD", "BEAK", "BEAM", "BEAN", "BEAR", "BEAT", "BEAU", "BECK", "BED", "BEE", "BEEF", "BEEK", "BEEN", "BEER", "BEES", "BEET", "BEG", "BELL", "BELT", "BEND", "BENT", "BERG", "BERM", "BEST", "BET", "BETA", "BIAS", "BIB", "BID", "BIDE", "BIER", "BIG", "BIKE", "BILE", "BILK", "BILL", "BIN", "BIND", "BING", "BIOS", "BIRD", "BIT", "BITE", "BITS", "BIZ", "BLAB", "BLED", "BLOB", "BLOC", "BLOK", "BLOT", "BLUE", "BLUR", "BOA" , "BOAR", "BOAT", "BOB", "BOCE", "BOCK", "BODE", "BODY", "BOG" , "BOIL", "BOLD", "BOLO", "BOLT", "BOND", "BONE", "BONY", "BOO" , "BOOK", "BOOL", "BOOM", "BOON", "BOOR", "BOOT", "BORE", "BORG", "BORN", "BOSS", "BOTH", "BOUT", "BOW", "BOWL", "BOXY", "BOY" , "BRAG", "BRAN", "BRAT", "BRAY", "BRED", "BREW", "BRIE", "BRIG", "BRIM", "BRIT", "BROW", "BUCK", "BUD", "BUFF", "BUG", "BULB", "BULK", "BULL", "BUMP", "BUN", "BUNK", "BUNT", "BUOY", "BUR" , "BURG", "BURL", "BURN", "BURP", "BURR", "BURY", "BUS", "BUSH", "BUSK", "BUSS", "BUSY", "BUT", "BUY", "BY", "BYE", "BYTE", "CAB", "CAD", "CAFE", "CAGE", "CAIN", "CAKE", "CAL", "CALF", "CALL", "CALM", "CAM", "CAMP", "CAN", "CANE", "CANT", "CAP" , "CAPE", "CAR", "CARD", "CARE", "CARP", "CART", "CASE", "CASH", "CASK", "CAST", "CAT", "CAVE", "CEDE", "CEIL", "CELL", "CENT", "CHAP", "CHAT", "CHEF", "CHEW", "CHIC", "CHIN", "CHIP", "CHIT", "CHOP", "CHOW", "CHUG", "CHUM", "CINE", "CITE", "CITY", "CLAD", "CLAM", "CLAN", "CLAP", "CLAW", "CLAY", "CLEF", "CLIP", "CLOD", "CLOG", "CLOT", "CLOY", "CLUB", "CLUE", "COAL", "COAT", "COAX", "COB", "COD", "CODA", "CODE", "COG", "COIL", "COIN", "COKE", "COLA", "COLD", "COLE", "COLT", "COMB", "COOK", "COOL", "COP" , "COPE", "COPY", "CORD", "CORE", "CORK", "CORN", "CORP", "COST", "COSY", "COT", "COUP", "COVE", "COW", "COWL", "COY", "COZY", "CRAB", "CRAG", "CRAM", "CRAW", "CRAY", "CREW", "CRIB", "CROC", "CROP", "CROW", "CRUX", "CRY", "CUB", "CUBE", "CUE", "CUFF", "CUP", "CUR", "CURB", "CURD", "CURE", "CURL", "CURT", "CUT" , "CUTE", "CYAN", "CYST", "CZAR", "DAB", "DAD", "DADA", "DADO", "DAIS", "DALE", "DALI", "DAM", "DAME", "DAMP", "DARE", "DARK", "DARN", "DART", "DASH", "DATA", "DATE", "DAUB", "DAWN", "DAY" , "DAYS", "DAZE", "DAZY", "DEAL", "DEAR", "DEBT", "DECK", "DEED", "DEEM", "DEER", "DEFT", "DEFY", "DELI", "DELL", "DEMO", "DEN" , "DENT", "DENY", "DESK", "DEW", "DIAL", "DIBS", "DICE", "DID" , "DIG", "DIGS", "DILL", "DIM", "DIME", "DIN", "DINE", "DIP" , "DIRE", "DIRT", "DISC", "DISH", "DISK", "DIVE", "DO", "DOCK", "DOE", "DOES", "DOG", "DOGS", "DOLE", "DOLL", "DOME", "DON" , "DONE", "DOOM", "DOOR", "DORM", "DOSE", "DOT", "DOTE", "DOUR", "DOVE", "DOWN", "DOZE", "DRAB", "DRAG", "DRAM", "DRAT", "DRAW", "DREW", "DRIB", "DRIP", "DROP", "DRUB", "DRUM", "DRY", "DUAL", "DUB", "DUBS", "DUCK", "DUCT", "DUD", "DUE", "DUET", "DUG" , "DUKE", "DULL", "DULY", "DUMP", "DUNE", "DUNK", "DUPE", "DUSK", "DUST", "DUTY", "DYAD", "EACH", "EAR", "EARL", "EARN", "EASE", "EAST", "EASY", "EAT", "EATS", "EBB", "ECHO", "EDDY", "EDGE", "EDGY", "EDIT", "EEL", "EGG", "EGO", "ELF", "ELK", "ELM" , "ELSE", "EMIT", "END", "ENDS", "ENSE", "ENVY", "EPIC", "ERA" , "ERG", "EVE", "EVEN", "EVER", "EWE", "EXAM", "EXIT", "EYE" , "EYED", "FACE", "FACT", "FAD", "FADE", "FADY", "FAIL", "FAIR", "FAKE", "FALL", "FAME", "FAN", "FANG", "FAR", "FARE", "FARM", "FAST", "FATE", "FAWN", "FAZE", "FEAR", "FEAT", "FED", "FEE" , "FEED", "FEEL", "FEET", "FELL", "FELT", "FEND", "FERN", "FEST", "FEUD", "FEW", "FEZ", "FIAT", "FIB", "FIFE", "FIG", "FIGS", "FILE", "FILL", "FILM", "FIN", "FIND", "FINE", "FINK", "FIR" , "FIRE", "FIRM", "FISH", "FIT", "FITS", "FIVE", "FIX", "FLAG", "FLAK", "FLAP", "FLAT", "FLAW", "FLAX", "FLED", "FLEE", "FLEW", "FLEX", "FLIP", "FLIT", "FLOE", "FLOG", "FLOP", "FLOW", "FLU" , "FLUB", "FLUE", "FLUX", "FLY", "FOAL", "FOAM", "FOE", "FOG" , "FOIL", "FOLD", "FOLK", "FOND", "FONT", "FOOD", "FOOL", "FOOT", "FORD", "FORE", "FORK", "FORM", "FORT", "FOUL", "FOUR", "FOW" , "FOWL", "FOX", "FRAY", "FRED", "FREE", "FRET", "FROG", "FROM", "FRY", "FUEL", "FUGU", "FULL", "FUME", "FUN", "FUND", "FUNK", "FUR", "FURY", "FUSE", "FUSS", "FUZZ", "GAB", "GAG", "GAGE", "GAIN", "GAIT", "GAL", "GALA", "GALE", "GALL", "GAME", "GAMY", "GANG", "GAP", "GARB", "GAS", "GASP", "GATE", "GAVE", "GAWK", "GAZE", "GEAR", "GEEK", "GEL", "GEM", "GENE", "GENT", "GERM", "GET", "GETS", "GIFT", "GIG", "GILD", "GILL", "GILT", "GIN" , "GIRD", "GIRL", "GIST", "GIT", "GIVE", "GLAD", "GLAM", "GLEE", "GLEN", "GLIB", "GLOB", "GLOM", "GLOP", "GLOW", "GLUE", "GLUG", "GLUM", "GLUT", "GNAT", "GNAW", "GNU", "GO", "GOAD", "GOAL", "GOAT", "GOB", "GOBO", "GOES", "GOLD", "GOLF", "GONE", "GONG", "GOO", "GOOD", "GOOF", "GOON", "GOSH", "GOT", "GOWN", "GRAB", "GRAD", "GRAM", "GRAY", "GREW", "GREY", "GRID", "GRIM", "GRIN", "GRIP", "GRIT", "GROG", "GROW", "GRUB", "GRUE", "GULF", "GULL", "GULP", "GUM", "GUNK", "GURU", "GUSH", "GUST", "GUT", "GUY" , "GYM", "HACK", "HAD", "HAH", "HAIL", "HAIR", "HALE", "HALF", "HALL", "HALO", "HALT", "HAM", "HAND", "HANG", "HANK", "HARD", "HARE", "HARK", "HARM", "HARP", "HAS", "HASH", "HASP", "HAT" , "HATH", "HAUL", "HAVE", "HAWK", "HAY", "HAZE", "HAZY", "HE" , "HEAL", "HEAP", "HEAR", "HEAT", "HECK", "HEED", "HEEL", "HEFT", "HEIR", "HELD", "HELM", "HELP", "HEM", "HEMP", "HEN", "HER" , "HERB", "HERD", "HERE", "HERO", "HERS", "HEW", "HEWN", "HEX" , "HEY", "HI", "HID", "HIDE", "HIGH", "HIKE", "HILL", "HILT", "HIM", "HIND", "HINT", "HIP", "HIRE", "HIS", "HISS", "HIT" , "HIVE", "HOAX", "HOCK", "HOE", "HOG", "HOLD", "HOLE", "HOME", "HONE", "HONK", "HOOD", "HOOF", "HOOK", "HOOP", "HOOT", "HOP" , "HOPE", "HORN", "HOSE", "HOST", "HOT", "HOUR", "HOW", "HOWL", "HUB", "HUE", "HUED", "HUFF", "HUG", "HUGE", "HUH", "HULK", "HULL", "HUM", "HUNK", "HUNT", "HURL", "HURT", "HUSH", "HUSK", "HUT", "HYMN", "HYPO", "ICE", "ICON", "ICY", "ID", "IDEA", "IDES", "IDLE", "IDLY", "IDOL", "IF", "IFFY", "ILK", "ILL" , "IMP", "IN", "INCH", "INDY", "INK", "INN", "INTO", "ION" , "IONS", "IOTA", "IRIS", "IRON", "IS", "ISLE", "IT", "ITEM", "IVY", "JADE", "JAG", "JAM", "JAR", "JAVA", "JAW", "JAZZ", "JEDI", "JEEP", "JEST", "JET", "JIB", "JIG", "JILT", "JIVE", "JOB", "JOBS", "JOG", "JOIN", "JOKE", "JOLT", "JOT", "JUDO", "JUG", "JULY", "JUMP", "JUNE", "JUNK", "JURY", "JUST", "JUT" , "KAHN", "KALE", "KANE", "KEEL", "KEEN", "KEEP", "KEG", "KELP", "KENO", "KEPT", "KERF", "KERN", "KEY", "KEYS", "KHAN", "KICK", "KID", "KILN", "KILO", "KILT", "KIN", "KIND", "KING", "KINO", "KIT", "KITE", "KNEE", "KNEW", "KNIT", "KNOT", "KNOW", "KOI" , "LAB", "LACE", "LACK", "LAD", "LADY", "LAG", "LAIR", "LAKE", "LAM", "LAMB", "LAME", "LAMP", "LAND", "LANE", "LAP", "LARD", "LARK", "LASH", "LASS", "LAST", "LATE", "LAUD", "LAVA", "LAW" , "LAWN", "LAWS", "LAX", "LAY", "LAZY", "LEAD", "LEAF", "LEAK", "LEAN", "LEAP", "LED", "LEDE", "LEED", "LEEK", "LEFT", "LEG" , "LEND", "LENS", "LENT", "LESS", "LEST", "LET", "LETS", "LIAR", "LID", "LIEN", "LIEU", "LIFE", "LIFO", "LIFT", "LIKE", "LILT", "LILY", "LIMA", "LIME", "LINE", "LINK", "LINT", "LION", "LIP" , "LIST", "LIT", "LIVE", "LOAD", "LOAF", "LOAN", "LOB", "LOBE", "LOCK", "LODE", "LOFT", "LOG", "LOGE", "LOIN", "LONE", "LONG", "LOOK", "LOON", "LOOP", "LOOT", "LORE", "LOSE", "LOSS", "LOST", "LOT", "LOTS", "LOUD", "LOVE", "LOW", "LOX", "LUCK", "LUG" , "LULL", "LUMP", "LUSH", "LUTE", "LUX", "LYE", "LYNX", "MAD" , "MADE", "MAID", "MAIL", "MAIN", "MAKE", "MALE", "MALL", "MALT", "MAN", "MANY", "MAP", "MARE", "MARK", "MART", "MASH", "MASK", "MASS", "MAST", "MAT", "MATE", "MATH", "MAUL", "MAW", "MAY" , "MAZE", "ME", "MEAD", "MEAL", "MEAN", "MEAT", "MEEK", "MEET", "MELD", "MELT", "MEME", "MEMO", "MEN", "MEND", "MENU", "MERE", "MESH", "MESS", "MET", "MICA", "MICE", "MID", "MIKE", "MILD", "MILE", "MILK", "MILL", "MIME", "MIND", "MINE", "MINK", "MINT", "MIRE", "MISS", "MIST", "MITE", "MITT", "MIX", "MOAT", "MOB" , "MOCK", "MOD", "MODE", "MOLD", "MOLE", "MOLT", "MONK", "MONO", "MOOD", "MOON", "MOOT", "MOP", "MOPE", "MORE", "MORN", "MOSS", "MOST", "MOTE", "MOTH", "MOVE", "MOW", "MOWN", "MUCH", "MUCK", "MUD", "MUG", "MULE", "MULL", "MULT", "MUM", "MUMP", "MURK", "MUSE", "MUSH", "MUSK", "MUSS", "MUST", "MUTE", "MUTT", "MY" , "MYTH", "NAB", "NAG", "NAIF", "NAIL", "NAME", "NAP", "NAPE", "NARY", "NEAR", "NEAT", "NEE", "NEED", "NEON", "NEST", "NET" , "NEW", "NEWS", "NEWT", "NEXT", "NIB", "NIBS", "NICE", "NICK", "NIL", "NINE", "NIX", "NO", "NOD", "NODE", "NONE", "NOOK", "NOON", "NOPE", "NOR", "NORI", "NORM", "NOSE", "NOSY", "NOT" , "NOTE", "NOUN", "NOVA", "NOW", "NULL", "NUMB", "NUN", "OAK" , "OAR", "OAT", "OATH", "OBOE", "ODD", "ODDS", "ODE", "OF" , "OFF", "OFT", "OGRE", "OH", "OHIO", "OHM", "OIL", "OILY", "OK", "OKAY", "OKRA", "OLD", "OMEN", "OMIT", "ON", "ONCE", "ONE", "ONES", "ONLY", "ONTO", "ONUS", "ONYX", "OPAL", "OPEN", "OPT", "OPUS", "OR", "ORB", "ORC", "ORE", "OUCH", "OUR" , "OURS", "OUST", "OUT", "OUTS", "OVAL", "OVEN", "OVER", "OWE" , "OWL", "OWN", "OWNS", "OX", "PACK", "PACT", "PAD", "PAGE", "PAIL", "PAIN", "PAIR", "PAL", "PALE", "PALL", "PALM", "PAN" , "PANE", "PAPA", "PAR", "PARK", "PART", "PASS", "PAST", "PAT" , "PATE", "PATH", "PAVE", "PAW", "PAWN", "PAX", "PAY", "PEA" , "PEAK", "PEAL", "PEAR", "PEAT", "PECK", "PEEL", "PEEN", "PEER", "PELT", "PEN", "PEND", "PENT", "PEP", "PER", "PERK", "PEST", "PET", "PEW", "PHI", "PI", "PICK", "PIE", "PIER", "PIG" , "PIKE", "PILE", "PILL", "PIN", "PINE", "PING", "PINT", "PIPE", "PIT", "PITY", "PLAN", "PLAY", "PLEA", "PLED", "PLOD", "PLOP", "PLOT", "PLOW", "PLOY", "PLUG", "PLUM", "PLUS", "PLY", "POD" , "POEM", "POET", "POKE", "POLE", "POLL", "POLO", "POMP", "POND", "PONY", "POOF", "POOL", "POOR", "POP", "PORE", "PORK", "PORT", "POSE", "POSH", "POST", "POT", "POUR", "POW", "POX", "POXY", "PRAM", "PRAT", "PRAY", "PREP", "PREY", "PRIG", "PRIM", "PROP", "PRY", "PUB", "PUCE", "PUCK", "PUFF", "PUG", "PULL", "PULP", "PUMP", "PUN", "PUNK", "PUNT", "PUNY", "PUP", "PURE", "PURR", "PUSH", "PUT", "PUTT", "QUAD", "QUIP", "QUIT", "QUIZ", "QUO" , "RACE", "RAFT", "RAID", "RAIL", "RAIN", "RAKE", "RAM", "RAMP", "RAN", "RANG", "RANK", "RAP", "RAPT", "RARE", "RASH", "RASP", "RAT", "RATE", "RATH", "RAVE", "RAW", "RAY", "RAZE", "RAZZ", "READ", "REAK", "REAL", "REAM", "REAP", "REAR", "RED", "REDO", "REED", "REEF", "REEL", "REIN", "REND", "RENT", "REST", "REV" , "RIB", "RICE", "RICH", "RICK", "RID", "RIDE", "RIFE", "RIFF", "RIFT", "RIG", "RILE", "RIM", "RIND", "RING", "RINK", "RIOT", "RIP", "RIPE", "RISE", "RISK", "RITE", "ROAD", "ROAM", "ROAR", "ROBE", "ROCK", "ROD", "RODE", "ROE", "ROIL", "ROLL", "ROME", "ROOF", "ROOM", "ROOT", "ROPE", "ROSE", "ROSY", "ROT", "ROUT", "ROVE", "ROW", "ROWS", "RUB", "RUBY", "RUG", "RUIN", "RULE", "RUM", "RUN", "RUNE", "RUNG", "RUNS", "RUNT", "RUSE", "RUSH", "RUST", "RUT", "RYE", "SACK", "SAD", "SAFE", "SAGA", "SAGE", "SAID", "SAIL", "SAKE", "SALE", "SALT", "SAME", "SAND", "SANE", "SANG", "SANK", "SANS", "SAP", "SASH", "SAT", "SATE", "SAVE", "SAW", "SAWN", "SAX", "SAY", "SAYS", "SCAD", "SCAM", "SCAN", "SCAR", "SCUM", "SEA", "SEAL", "SEAM", "SEAR", "SEAT", "SEE" , "SEED", "SEEK", "SEEM", "SEEN", "SEEP", "SEES", "SELF", "SELL", "SEND", "SENT", "SET", "SETS", "SEW", "SEWN", "SHAW", "SHE" , "SHED", "SHIM", "SHIN", "SHIP", "SHOD", "SHOE", "SHOO", "SHOP", "SHOT", "SHOW", "SHUN", "SHUT", "SHY", "SIC", "SICK", "SIDE", "SIFT", "SIGH", "SIGN", "SILK", "SILL", "SILO", "SILT", "SIN" , "SINE", "SING", "SINK", "SIR", "SIRE", "SIS", "SIT", "SITE", "SITH", "SITS", "SITU", "SIX", "SIZE", "SKEW", "SKI", "SKID", "SKIM", "SKIN", "SKIP", "SKIT", "SKY", "SLAB", "SLAG", "SLAM", "SLAP", "SLAT", "SLAW", "SLAY", "SLED", "SLEW", "SLID", "SLIM", "SLIP", "SLOG", "SLOP", "SLOT", "SLOW", "SLUG", "SLUM", "SLUR", "SLY", "SMOG", "SMUG", "SNAG", "SNAP", "SNOB", "SNOT", "SNOW", "SNUB", "SNUG", "SO", "SOAK", "SOAP", "SOAR", "SOB", "SOCK", "SOD", "SODA", "SOFA", "SOFT", "SOHO", "SOIL", "SOLD", "SOLE", "SOLO", "SOME", "SON", "SONG", "SONS", "SOON", "SOOT", "SOP" , "SOPE", "SORE", "SORT", "SORY", "SOUL", "SOUP", "SOUR", "SOW" , "SOWN", "SOY", "SPA", "SPAN", "SPAR", "SPAT", "SPAY", "SPEC", "SPED", "SPEW", "SPIN", "SPIT", "SPOT", "SPRY", "SPUD", "SPUR", "SPY", "STAB", "STAG", "STAR", "STAY", "STEM", "STEP", "STEW", "STIM", "STIR", "STOP", "STOW", "STUB", "STUD", "STUN", "SUB" , "SUCH", "SUDS", "SUE", "SUET", "SUIT", "SULK", "SUM", "SUMP", "SUMS", "SUN", "SUNG", "SUNK", "SURE", "SURF", "SWAB", "SWAD", "SWAG", "SWAM", "SWAN", "SWAP", "SWAT", "SWAY", "SWIG", "SWIM", "SWUM", "SYNC", "TAB", "TACK", "TACT", "TAD", "TAG", "TAIL", "TAKE", "TALC", "TALE", "TALK", "TALL", "TAME", "TAMP", "TAN" , "TANG", "TANK", "TAP", "TAPE", "TAPS", "TAR", "TARE", "TARP", "TART", "TASK", "TAUT", "TAX", "TAXI", "TEA", "TEAK", "TEAL", "TEAM", "TEAR", "TECH", "TEE", "TEEM", "TEEN", "TELL", "TEMP", "TEN", "TEND", "TENT", "TERM", "TEST", "TEXT", "THAN", "THAT", "THAW", "THE", "THEE", "THEM", "THEN", "THEY", "THIN", "THIS", "THOU", "THOW", "THUD", "THY", "TIC", "TICK", "TIDE", "TIDY", "TIE", "TIED", "TIER", "TIFF", "TILE", "TILL", "TILT", "TIME", "TIN", "TINE", "TINT", "TINY", "TIP", "TIRE", "TO", "TOAD", "TOE", "TOFU", "TOG", "TOGA", "TOGS", "TOIL", "TOKE", "TOLD", "TOLE", "TOLL", "TOMB", "TON", "TONE", "TONG", "TONY", "TOO" , "TOOK", "TOOL", "TOOT", "TOP", "TOPS", "TORE", "TORN", "TORT", "TOTE", "TOTO", "TOUR", "TOUT", "TOW", "TOWN", "TOY", "TRAM", "TRAP", "TRAY", "TREE", "TREK", "TRIM", "TRIO", "TROD", "TROT", "TRUE", "TRY", "TUB", "TUBA", "TUBE", "TUCK", "TUFT", "TUG" , "TULE", "TUNA", "TUNE", "TURF", "TURN", "TUSK", "TUT", "TUTU", "TUX", "TWAS", "TWEE", "TWIG", "TWIN", "TWIT", "TWO", "TYPE", "TYPO", "UGLY", "UNDO", "UNIT", "UNTO", "UP", "UPON", "URGE", "URN", "US", "USE", "USED", "USER", "USES", "VAIN", "VALE", "VAN", "VANE", "VARY", "VASE", "VAST", "VAT", "VEAL", "VEER", "VEIL", "VEIN", "VEND", "VENT", "VERB", "VERY", "VEST", "VET" , "VETO", "VEX", "VIA", "VICE", "VIE", "VIEW", "VILA", "VINE", "VISA", "VISE", "VOID", "VOLT", "VOTE", "VOW", "WAD", "WADE", "WAFT", "WAG", "WAGE", "WAIK", "WAIL", "WAIT", "WAKE", "WALK", "WALL", "WAND", "WANE", "WANT", "WAR", "WARD", "WARE", "WARM", "WARN", "WARP", "WART", "WARY", "WAS", "WASH", "WASP", "WATT", "WAVE", "WAVY", "WAX", "WAXY", "WAY", "WAYS", "WE", "WEAK", "WEAL", "WEAN", "WEAR", "WEB", "WED", "WEE", "WEED", "WEEK", "WEEP", "WEIR", "WELD", "WELL", "WELT", "WEND", "WENT", "WEPT", "WERE", "WEST", "WET", "WEVE", "WHAM", "WHAT", "WHEN", "WHET", "WHEY", "WHIM", "WHIP", "WHIZ", "WHO", "WHOA", "WHOM", "WHY" , "WICK", "WIDE", "WIFE", "WIG", "WILD", "WILL", "WILT", "WILY", "WIN", "WIND", "WINE", "WING", "WINK", "WIPE", "WIRE", "WISE", "WISH", "WISP", "WIT", "WITH", "WOK", "WOKE", "WOLF", "WON" , "WONT", "WOO", "WOOD", "WOOL", "WORD", "WORE", "WORK", "WORM", "WORN", "WORT", "WOT", "WOW", "WRAP", "WREN", "WRIT", "WRY" , "WUSS", "YAGI", "YAK", "YAM", "YANK", "YAP", "YARD", "YARN", "YAW", "YAWN", "YEA", "YEAH", "YEAR", "YELL", "YELP", "YES" , "YET", "YOGA", "YOGI", "YOKE", "YOLK", "YORE", "YORK", "YOU" , "YOUD", "YOUR", "YOWL", "YURT", "ZERO", "ZEST", "ZETA", "ZINC", "ZING", "ZINK", "ZIP", "ZONE", "ZOO", "ZORK", "ZOOM" }; // void banner(FILE* stream = stdout) { fprintf(stream, "\n\ %s (asdcplib %s)\n\n\ Copyright (c) 2003-2017 John Hurst\n\n\ %s is part of the asdcp DCP tools package.\n\ asdcplib may be copied only under the terms of the license found at\n\ the top of every file in the asdcplib distribution kit.\n\n\ Specify the -h (help) option for further information about %s\n\n", PROGRAM_NAME, Kumu::Version(), PROGRAM_NAME, PROGRAM_NAME); } // void usage(FILE* stream = stdout) { fprintf(stream, "\ USAGE: %s [-b|-B|-c|-x] [-n] [-s <size>] [-v]\n\ \n\ %s [-h|-help] [-V]\n\ \n\ -b - Output a stream of binary data\n\ -B - Output a Base64 string\n\ -c - Output a C-language struct containing the values\n\ -C - Encode as a list of code words (for each code word, 20 bits of\n\ entropy are consumed, 4 are discarded)\n\ -h | -help - Show help\n\ -n - Suppress newlines\n\ -s <size> - Number of random bytes to generate (default 32)\n\ -v - Verbose. Prints informative messages to stderr\n\ -V - Show version information\n\ -w - Encode as a list of dictionary words (for each dictionary word,\n\ 11 bits of entropy are consumed, 1 is discarded)\n\ -W <expr> - Word separator, for use with -C and -w (default '-')\n\ -x - Output hexadecimal (default)\n\ \n\ NOTES: o There is no option grouping, all options must be distinct arguments.\n\ o All option arguments must be separated from the option by whitespace.\n\ \n", PROGRAM_NAME, PROGRAM_NAME); } enum OutputFormat_t { OF_HEX, OF_BINARY, OF_BASE64, OF_CSTRUCT, OF_DICTWORD, OF_CODEWORD }; // class CommandOptions { CommandOptions(); public: bool error_flag; // true if the given options are in error or not complete bool no_newline_flag; // bool verbose_flag; // true if the verbose option was selected bool version_flag; // true if the version display option was selected bool help_flag; // true if the help display option was selected OutputFormat_t format; // ui32_t request_size; bool size_provided; // if true, the -s option has been used std::string separator; // word separator value for OF_DICTWORD and CODEWORD modes // CommandOptions(int argc, const char** argv) : error_flag(true), no_newline_flag(false), verbose_flag(false), version_flag(false), help_flag(false), format(OF_HEX), request_size(RandBlockSize*2), size_provided(false), separator("-") { for ( int i = 1; i < argc; i++ ) { if ( (strcmp( argv[i], "-help") == 0) ) { help_flag = true; continue; } if ( argv[i][0] == '-' && isalpha(argv[i][1]) && argv[i][2] == 0 ) { switch ( argv[i][1] ) { case 'b': format = OF_BINARY; break; case 'B': format = OF_BASE64; break; case 'c': format = OF_CSTRUCT; break; case 'C': format = OF_CODEWORD; break; case 'n': no_newline_flag = true; break; case 'h': help_flag = true; break; case 's': TEST_EXTRA_ARG(i, 's'); request_size = Kumu::xabs(strtol(argv[i], 0, 10)); size_provided = true; break; case 'v': verbose_flag = true; break; case 'V': version_flag = true; break; case 'w': format = OF_DICTWORD; break; case 'W': TEST_EXTRA_ARG(i, 'W'); separator = argv[i]; break; case 'x': format = OF_HEX; break; default: fprintf(stderr, "Unrecognized option: %s\n", argv[i]); return; } } else { fprintf(stderr, "Unrecognized option: %s\n", argv[i]); return; } } if ( help_flag || version_flag ) return; if ( ! size_provided ) { if ( format == OF_CODEWORD ) { request_size = 20; } else if ( format == OF_DICTWORD ) { request_size = 16; } } else if ( request_size == 0 ) { fprintf(stderr, "Please use a non-zero request size\n"); return; } error_flag = false; } }; // int main(int argc, const char** argv) { CommandOptions Options(argc, argv); if ( Options.version_flag ) banner(); if ( Options.help_flag ) usage(); if ( Options.version_flag || Options.help_flag ) return 0; if ( Options.error_flag ) { fprintf(stderr, "There was a problem. Type %s -h for help.\n", PROGRAM_NAME); return 3; } FortunaRNG RandGen; ByteString Buf(Kumu::Kilobyte); if ( Options.verbose_flag ) fprintf(stderr, "Generating %d random byte%s.\n", Options.request_size, (Options.request_size == 1 ? "" : "s")); if ( Options.format == OF_BINARY ) { if ( KM_FAILURE(Buf.Capacity(Options.request_size)) ) { fprintf(stderr, "randbuf: %s\n", RESULT_ALLOC.Label()); return 1; } RandGen.FillRandom(Buf.Data(), Options.request_size); fwrite((byte_t*)Buf.Data(), 1, Options.request_size, stdout); } else if ( Options.format == OF_CSTRUCT ) { ui32_t line_count = 0; byte_t* p = Buf.Data(); printf("byte_t rand_buf[%u] = {\n", Options.request_size); if ( Options.request_size > 128 ) fputs(" // 0x00000000\n", stdout); while ( Options.request_size > 0 ) { if ( line_count > 0 && (line_count % (RandBlockSize*8)) == 0 ) fprintf(stdout, " // 0x%08x\n", line_count); RandGen.FillRandom(p, RandBlockSize); fputc(' ', stdout); for ( ui32_t i = 0; i < RandBlockSize && Options.request_size > 0; i++, Options.request_size-- ) printf(" 0x%02x,", p[i]); fputc('\n', stdout); line_count += RandBlockSize; } fputs("};", stdout); if ( ! Options.no_newline_flag ) fputc('\n', stdout); } else if ( Options.format == OF_BASE64 ) { if ( KM_FAILURE(Buf.Capacity(Options.request_size)) ) { fprintf(stderr, "randbuf: %s\n", RESULT_ALLOC.Label()); return 1; } ByteString Strbuf; ui32_t e_len = base64_encode_length(Options.request_size) + 1; if ( KM_FAILURE(Strbuf.Capacity(e_len)) ) { fprintf(stderr, "strbuf: %s\n", RESULT_ALLOC.Label()); return 1; } RandGen.FillRandom(Buf.Data(), Options.request_size); if ( base64encode(Buf.RoData(), Options.request_size, (char*)Strbuf.Data(), Strbuf.Capacity()) == 0 ) { fprintf(stderr, "encode error\n"); return 2; } fputs((const char*)Strbuf.RoData(), stdout); if ( ! Options.no_newline_flag ) fputs("\n", stdout); } else if ( Options.format == OF_DICTWORD ) { byte_t* p = Buf.Data(); char hex_buf[64]; int word_count = 0; while ( Options.request_size > 0 ) { ui32_t x_len = xmin(Options.request_size, RandBlockSize); RandGen.FillRandom(p, RandBlockSize); // process 3 words at a time, each containing two 12-bit segments for ( int i = 0; i+3 < x_len; i+=3 ) { // ignore the high bit of each 12-bit segment, thus each output // word has 11 bits of the entropy int index1 = ( ( p[i] & 0x07f ) << 4 ) | ( p[i+1] >> 4 ); assert(index1<2048); int index2 = ( ( p[i+1] & 0x07 ) << 8 ) | p[i+2]; assert(index2<2048); printf("%s%s%s%s", (word_count==0?"":Options.separator.c_str()), _word_list[index1], Options.separator.c_str(), _word_list[index2]); word_count += 2; } Options.request_size -= x_len; } if ( ! Options.no_newline_flag ) { fputc('\n', stdout); } } else if ( Options.format == OF_CODEWORD ) { const char word_chars[] = "123456789ABCDEFGHJKLMNPRSTUVWXYZ"; byte_t* p = Buf.Data(); char hex_buf[64]; int word_count = 0; while ( Options.request_size > 0 ) { ui32_t x_len = xmin(Options.request_size, RandBlockSize); RandGen.FillRandom(p, RandBlockSize); // process 3 words at a time, derive a code word with 20 bits of entropy. for ( int i = 0; i+3 < x_len; i+=3 ) { int index1 = p[i] >> 3; // MSB bits 87654 assert(index1<32); int index2 = ( ( p[i] & 0x07 ) << 2 ) | ( p[i+1] >> 6 ); // MSB bits 321 & MSB+1 bits 78 assert(index2<32); int index3 = ( p[i+1] & 0x3e ) >> 1; // MSB+1 bits 65432 assert(index3<32); int index4 = p[i+2] & 0x1f; // MSB+2 bits 54321 assert(index4<32); printf("%s%c%c%c%c", (word_count==0?"":Options.separator.c_str()), word_chars[index1], word_chars[index2], word_chars[index3], word_chars[index4]); ++word_count; } Options.request_size -= x_len; } if ( ! Options.no_newline_flag ) { fputc('\n', stdout); } } else // OF_HEX { byte_t* p = Buf.Data(); char hex_buf[64]; while ( Options.request_size > 0 ) { ui32_t x_len = xmin(Options.request_size, RandBlockSize); RandGen.FillRandom(p, RandBlockSize); bin2hex(p, x_len, hex_buf, 64); fputs(hex_buf, stdout); Options.request_size -= x_len; if ( ! Options.no_newline_flag ) { fputc('\n', stdout); } } } return 0; } // // end kmrandgen.cpp //
42.942051
116
0.514291
[ "cad", "mesh" ]
109512eeb87e54d994a04c510c862e83a9f91345
2,507
hpp
C++
include/uitsl/nonce/spector.hpp
perryk12/conduit
3ea055312598353afd465536c8e04cdec1111c8c
[ "MIT" ]
null
null
null
include/uitsl/nonce/spector.hpp
perryk12/conduit
3ea055312598353afd465536c8e04cdec1111c8c
[ "MIT" ]
1
2020-10-22T20:41:05.000Z
2020-10-22T20:41:05.000Z
include/uitsl/nonce/spector.hpp
perryk12/conduit
3ea055312598353afd465536c8e04cdec1111c8c
[ "MIT" ]
null
null
null
#pragma once #ifndef UITSL_NONCE_SPECTOR_HPP_INCLUDE #define UITSL_NONCE_SPECTOR_HPP_INCLUDE #include <variant> #include "../../../third-party/Empirical/source/base/vector.h" #include "../../../third-party/Empirical/source/polyfill/span.h" namespace uitsl { template<typename T> class spector { using vector_t = emp::vector<T>; using span_t = std::span<T>; std::variant<vector_t, span_t> impl; public: /** * Forwarding constructor. * */ template <typename S, typename... Args> spector(std::in_place_type_t<S> which, Args&&... args) : impl( which, std::forward<Args>(args)... ) { ; } /** * Forwarding constructor. * */ template <typename... Args> spector(Args&&... args) : impl( std::in_place_type_t<vector_t>{}, std::forward<Args>(args)... ) { ; } /** * TODO. * * @return TODO. */ operator vector_t&() { emp_assert( std::holds_alternative<vector_t>(impl) ); return std::get<vector_t>(impl); } /** * TODO. * * @return TODO. */ operator const vector_t&() const { emp_assert( std::holds_alternative<vector_t>(impl) ); return std::get<vector_t>(impl); } /** * TODO. * * @return TODO. */ operator span_t&() { emp_assert( std::holds_alternative<span_t>(impl) ); return std::get<span_t>(impl); } /** * TODO. * * @return TODO. */ operator const span_t&() const { emp_assert( std::holds_alternative<span_t>(impl) ); return std::get<span_t>(impl); } /** * TODO. * * @return TODO. */ T *data() { return std::visit( [](auto& arg) -> T* { return arg.data(); }, impl ); } /** * TODO. * * @return TODO. */ const T *data() const { return std::visit( [](const auto& arg) -> const T* { return arg.data(); }, impl ); } /** * TODO. * * @return TODO. */ size_t size() const { return std::visit( [](const auto& arg) -> size_t { return arg.size(); }, impl ); } /** * TODO. * * @return TODO. */ size_t size_bytes() const { return std::visit( [](const auto& arg) -> size_t { return arg.size() * sizeof(T); }, impl ); } /** * TODO. * * @return TODO. */ void resize(const size_t count) { emp_assert( std::holds_alternative<vector_t>(impl) ); std::get<emp::vector<T>>(impl).resize(count); } }; } // namespace uitsl #endif // #ifndef UITSL_NONCE_SPECTOR_HPP_INCLUDE
16.493421
71
0.554846
[ "vector" ]
10a241dcd329d8308207add0eed8804d8b73b85b
4,779
hpp
C++
src/adapt/FixSideSetsSelector.hpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
3
2017-08-08T21:06:02.000Z
2020-01-08T13:23:36.000Z
src/adapt/FixSideSetsSelector.hpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2016-12-17T00:18:56.000Z
2019-08-09T15:29:25.000Z
src/adapt/FixSideSetsSelector.hpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2017-11-30T07:02:41.000Z
2019-08-05T17:07:04.000Z
// Copyright 2002 - 2008, 2010, 2011 National Technology Engineering // Solutions of Sandia, LLC (NTESS). Under the terms of Contract // DE-NA0003525 with NTESS, the U.S. Government retains certain rights // in this software. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef adapt_FixSideSetsSelector_hpp #define adapt_FixSideSetsSelector_hpp #include <adapt/Refiner.hpp> namespace percept { // for the refine pass class FixSideSetsSelectorRefine : public RefinerSelector { public: PerceptMesh& m_eMesh; SetOfEntities m_node_set; FixSideSetsSelectorRefine(PerceptMesh& eMesh) : m_eMesh(eMesh) { m_node_set.clear(); } // incoming is the list of all new elements void add_elements(vector<stk::mesh::Entity>::iterator beg, vector<stk::mesh::Entity>::iterator end) { PerceptMesh& eMesh = m_eMesh; for (auto elem = beg; elem != end; ++elem) { if (!eMesh.is_valid(*elem)) continue; if (eMesh.entity_rank(*elem) != eMesh.element_rank()) continue; unsigned nnode= eMesh.get_bulk_data()->num_nodes(*elem); stk::mesh::Entity const *elem_nodes = eMesh.get_bulk_data()->begin_nodes(*elem); for (unsigned ii=0; ii < nnode; ii++) { m_node_set.insert(elem_nodes[ii]); } } } virtual bool use_batch_filter() { return true; } virtual void batch_filter(stk::mesh::EntityRank rank, SetOfEntities& sides) { bool tmp = true; if (tmp) return; SetOfEntities sides_copy = sides; size_t orig_size = sides.size(); sides.clear(); for (auto side : sides_copy) { unsigned nnode= m_eMesh.get_bulk_data()->num_nodes(side); stk::mesh::Entity const *side_nodes = m_eMesh.get_bulk_data()->begin_nodes(side); for (unsigned ii=0; ii < nnode; ii++) { if (m_node_set.find(side_nodes[ii]) != m_node_set.end()) { sides.insert(side); break; } } } size_t new_size = sides.size(); stk::all_reduce( m_eMesh.parallel(), stk::ReduceSum<1>( &new_size ) ); stk::all_reduce( m_eMesh.parallel(), stk::ReduceSum<1>( &orig_size ) ); if (m_eMesh.get_rank()==0) { std::cerr << m_eMesh.rank() << "ref cpu= " << m_eMesh.cpu_time() << " new= " << new_size << " old= " << orig_size << " = " << 100.0*double(new_size)/double(std::max(size_t(1),orig_size)) << "%" << std::endl; } } }; // for the unrefine pass class FixSideSetsSelectorUnrefine : public RefinerSelector { public: PerceptMesh& m_eMesh; SetOfEntities m_node_set; FixSideSetsSelectorUnrefine(PerceptMesh& eMesh) : m_eMesh(eMesh) { m_node_set.clear(); } // incoming is the list of all new elements void add_elements(SetOfEntities& elem_set) { PerceptMesh& eMesh = m_eMesh; for (auto elem : elem_set) { if (!eMesh.is_valid(elem)) continue; if (eMesh.entity_rank(elem) != eMesh.element_rank()) continue; unsigned nnode= eMesh.get_bulk_data()->num_nodes(elem); stk::mesh::Entity const *elem_nodes = eMesh.get_bulk_data()->begin_nodes(elem); for (unsigned ii=0; ii < nnode; ii++) { m_node_set.insert(elem_nodes[ii]); } } } virtual bool use_batch_filter() { return true; } virtual void batch_filter(stk::mesh::EntityRank rank, SetOfEntities& sides) { bool tmp = true; if (tmp) return; SetOfEntities sides_copy = sides; size_t orig_size = sides.size(); sides.clear(); for (auto side : sides_copy) { unsigned nnode= m_eMesh.get_bulk_data()->num_nodes(side); stk::mesh::Entity const *side_nodes = m_eMesh.get_bulk_data()->begin_nodes(side); for (unsigned ii=0; ii < nnode; ii++) { if (m_node_set.find(side_nodes[ii]) != m_node_set.end()) { sides.insert(side); break; } } } size_t new_size = sides.size(); stk::all_reduce( m_eMesh.parallel(), stk::ReduceSum<1>( &new_size ) ); stk::all_reduce( m_eMesh.parallel(), stk::ReduceSum<1>( &orig_size ) ); if (m_eMesh.get_rank()==0) { std::cerr << m_eMesh.rank() << "unref cpu= " << m_eMesh.cpu_time() << " new= " << new_size << " old= " << orig_size << " = " << 100.0*double(new_size)/double(std::max(size_t(1),orig_size)) << "%" << std::endl; } } }; } #endif
30.832258
219
0.578782
[ "mesh", "vector" ]
10a4b997311a521b03485d2ab09cc1e7d775288f
1,708
hpp
C++
stan/math/rev/mat/fun/LDLT_alloc.hpp
riddell-stan/math
d84ee0d991400d6cf4b08a07a4e8d86e0651baea
[ "BSD-3-Clause" ]
null
null
null
stan/math/rev/mat/fun/LDLT_alloc.hpp
riddell-stan/math
d84ee0d991400d6cf4b08a07a4e8d86e0651baea
[ "BSD-3-Clause" ]
1
2019-09-23T19:58:36.000Z
2019-09-24T12:03:41.000Z
stan/math/rev/mat/fun/LDLT_alloc.hpp
riddell-stan/math
d84ee0d991400d6cf4b08a07a4e8d86e0651baea
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_REV_MAT_FUN_LDLT_ALLOC_HPP #define STAN_MATH_REV_MAT_FUN_LDLT_ALLOC_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/rev/core.hpp> namespace stan { namespace math { /** * This object stores the actual (double typed) LDLT factorization of * an Eigen::Matrix<var> along with pointers to its vari's which allow the * *ldlt_ functions to save memory. It is derived from a chainable_alloc * object so that it is allocated on the stack but does not have a chain() * function called. * * This class should only be instantiated as part of an LDLT_factor object * and is only used in *ldlt_ functions. **/ template <int R, int C> class LDLT_alloc : public chainable_alloc { public: LDLT_alloc() : N_(0) {} explicit LDLT_alloc(const Eigen::Matrix<var, R, C> &A) : N_(0) { compute(A); } /** * Compute the LDLT factorization and store pointers to the * vari's of the matrix entries to be used when chain() is * called elsewhere. **/ inline void compute(const Eigen::Matrix<var, R, C> &A) { Eigen::Matrix<double, R, C> Ad(A.rows(), A.cols()); N_ = A.rows(); variA_.resize(A.rows(), A.cols()); for (size_t j = 0; j < N_; j++) { for (size_t i = 0; i < N_; i++) { Ad(i, j) = A(i, j).val(); variA_(i, j) = A(i, j).vi_; } } ldlt_.compute(Ad); } // Compute the log(abs(det(A))). This is just a convenience function. inline double log_abs_det() const { return ldlt_.vectorD().array().log().sum(); } size_t N_; Eigen::LDLT<Eigen::Matrix<double, R, C> > ldlt_; Eigen::Matrix<vari *, R, C> variA_; }; } // namespace math } // namespace stan #endif
28.949153
80
0.65281
[ "object" ]
10a718e630cfc2b0ee7adef0696d2a433091704d
3,017
cpp
C++
test/testFSK.cpp
MaxZZG/RadProps
bd95421430fc266ee88d0480069f7d20be1414f6
[ "MIT" ]
null
null
null
test/testFSK.cpp
MaxZZG/RadProps
bd95421430fc266ee88d0480069f7d20be1414f6
[ "MIT" ]
null
null
null
test/testFSK.cpp
MaxZZG/RadProps
bd95421430fc266ee88d0480069f7d20be1414f6
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2017 The University of Utah * * 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 <radprops/AbsCoeffGas.h> #include "TestHelper.h" #include <vector> #include <stdexcept> #include <cmath> #include <iostream> using namespace std; using namespace RadProps; int main( int argc, char* argv[] ) { TestHelper status(false); std::vector<RadiativeSpecies> gasSpeciesEnum(5); gasSpeciesEnum[0]= H2O; gasSpeciesEnum[1]= CO2; gasSpeciesEnum[2]= CO; gasSpeciesEnum[3]= NO; gasSpeciesEnum[4]= OH; try{ const FSK fsk1(gasSpeciesEnum); const FSK fsk2("Gs.txt"); std::vector<RadiativeSpecies> gasSpeciesCheck; gasSpeciesCheck = fsk2.species(); vector<string> gasSpecies; for (int r = 0; r<5; r++) { gasSpecies.push_back(species_name( fsk2.species()[r] )); cout << "Order = " << gasSpecies[r] << endl; } std::vector<double> myMoleFracs (5); myMoleFracs[0]=0.1; myMoleFracs[1]=0.4; myMoleFracs[2]=0.15; myMoleFracs[3]=0.3; myMoleFracs[4]=0.05; std::vector<double> aF1, aF2; fsk1.a_function(aF1,myMoleFracs,1030,1080); fsk2.a_function(aF2,myMoleFracs,1030,1080); //Test a Func for( size_t r = 0; r<aF1.size(); ++r ){ const double err = std::abs( aF1[r] -aF2[r] )/aF1[r]; status( err < 1e-9 ); if( err>1e-9 ){ cout << "PROBLEMS! " << r << " of " << aF1.size() << " : " << aF1[r] << " : " << aF2[r] << " : " << std::abs( aF1[r] -aF2[r] )/aF1[r] << endl; } } // jcs need to add some more temperatures status( std::abs( fsk1.mixture_abs_coeff( myMoleFracs, 1050.0, 0.1 ) - fsk2.mixture_abs_coeff( myMoleFracs, 1050.0, 0.1 ))/fsk1.mixture_abs_coeff( myMoleFracs, 1050.0, 0.1 ) < 1e-5 ); if( status.ok() ){ cout << "PASS" << endl; return 0; } } catch( std::exception& err ){ cout << err.what() << endl; } cout << "FAIL" << endl; return -1; }
31.757895
136
0.648658
[ "vector" ]
10ac5f9a2921859cbc876e5c384ef4d92e4e0cd1
9,857
cc
C++
src/o1.flag_set.test.cc
garana/o1.cpp.lib
fbd795545222129dae90f5eb593b7cc169761d49
[ "BSD-3-Clause" ]
null
null
null
src/o1.flag_set.test.cc
garana/o1.cpp.lib
fbd795545222129dae90f5eb593b7cc169761d49
[ "BSD-3-Clause" ]
null
null
null
src/o1.flag_set.test.cc
garana/o1.cpp.lib
fbd795545222129dae90f5eb593b7cc169761d49
[ "BSD-3-Clause" ]
null
null
null
/** * BSD 3-Clause License * * Copyright (c) 2021, Gonzalo Arana * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <gtest/gtest.h> #include "o1.flag_set.hh" enum class enumSmallTest { enNONE = 0, enOne = 1, enTwo = 2, en31 = 31 }; enum class enum64Test { enNONE = 0, enOne = 1, enTwo = 2, en31 = 31, en63 = 63 }; enum class enumLargeTest { enNONE = 0, enOne = 1, enTwo = 2, en31 = 31, en63 = 63, en127 = 127, }; TEST(flag_set, small) { o1::flag_set<enumSmallTest> test_set; EXPECT_EQ(test_set.isSet(enumSmallTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enOne), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enTwo), false); EXPECT_EQ(test_set.isSet(enumSmallTest::en31), false); test_set.set(enumSmallTest::enOne); EXPECT_EQ(test_set.isSet(enumSmallTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enOne), true); EXPECT_EQ(test_set.isSet(enumSmallTest::enTwo), false); EXPECT_EQ(test_set.isSet(enumSmallTest::en31), false); test_set.set(enumSmallTest::enTwo); EXPECT_EQ(test_set.isSet(enumSmallTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enOne), true); EXPECT_EQ(test_set.isSet(enumSmallTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumSmallTest::en31), false); test_set.clear(enumSmallTest::enOne); EXPECT_EQ(test_set.isSet(enumSmallTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enOne), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumSmallTest::en31), false); test_set.set(enumSmallTest::en31); EXPECT_EQ(test_set.isSet(enumSmallTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enOne), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumSmallTest::en31), true); test_set.clear(enumSmallTest::en31); EXPECT_EQ(test_set.isSet(enumSmallTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enOne), false); EXPECT_EQ(test_set.isSet(enumSmallTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumSmallTest::en31), false); } TEST(flag_set, sixtyFourBits) { o1::flag_set<enum64Test, uint64_t> test_set; EXPECT_EQ(test_set.isSet(enum64Test::enNONE), false); EXPECT_EQ(test_set.isSet(enum64Test::enOne), false); EXPECT_EQ(test_set.isSet(enum64Test::enTwo), false); EXPECT_EQ(test_set.isSet(enum64Test::en31), false); EXPECT_EQ(test_set.isSet(enum64Test::en63), false); test_set.set(enum64Test::enOne); EXPECT_EQ(test_set.isSet(enum64Test::enNONE), false); EXPECT_EQ(test_set.isSet(enum64Test::enOne), true); EXPECT_EQ(test_set.isSet(enum64Test::enTwo), false); EXPECT_EQ(test_set.isSet(enum64Test::en31), false); EXPECT_EQ(test_set.isSet(enum64Test::en63), false); test_set.set(enum64Test::enTwo); EXPECT_EQ(test_set.isSet(enum64Test::enNONE), false); EXPECT_EQ(test_set.isSet(enum64Test::enOne), true); EXPECT_EQ(test_set.isSet(enum64Test::enTwo), true); EXPECT_EQ(test_set.isSet(enum64Test::en31), false); EXPECT_EQ(test_set.isSet(enum64Test::en63), false); test_set.clear(enum64Test::enOne); EXPECT_EQ(test_set.isSet(enum64Test::enNONE), false); EXPECT_EQ(test_set.isSet(enum64Test::enOne), false); EXPECT_EQ(test_set.isSet(enum64Test::enTwo), true); EXPECT_EQ(test_set.isSet(enum64Test::en31), false); EXPECT_EQ(test_set.isSet(enum64Test::en63), false); test_set.set(enum64Test::en31); EXPECT_EQ(test_set.isSet(enum64Test::enNONE), false); EXPECT_EQ(test_set.isSet(enum64Test::enOne), false); EXPECT_EQ(test_set.isSet(enum64Test::enTwo), true); EXPECT_EQ(test_set.isSet(enum64Test::en31), true); EXPECT_EQ(test_set.isSet(enum64Test::en63), false); test_set.clear(enum64Test::en31); EXPECT_EQ(test_set.isSet(enum64Test::enNONE), false); EXPECT_EQ(test_set.isSet(enum64Test::enOne), false); EXPECT_EQ(test_set.isSet(enum64Test::enTwo), true); EXPECT_EQ(test_set.isSet(enum64Test::en31), false); EXPECT_EQ(test_set.isSet(enum64Test::en63), false); test_set.set(enum64Test::en63); EXPECT_EQ(test_set.isSet(enum64Test::enNONE), false); EXPECT_EQ(test_set.isSet(enum64Test::enOne), false); EXPECT_EQ(test_set.isSet(enum64Test::enTwo), true); EXPECT_EQ(test_set.isSet(enum64Test::en31), false); EXPECT_EQ(test_set.isSet(enum64Test::en63), true); test_set.clear(enum64Test::en63); EXPECT_EQ(test_set.isSet(enum64Test::enNONE), false); EXPECT_EQ(test_set.isSet(enum64Test::enOne), false); EXPECT_EQ(test_set.isSet(enum64Test::enTwo), true); EXPECT_EQ(test_set.isSet(enum64Test::en31), false); EXPECT_EQ(test_set.isSet(enum64Test::en63), false); } TEST(flag_set, large) { o1::flag_set<enumLargeTest, std::vector<bool>> test_set; EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), false); test_set.set(enumLargeTest::enOne); EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), true); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), false); test_set.set(enumLargeTest::enTwo); EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), true); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), false); test_set.clear(enumLargeTest::enOne); EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), false); test_set.set(enumLargeTest::en31); EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), false); test_set.clear(enumLargeTest::en31); EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), false); test_set.set(enumLargeTest::en63); EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), false); test_set.clear(enumLargeTest::en63); EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), false); test_set.set(enumLargeTest::en127); EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), true); test_set.clear(enumLargeTest::en127); EXPECT_EQ(test_set.isSet(enumLargeTest::enNONE), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enOne), false); EXPECT_EQ(test_set.isSet(enumLargeTest::enTwo), true); EXPECT_EQ(test_set.isSet(enumLargeTest::en31), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en63), false); EXPECT_EQ(test_set.isSet(enumLargeTest::en127), false); }
41.070833
81
0.77133
[ "vector" ]
10b23605ddeeed08fe0e8849cc97e3007bd4ec52
1,611
cpp
C++
169.cpp
LeeYiyuan/projecteuler
81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74
[ "MIT" ]
null
null
null
169.cpp
LeeYiyuan/projecteuler
81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74
[ "MIT" ]
null
null
null
169.cpp
LeeYiyuan/projecteuler
81a0b65f73b47fbb9bfe99cb5ff72da7e0ba0d74
[ "MIT" ]
null
null
null
/* We start from a sum of 0 and try to add powers of 2 until the sum reaches 10^25. We start from 2^0 and consider powers of 2 incrementally. Note that at each power 2^e, we either add 0, 2^e, 2^{e + 1} to the current sum depending on whether 2^e is counted 0, 1, 2 times respectively. The trick is to notice that after considering the power 2^e, all future steps will only alter the bits greater than the e-th bit, meaning that the bits 0, ..., e are fixed after step e. Hence at each step e, the multiple of 2^e added to the current sum must satisfy the requirement that bits 0, ..., e of the resultant sum are the same as that of 10^25. The above allows us to do some dynamic programming. At each step e + 1, we consider the possible sums from step 0, ..., e. Since we know what bits 0, ..., e must be after step e, we only need to consider the number of cases for each possible value of bit e + 1 after step e. After step e + 1, we save the number of cases for each possible value of bit e + 2 for use for the next step, and repeat until we finish up all the bits in 10^25. */ #include <iostream> #include <gmpxx.h> #include <vector> #include <cstdint> #include "number_util.h" int main() { mpz_class n = util::pow(mpz_class(10), 25); std::vector<uint64_t> cases = { 1, (n & 1) == 0 }; while ((n >>= 1) > 0) { if ((n & 1) == mpz_class(0)) cases = { cases[0], cases[0] + cases[1] }; else cases = { cases[0] + cases[1], cases[1] }; } std::cout << cases[0]; }
34.276596
80
0.629423
[ "vector" ]
10b9a9cc59079de3d47ec6766bc0aa58aa6d2a37
2,191
cpp
C++
Exercise3_User/User.cpp
CalaW/Hitokoto-
33f456a7f1105ce7dfbfad8cd0bbf4c86c0c25c6
[ "WTFPL" ]
4
2021-08-18T06:51:14.000Z
2022-03-06T01:30:01.000Z
Exercise3_User/User.cpp
CalaW/Hitokoto
33f456a7f1105ce7dfbfad8cd0bbf4c86c0c25c6
[ "WTFPL" ]
null
null
null
Exercise3_User/User.cpp
CalaW/Hitokoto
33f456a7f1105ce7dfbfad8cd0bbf4c86c0c25c6
[ "WTFPL" ]
null
null
null
/** * @file User.cpp * @author CalaW (maker_cc@foxmail.com) * @brief * @version 0.1 * @date 2021-07-28 * * */ #include "User.h" //static member initialization string User::admin_name = "Admin"; string User::admin_pwd = "Admin"; vector<User*> User::user_index{}; //bool User::_admin_exist = false; /** * @brief Method to add an administrator * * @retval true: success * @retval false: unsuccess */ bool User::AddAdminUser() { // if (_admin_exist == false) { //TODO why not? // user_index.push_back(new User(admin_name, admin_pwd, userType::Admin)); // return true; // } // return false; bool admin_exist = false; std::for_each(user_index.begin(), user_index.end(), [&](User* const iter) { if (iter->_type == userType::Admin) { admin_exist = true; } }); if (admin_exist) { return false; //only one admin user can exist } user_index.push_back(new User(admin_name, admin_pwd, userType::Admin)); return true; } /** * @brief Method to add a trivial user * * @param name username * @param pwd user password * @retval true: success * @retval false: unsuccess */ bool User::AddTrivialUser(const string& name, const string& pwd) { if (name == admin_name) { return false; //trivial username cannot be admin } for (const auto& iter : user_index) { if (iter->_name == name) { return false; //username cannot be same } } user_index.push_back(new User(name, pwd, userType::Trivial)); return true; } /** * @brief Method for delete all user * */ void User::ClearAllUser() { for (auto& iter : user_index) { delete iter; iter = nullptr; //set pointer to null } } /** * @brief Private constructor of User object * * @param name username * @param pwd password * @param type usertype * @exception UserException username/password cannot be empty */ User::User(const string& name, const string& pwd, userType type) { if (name.empty() || pwd.empty()) { throw UserException("error: Username or password cannot be empty.\n"); } _name = name; _pwd = pwd; _type = type; }
23.815217
82
0.61707
[ "object", "vector" ]
10b9f4b3a20eec0e0d8b1cf093a9f08308436ed2
864
cpp
C++
158.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
158.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
158.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ull = uint64_t; using ll = int64_t; using ld = long double; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; // Forward declaration of the read4 API. int read4(char *buf); class Solution { private: stack<char> s; public: /** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */ int read(char *buf, int n) { int len = 0; while (len < n) { if (!s.empty()) { char c = s.top(); s.pop(); *buf = c; buf++; len++; } else { int read_len = read4(buf); if (read_len) { len += read_len; buf += read_len; } else return len; } } while (len > n) { buf--; s.push(*buf); *buf = '\0'; len--; } return len; } };
14.4
51
0.553241
[ "vector" ]
10c36182b83781bb3997b75682ceff0a404ba31c
6,389
cpp
C++
Clase6 08-11-21/GRAPHS_DFS/DFS_implementacion.cpp
FabiTaparaQuispe/LabADAGrupoB
cb12f6408329ac94b47425615545e094e65b3875
[ "BSD-3-Clause" ]
null
null
null
Clase6 08-11-21/GRAPHS_DFS/DFS_implementacion.cpp
FabiTaparaQuispe/LabADAGrupoB
cb12f6408329ac94b47425615545e094e65b3875
[ "BSD-3-Clause" ]
null
null
null
Clase6 08-11-21/GRAPHS_DFS/DFS_implementacion.cpp
FabiTaparaQuispe/LabADAGrupoB
cb12f6408329ac94b47425615545e094e65b3875
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <cstdlib> #include<fstream> #include<bits/stdc++.h> /* * Ejercicio 4 DFS Implementacion * Autor: Fabiola Tapara Quispe * Description: Implementacion del algoritmo DFS fstream y ostream * Date: 08/11/21 */ using namespace std; //Primero generamos una matriz que contenga ceros para asi crear poco a poco el grafo con camino basico pseudoaleatorio void vacio(int **Ma, int fil){ for (int i=0; i<fil;i++) { for(int j=0; j<fil; j++) { Ma[i][j]=0; } } } //Creamos el grafo pseudoaleatorio considerando el camino basico, el rand()nos ayuda a llenar la matriz void ingreso(int **Ma, int fil) { int a=0,b=1; for(int i=0; i<fil;i++) { for(int j=0; j<fil; j++) { if(j>i) { if(i==a &&j==b){ Ma[i][j]=1; a++; b++; } else{ Ma[i][j]=rand()%2; } Ma[j][i]=Ma[i][j]; } } } } //Mostramos el grafo conexo pseudo aleatorio creado void mostrar(int **Ma, int fil){ for(int i=0; i<fil;i++) { for(int j=0; j<fil;j++){ cout<<Ma[i][j]<<" "; } cout<<endl; } } //Creamos el archivo .dot para ver el grafo conexo void graphviz(int **Ma, int fil) { cout<<"LISTA DE ADYACENCIA"<<endl; ofstream f; f.open("E:\\SISTEMAS\\CUARTO SEMESTRE\\ADA\\LABORATORIO\\Graphviz\\bin\\grafoconexo.dot"); f<<"graph A {"<<endl; cout<<"graph A {"<<endl; for(int i=0; i<fil;i++) { for(int j=0; j<fil; j++) { if(j>=i) { if(Ma[i][j]==1) { f<<i<<" -- "<<j<<";"<<endl; cout<<i<<" -- "<<j<<";"<<endl; } } } } f<<"}"; cout<<"}"<<endl; f.close(); } //Creamos una lista de adyacencia que usaremos para la busqueda en profundidad y en anchura void crearlista(vector<int> adyacencia[],int& numero,int**& matriz,int& inicio,vector<int>& indices){ for(int j=0;j<numero;j++){ if(matriz[inicio][j]==1){ adyacencia[0].push_back(j); } } bool flag=false; for(int i=0;i<numero;i++){ if(i==inicio){ flag=true; continue; }else{ indices[0]=inicio; if(flag){ indices[i]=i; }else{ indices[i+1]=i; } } for(int j=0;j<numero;j++){ if(matriz[i][j]==1){ if(flag){ adyacencia[i].push_back(j); }else{ adyacencia[i+1].push_back(j); } } } } } void imprimir(vector<int> adyacencia[],int& numero,vector<int>& indices){ cout<<"La lista de adyacencia es: "<<endl; for(int i=0;i<numero;i++){ cout<<indices[i]<<" "; for(int j=0;j<adyacencia[i].size();j++){ cout<<adyacencia[i][j]<<"-"; } cout<<endl; } } //Para la busqueda en profundidad usamos un arreglo de vectores en donde guardaremos //la matriz de adyacencia anterior y asi llevamos el recorrido con el vector visited. void DFSUtil(int numero, vector<int> adj[],vector<bool> &visited) { visited[numero] = true; for (int i=0; i<adj[numero].size(); i++){ if (visited[adj[numero][i]] == false){ cout<<numero<<"->"<<adj[numero][i]<<";"<<endl; DFSUtil(adj[numero][i], adj, visited); } } } void DFS(vector<int> adj[], int V,vector<int>& indices) { cout<<"El recorrido por DFS es: "<<endl; vector<bool> visited(V, false); for (int u=0; u<V; u++){ if (visited[indices[u]] == false){ DFSUtil(indices[u], adj, visited); } } cout<<endl; } void imprimirlista(vector<bool> vec){ for(int i=0;i<vec.size();i++){ cout<<vec[i]<<" "; } cout<<endl; } int block; //Para el recorrdo en anchura, esta vez cuidamos que en el vector visited true o false y //y recorre mas cuando sea true en el vector de adyacencia void BFSUtil(int& numero, vector<int> adj[],vector<bool> &visited,vector<int>& indices) { vector<int> cola; for(int j=0;j<adj[numero].size();j++){ if(visited[indices[adj[numero][j]]]==false){ cola.push_back(adj[numero][j]); visited[indices[adj[numero][j]]]=true; if(adj[numero][j]!=block){ cout <<numero<<"->"<<adj[numero][j]<<";"<<endl; } } } for (int i=0; i<cola.size(); i++) BFSUtil(cola[i], adj, visited,indices); } void BFS(vector<int> adj[], int V,vector<int>& indices) { cout<<"El recorrido por BFS es: "<<endl; vector<bool> visited(V, false); vector<int> cola; int aux; visited[indices[0]]=true; aux=indices[0]; block=aux; for(int j=0;j<adj[0].size();j++){ cola.push_back(adj[0][j]); visited[indices[adj[0][j]]]=true; cout <<aux<<"->"<<cola[j]<<";"<<endl; } for(int j=0;j<cola.size();j++){ BFSUtil(cola[j], adj, visited,indices); } } int main(){ //Elabora un grafo conexo pseudo aleatorio int fi; cout<<"Ingresar numero de vertices: "<<endl;cin>>fi; //int matriz[fi][col]; int **matriz=new int *[fi]; //puntero que apunta a un array de punteros for(int i=0; i<fi;i++){ matriz[i]=new int[fi]; } //cout<<"Primero se crea un grafo vacio"<<endl; vacio(matriz, fi); //cout<<"Luego ingresamos un grafo"<<endl; ingreso(matriz, fi); cout<<"Mostramos el grafo"<<endl; mostrar(matriz, fi); //cout<<"Lista de adyascencia del grafo"<<endl; graphviz(matriz, fi); cout<<"Se ingreso arbol conexo "<<endl; int v; cout<<"Ingresar el vertice raiz: "<<endl; cin>>v; //Mediante el grafo conexo formamos un arbol generador por busqueda en profundidad vector<int> adyacencia[fi]; vector<int> indices(fi); crearlista(adyacencia,fi,matriz,v,indices); imprimir(adyacencia,fi,indices); DFS(adyacencia,fi,indices); //Mediante el grafo conexo formamos un arbol generador por busqueda en abchura BFS(adyacencia,fi,indices); return 0; }
26.292181
119
0.5198
[ "vector" ]
10c4506a82a17e637825b97dadcc01fe602c6eb0
8,594
cpp
C++
lib/qextserial/qextserialport.cpp
nddvn2008/bullet-physics-playground
2895af190054b6a38525b679cf3f241c7147ee6f
[ "Zlib" ]
1
2015-10-05T01:25:18.000Z
2015-10-05T01:25:18.000Z
lib/qextserial/qextserialport.cpp
nddvn2008/bullet-physics-playground
2895af190054b6a38525b679cf3f241c7147ee6f
[ "Zlib" ]
null
null
null
lib/qextserial/qextserialport.cpp
nddvn2008/bullet-physics-playground
2895af190054b6a38525b679cf3f241c7147ee6f
[ "Zlib" ]
2
2015-01-02T20:02:13.000Z
2018-02-26T03:08:43.000Z
#include <stdio.h> #include "qextserialport.h" /*! Default constructor. Note that the name of the device used by a QextSerialPort constructed with this constructor will be determined by #defined constants, or lack thereof - the default behavior is the same as _TTY_LINUX_. Possible naming conventions and their associated constants are: \verbatim Constant Used By Naming Convention ---------- ------------- ------------------------ Q_OS_WIN Windows COM1, COM2 _TTY_IRIX_ SGI/IRIX /dev/ttyf1, /dev/ttyf2 _TTY_HPUX_ HP-UX /dev/tty1p0, /dev/tty2p0 _TTY_SUN_ SunOS/Solaris /dev/ttya, /dev/ttyb _TTY_DIGITAL_ Digital UNIX /dev/tty01, /dev/tty02 _TTY_FREEBSD_ FreeBSD /dev/ttyd0, /dev/ttyd1 _TTY_OPENBSD_ OpenBSD /dev/tty00, /dev/tty01 _TTY_LINUX_ Linux /dev/ttyS0, /dev/ttyS1 <none> Linux /dev/ttyS0, /dev/ttyS1 \endverbatim This constructor assigns the device name to the name of the first port on the specified system. See the other constructors if you need to open a different port. */ QextSerialPort::QextSerialPort(QObject* parent, QextSerialPort::QueryMode mode) : QIODevice(parent) { #ifdef Q_OS_WIN setPortName("COM1"); #elif defined(_TTY_IRIX_) setPortName("/dev/ttyf1"); #elif defined(_TTY_HPUX_) setPortName("/dev/tty1p0"); #elif defined(_TTY_SUN_) setPortName("/dev/ttya"); #elif defined(_TTY_DIGITAL_) setPortName("/dev/tty01"); #elif defined(_TTY_FREEBSD_) setPortName("/dev/ttyd1"); #elif defined(_TTY_OPENBSD_) setPortName("/dev/tty00"); #else setPortName("/dev/ttyS0"); #endif construct(); setQueryMode(mode); platformSpecificInit(); } /*! Constructs a serial port attached to the port specified by name. name is the name of the device, which is windowsystem-specific, e.g."COM1" or "/dev/ttyS0". */ QextSerialPort::QextSerialPort(const QString & name, QObject* parent, QextSerialPort::QueryMode mode) : QIODevice(parent) { construct(); setQueryMode(mode); setPortName(name); platformSpecificInit(); } /*! Constructs a port with default name and specified settings. */ QextSerialPort::QextSerialPort(const PortSettings& settings, QObject* parent, QextSerialPort::QueryMode mode) : QIODevice(parent) { construct(); setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setParity(settings.Parity); setStopBits(settings.StopBits); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Millisec); setQueryMode(mode); platformSpecificInit(); } /*! Constructs a port with specified name and settings. */ QextSerialPort::QextSerialPort(const QString & name, const PortSettings& settings, QObject* parent, QextSerialPort::QueryMode mode) : QIODevice(parent) { construct(); setPortName(name); setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setParity(settings.Parity); setStopBits(settings.StopBits); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Millisec); setQueryMode(mode); platformSpecificInit(); } /*! Common constructor function for setting up default port settings. (115200 Baud, 8N1, Hardware flow control where supported, otherwise no flow control, and 0 ms timeout). */ void QextSerialPort::construct() { lastErr = E_NO_ERROR; Settings.BaudRate=BAUD115200; Settings.DataBits=DATA_8; Settings.Parity=PAR_NONE; Settings.StopBits=STOP_1; Settings.FlowControl=FLOW_HARDWARE; Settings.Timeout_Millisec=500; mutex = new QMutex( QMutex::Recursive ); setOpenMode(QIODevice::NotOpen); } void QextSerialPort::setQueryMode(QueryMode mechanism) { _queryMode = mechanism; } /*! Sets the name of the device associated with the object, e.g. "COM1", or "/dev/ttyS0". */ void QextSerialPort::setPortName(const QString & name) { #ifdef Q_OS_WIN port = fullPortNameWin( name ); #else port = fullPortNameUnix( name ); #endif } /*! Returns the name set by setPortName(). */ QString QextSerialPort::portName() const { return port; } /*! Reads all available data from the device, and returns it as a QByteArray. This function has no way of reporting errors; returning an empty QByteArray() can mean either that no data was currently available for reading, or that an error occurred. */ QByteArray QextSerialPort::readAll() { int avail = this->bytesAvailable(); return (avail > 0) ? this->read(avail) : QByteArray(); } /*! Returns the baud rate of the serial port. For a list of possible return values see the definition of the enum BaudRateType. */ BaudRateType QextSerialPort::baudRate(void) const { return Settings.BaudRate; } /*! Returns the number of data bits used by the port. For a list of possible values returned by this function, see the definition of the enum DataBitsType. */ DataBitsType QextSerialPort::dataBits() const { return Settings.DataBits; } /*! Returns the type of parity used by the port. For a list of possible values returned by this function, see the definition of the enum ParityType. */ ParityType QextSerialPort::parity() const { return Settings.Parity; } /*! Returns the number of stop bits used by the port. For a list of possible return values, see the definition of the enum StopBitsType. */ StopBitsType QextSerialPort::stopBits() const { return Settings.StopBits; } /*! Returns the type of flow control used by the port. For a list of possible values returned by this function, see the definition of the enum FlowType. */ FlowType QextSerialPort::flowControl() const { return Settings.FlowControl; } /*! Returns true if device is sequential, otherwise returns false. Serial port is sequential device so this function always returns true. Check QIODevice::isSequential() documentation for more information. */ bool QextSerialPort::isSequential() const { return true; } /*! Sets the port settigns. */ void QextSerialPort::setPortSetting(const PortSettings& settings) { setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setParity(settings.Parity); setStopBits(settings.StopBits); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Millisec); } /*! Returns the current setting of the port. */ PortSettings QextSerialPort::portSetting() const { return Settings; } QString QextSerialPort::errorString() { #ifdef Q_OS_WIN LPTSTR lpMsgBuf = 0; DWORD ret = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, 0); #ifdef UNICODE QString res = QString::fromWCharArray( (LPTSTR)lpMsgBuf); #else QString res = QString::fromLocal8Bit((LPTSTR) lpMsgBuf); #endif res.remove(QChar('\n')); LocalFree(lpMsgBuf); (void)ret; return res; #endif switch(lastErr) { case E_NO_ERROR: return "No Error has occurred"; case E_INVALID_FD: return "Invalid file descriptor (port was not opened correctly)"; case E_NO_MEMORY: return "Unable to allocate memory tables (POSIX)"; case E_CAUGHT_NON_BLOCKED_SIGNAL: return "Caught a non-blocked signal (POSIX)"; case E_PORT_TIMEOUT: return "Operation timed out (POSIX)"; case E_INVALID_DEVICE: return "The file opened by the port is not a valid device"; case E_BREAK_CONDITION: return "The port detected a break condition"; case E_FRAMING_ERROR: return "The port detected a framing error (usually caused by incorrect baud rate settings)"; case E_IO_ERROR: return "There was an I/O error while communicating with the port"; case E_BUFFER_OVERRUN: return "Character buffer overrun"; case E_RECEIVE_OVERFLOW: return "Receive buffer overflow"; case E_RECEIVE_PARITY_ERROR: return "The port detected a parity error in the received data"; case E_TRANSMIT_OVERFLOW: return "Transmit buffer overflow"; case E_READ_FAILED: return "General read operation failure"; case E_WRITE_FAILED: return "General write operation failure"; case E_FILE_NOT_FOUND: return "The "+this->portName()+" file doesn't exists"; default: return QString("Unknown error: %1").arg(lastErr); } } /*! Standard destructor. */ QextSerialPort::~QextSerialPort() { if (isOpen()) { close(); } platformSpecificDestruct(); delete mutex; }
29.331058
131
0.711659
[ "object" ]
10ce18eb1455dd3c697b6608a8397c853829a411
2,455
cpp
C++
leetcode/zigzagLevelOrder.cpp
jcpince/algorithms
c43dd8e98a0f0df691ead5f25c2c17a9241db908
[ "MIT" ]
null
null
null
leetcode/zigzagLevelOrder.cpp
jcpince/algorithms
c43dd8e98a0f0df691ead5f25c2c17a9241db908
[ "MIT" ]
null
null
null
leetcode/zigzagLevelOrder.cpp
jcpince/algorithms
c43dd8e98a0f0df691ead5f25c2c17a9241db908
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { if (!root) return {}; vector<vector<int>> result = {}; vector<TreeNode*> v1 = {root}, v2, *to_visit = &v1, *next_to_visit = &v2; bool zig = true; vector<int> level; while(to_visit->size()) { for (int idx = 0 ; idx < to_visit->size() ; idx++) { size_t level_index = zig ? idx : to_visit->size() - idx - 1; TreeNode *n = (*to_visit)[idx]; level.push_back((*to_visit)[level_index]->val); if (n->left) next_to_visit->push_back(n->left); if (n->right) next_to_visit->push_back(n->right); } result.push_back(level); level.clear(); /*swap*/ vector<TreeNode*> *tmp = to_visit; to_visit->erase(to_visit->begin(), to_visit->end()); to_visit = next_to_visit; next_to_visit = tmp; zig = !zig; } return result; } }; class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { if (!root) return {}; vector<vector<int>> result = {}; vector<TreeNode*> v1 = {root}, v2, *to_visit = &v1, *next_to_visit = &v2; bool zig = true; while(to_visit->size()) { vector<int> level(2 * to_visit->size()); int level_index = zig ? 0 : 2 * to_visit->size() - 1; for (TreeNode *n : *to_visit) { if (zig) level[level_index++] = n->val; else level[level_index--] = n->val; if (n->left) next_to_visit->push_back(n->left); if (n->right) next_to_visit->push_back(n->right); } if (zig) result.push_back(vector<int>(level.begin(), level.begin()+level_index)); else result.push_back(vector<int>(level.begin()+level_index+1, level.end())); /*swap*/ vector<TreeNode*> *tmp = to_visit; to_visit->erase(to_visit->begin(), to_visit->end()); to_visit = next_to_visit; next_to_visit = tmp; zig = !zig; } return result; } };
31.883117
93
0.505499
[ "vector" ]
10cece643ff42489e8a0413ea46ec84b05f1c53a
23,711
cc
C++
test/paxos_impl_test.cc
dengoswei/cpaxos
bccad547e7ea80d953fa495199f15680b1c555a6
[ "Apache-2.0" ]
6
2015-09-09T15:30:17.000Z
2021-03-29T20:11:54.000Z
test/paxos_impl_test.cc
dengoswei/cpaxos
bccad547e7ea80d953fa495199f15680b1c555a6
[ "Apache-2.0" ]
null
null
null
test/paxos_impl_test.cc
dengoswei/cpaxos
bccad547e7ea80d953fa495199f15680b1c555a6
[ "Apache-2.0" ]
null
null
null
#include <deque> #include "gtest/gtest.h" #include "paxos.pb.h" #include "test_helper.h" #include "paxos_instance.h" #include "paxos_impl.h" #include "mem_utils.h" #include "hassert.h" #include "log_utils.h" #include "random_utils.h" #include "id_utils.h" using namespace std; using namespace paxos; using namespace test; using cutils::RandomStrGen; using cutils::prop_num_compose; TEST(PaxosImplTest, SimpleConstruct) { auto logid = LOGID; auto group_ids = GROUP_IDS; auto selfid = 1ull; assert(group_ids.end() != group_ids.find(selfid)); auto paxos = cutils::make_unique<PaxosImpl>(logid, selfid, group_ids); assert(nullptr != paxos); assert(paxos->GetSelfId() == selfid); assert(paxos->GetLogId() == logid); assert(0ull == paxos->GetCommitedIndex()); assert(0ull == paxos->GetMaxIndex()); } TEST(PaxosImplTest, SimplePropose) { auto logid = LOGID; auto group_ids = GROUP_IDS; auto map_paxos = build_paxos(logid, group_ids); assert(map_paxos.size() == group_ids.size()); auto selfid = 1ull; auto& paxos = map_paxos[selfid]; assert(nullptr != paxos); std::string prop_value; vector<unique_ptr<Message>> vec_msg; // 1. prop { auto prop_index = paxos->NextProposingIndex(); assert(1ull == prop_index); auto prop_msg = buildMsgProp(logid, selfid, prop_index); assert(nullptr != prop_msg); prop_value = prop_msg->accepted_value().data(); assert(false == prop_value.empty()); assert(selfid == prop_msg->to()); auto rsp_msg_type = Step(*paxos, *prop_msg, nullptr); assert(MessageType::PROP == rsp_msg_type); { assert(prop_msg->index() == paxos->GetMaxIndex()); auto ins = paxos->GetInstance(prop_msg->index(), false); assert(nullptr != ins); assert(true == ins->GetStrictPropFlag()); assert(PropState::WAIT_PREPARE == ins->GetPropState()); } vec_msg = ProduceRsp(*paxos, *prop_msg, rsp_msg_type, nullptr); assert(vec_msg.size() == group_ids.size() - 1); for (auto& rsp_msg : vec_msg) { assert(nullptr != rsp_msg); assert(MessageType::PROP == rsp_msg->type()); assert(selfid == rsp_msg->from()); assert(logid == rsp_msg->logid()); assert(prop_msg->index() == rsp_msg->index()); assert(0ull < rsp_msg->proposed_num()); } } // 2. send prop to peers { vec_msg = apply(map_paxos, vec_msg, 0, 0); assert(vec_msg.size() == group_ids.size() - 1); for (auto& rsp_msg : vec_msg) { assert(nullptr != rsp_msg); assert(MessageType::PROP_RSP == rsp_msg->type()); assert(selfid == rsp_msg->to()); assert(logid == rsp_msg->logid()); assert(0ull < rsp_msg->proposed_num()); assert(rsp_msg->proposed_num() == rsp_msg->promised_num()); assert(0ull == rsp_msg->accepted_num()); assert(0ull < rsp_msg->index()); { auto& peer_paxos = map_paxos[rsp_msg->from()]; assert(nullptr != peer_paxos); auto ins = peer_paxos->GetInstance( rsp_msg->index(), false); assert(nullptr != ins); assert(false == ins->GetStrictPropFlag()); assert(ins->GetPromisedNum() == rsp_msg->promised_num()); } } } // 3. peers send prop rsp back to selfid { vec_msg = apply(map_paxos, vec_msg, 0, 0); hassert(vec_msg.size() == group_ids.size() - 1, "vec_msg.size %zu group_ids.size %zu", vec_msg.size(), group_ids.size()); { auto index = paxos->GetMaxIndex(); // check selfid stat auto ins = paxos->GetInstance(index, false); assert(nullptr != ins); assert(true == ins->GetStrictPropFlag()); assert(PropState::WAIT_ACCEPT == ins->GetPropState()); } for (auto& rsp_msg : vec_msg) { assert(nullptr != rsp_msg); assert(MessageType::ACCPT == rsp_msg->type()); assert(selfid == rsp_msg->from()); assert(logid == rsp_msg->logid()); assert(0ull < rsp_msg->proposed_num()); } } // 4. selfid send accpt to peers { vec_msg = apply(map_paxos, vec_msg, 0, 0); assert(vec_msg.size() == group_ids.size() - 1); for (auto& rsp_msg : vec_msg) { assert(nullptr != rsp_msg); assert(MessageType::ACCPT_RSP == rsp_msg->type()); assert(0ull < rsp_msg->proposed_num()); assert(rsp_msg->proposed_num() == rsp_msg->accepted_num()); { auto& peer_paxos = map_paxos[rsp_msg->from()]; assert(nullptr != peer_paxos); auto ins = peer_paxos->GetInstance(rsp_msg->index(), false); assert(nullptr != ins); assert(false == ins->GetStrictPropFlag()); assert(ins->GetAcceptedNum() == rsp_msg->accepted_num()); assert(prop_value == ins->GetAcceptedValue().data()); } } } // 5. peers send accpt_rsp to selfid { vec_msg = apply(map_paxos, vec_msg, 0, 0); assert(false == vec_msg.empty()); { assert(paxos->GetCommitedIndex() == paxos->GetMaxIndex()); auto index = paxos->GetMaxIndex(); auto ins = paxos->GetInstance(index, false); assert(nullptr != ins); assert(true == ins->GetStrictPropFlag()); assert(PropState::CHOSEN == ins->GetPropState()); assert(true == paxos->IsChosen(index)); } for (auto& rsp_msg : vec_msg) { assert(nullptr != rsp_msg); assert(MessageType::CHOSEN == rsp_msg->type()); assert(0ull < rsp_msg->accepted_num()); } } // 7. selfid send chosen to peers { vec_msg = apply(map_paxos, vec_msg, 0, 0); assert(true == vec_msg.empty()); auto index = paxos->GetCommitedIndex(); assert(paxos->GetMaxIndex() == index); for (auto id : group_ids) { auto& peer_paxos = map_paxos[id]; assert(nullptr != peer_paxos); assert(peer_paxos->GetMaxIndex() == peer_paxos->GetCommitedIndex()); assert(index == peer_paxos->GetCommitedIndex()); auto ins = peer_paxos->GetInstance(index, false); assert(nullptr != ins); assert((selfid == id) == ins->GetStrictPropFlag()); assert(ins->GetAcceptedValue().data() == prop_value); assert(PropState::CHOSEN == ins->GetPropState()); assert(true == peer_paxos->IsChosen(index)); } } } TEST(PaxosImplTest, FastProp) { auto logid = LOGID; auto group_ids = GROUP_IDS; auto map_paxos = build_paxos(logid, group_ids); assert(map_paxos.size() == group_ids.size()); auto selfid = 1ull; auto& paxos = map_paxos[selfid]; assert(nullptr != paxos); vector<unique_ptr<Message>> vec_msg; // 1. first prop { auto prop_index = paxos->NextProposingIndex(); assert(1ull == prop_index); auto prop_msg = buildMsgProp(logid, selfid, prop_index); assert(nullptr != prop_msg); assert(false == paxos->CanFastProp(prop_msg->index())); vec_msg.emplace_back(move(prop_msg)); apply_until(map_paxos, move(vec_msg), 0, 0); for (const auto& id_paxos : map_paxos) { const auto& peer_paxos = id_paxos.second; assert(nullptr != peer_paxos); assert(peer_paxos->GetCommitedIndex() == peer_paxos->GetMaxIndex()); assert(peer_paxos->GetCommitedIndex() == prop_index); assert(true == peer_paxos->IsChosen(prop_index)); } } // 2. fast prop : repeat test for (int i = 0; i < 10; ++i) { assert(true == vec_msg.empty()); // 2.1 selfid fast accept to peers auto prop_index = paxos->NextProposingIndex(); assert(1ull < prop_index); assert(true == paxos->CanFastProp(prop_index)); { auto prop_msg = buildMsgProp(logid, selfid, prop_index); assert(nullptr != prop_msg); prop_msg->set_type(MessageType::BEGIN_FAST_PROP); vec_msg.emplace_back(move(prop_msg)); vec_msg = apply(map_paxos, vec_msg, 0, 0); assert(vec_msg.size() == group_ids.size() - 1); for (auto& rsp_msg : vec_msg) { assert(nullptr != rsp_msg); assert(selfid == rsp_msg->from()); assert(MessageType::FAST_ACCPT == rsp_msg->type()); assert(prop_index == rsp_msg->index()); assert(0ull < rsp_msg->proposed_num()); } { auto ins = paxos->GetInstance(prop_index, false); assert(nullptr != ins); assert(true == ins->GetStrictPropFlag()); } } // 2.2 peers recv fast accept, send back fast accpt rsp { vec_msg = apply(map_paxos, vec_msg, 0, 0); assert(vec_msg.size() == group_ids.size() - 1); for (auto& rsp_msg : vec_msg) { assert(nullptr != rsp_msg); assert(selfid == rsp_msg->to()); assert(MessageType::FAST_ACCPT_RSP == rsp_msg->type()); assert(0ull < rsp_msg->proposed_num()); { auto& peer_paxos = map_paxos[rsp_msg->from()]; assert(nullptr != peer_paxos); auto ins = peer_paxos->GetInstance( rsp_msg->index(), false); assert(nullptr != ins); assert(false == ins->GetStrictPropFlag()); } } } // 2.3 self recv fast accpt rsp, mark ins as chosen(broad-cast) { vec_msg = apply(map_paxos, vec_msg, 0, 0); assert(false == vec_msg.empty()); { auto ins = paxos->GetInstance(prop_index, false); assert(nullptr != ins); assert(true == ins->GetStrictPropFlag()); assert(PropState::CHOSEN == ins->GetPropState()); assert(true == paxos->IsChosen(prop_index)); assert(paxos->GetCommitedIndex() == prop_index); assert(paxos->GetCommitedIndex() == paxos->GetMaxIndex()); } for (auto& rsp_msg : vec_msg) { assert(nullptr != rsp_msg); assert(MessageType::CHOSEN == rsp_msg->type()); assert(0ull < rsp_msg->accepted_num()); } } // 2.4 peers recv chosen { vec_msg = apply(map_paxos, vec_msg, 0, 0); assert(true == vec_msg.empty()); for (auto id : group_ids) { auto& peer_paxos = map_paxos[id]; assert(nullptr != peer_paxos); assert(peer_paxos->GetMaxIndex() == peer_paxos->GetCommitedIndex()); assert(prop_index == peer_paxos->GetCommitedIndex()); auto ins = peer_paxos->GetInstance(prop_index, false); assert(nullptr != ins); assert((selfid == id) == ins->GetStrictPropFlag()); assert(PropState::CHOSEN == ins->GetPropState()); assert(true == peer_paxos->IsChosen(prop_index)); } } } // 3. end fast accpt auto peer_id = 2ull; assert(peer_id != selfid); auto& peer_paxos = map_paxos[peer_id]; assert(nullptr != peer_paxos); assert(true == vec_msg.empty()); { auto prop_index = peer_paxos->NextProposingIndex(); assert(0ull < prop_index); assert(true == paxos->CanFastProp(prop_index)); assert(false == peer_paxos->CanFastProp(prop_index)); auto prop_msg = buildMsgProp(logid, peer_id, prop_index); assert(nullptr != prop_msg); vec_msg.emplace_back(move(prop_msg)); // 1. { vec_msg = apply(map_paxos, vec_msg, 0, 0); assert(vec_msg.size() == group_ids.size() - 1); { auto ins = peer_paxos->GetInstance(prop_index, false); assert(nullptr != ins); assert(true == ins->GetStrictPropFlag()); } } apply_until(map_paxos, move(vec_msg), 0, 0); for (const auto& id_paxos : map_paxos) { auto& other_paxos = id_paxos.second; assert(nullptr != other_paxos); assert(prop_index == other_paxos->GetCommitedIndex()); assert(true == other_paxos->IsChosen(prop_index)); logdebug("id %" PRIu64 " prop_index %" PRIu64 " can fast prop %d", id_paxos.first, prop_index, other_paxos->CanFastProp(prop_index)); assert((peer_id == id_paxos.first) == other_paxos->CanFastProp(prop_index + 1ull)); } assert(true == peer_paxos->CanFastProp(prop_index + 1ull)); assert(false == paxos->CanFastProp(prop_index + 1ull)); } } TEST(PaxosImplTest, RandomIterPropose) { auto logid = LOGID; auto group_ids = GROUP_IDS; auto map_paxos = build_paxos(logid, group_ids); assert(map_paxos.size() == group_ids.size()); for (auto i = 0; i < 10; ++i) { auto prop_id = i % (group_ids.size()) + 1ull; assert(0 < prop_id); auto& paxos = map_paxos[prop_id]; assert(nullptr != paxos); auto prop_index = paxos->NextProposingIndex(); assert(0ull < prop_index); assert(false == paxos->CanFastProp(prop_index)); for (auto count = 0; count < 3; ++count) { prop_index = paxos->NextProposingIndex(); assert(0ull < prop_index); vector<unique_ptr<Message>> vec_msg; vec_msg.emplace_back(buildMsgProp(logid, prop_id, prop_index)); apply_until(map_paxos, move(vec_msg), 0, 0); } prop_index = paxos->NextProposingIndex(); for (auto id : group_ids) { auto& peer_paxos = map_paxos[id]; assert(nullptr != peer_paxos); assert(peer_paxos->GetCommitedIndex() == peer_paxos->GetMaxIndex()); assert((prop_id == id) == peer_paxos->CanFastProp(prop_index)); } } } TEST(PaxosImplTest, LiveLock) { auto logid = LOGID; auto group_ids = GROUP_IDS; auto map_paxos = build_paxos(logid, group_ids); assert(map_paxos.size() == group_ids.size()); uint64_t prop_index = map_paxos[1ull]->NextProposingIndex(); assert(0ull < prop_index); map<uint64_t, vector<unique_ptr<Message>>> map_msg; // 1. begin propose for (auto id : group_ids) { auto& paxos = map_paxos[id]; assert(nullptr != paxos); auto prop_msg = buildMsgProp(logid, id, prop_index); assert(nullptr != prop_msg); map_msg[id].emplace_back(move(prop_msg)); // apply begin prop; produce prop auto vec_msg = apply(map_paxos, map_msg[id], 0, 0); map_msg[id].swap(vec_msg); } // 2. iter apply map_msg for (int i = 0; i < 30; ++i) { for (auto id : group_ids) { assert(false == map_msg[id].empty()); auto vec_msg = apply(map_paxos, map_msg[id], 0, 0); logdebug("LIVE LOCK id %" PRIu64 " map_msg[id].size %zu vec_msg.size %zu", id, map_msg[id].size(), vec_msg.size()); for (auto& rsp_msg : vec_msg) { logdebug("INFO from %" PRIu64 " to %" PRIu64 " proposed_num %" PRIu64 " promised_num %" PRIu64 " msg_type %d", rsp_msg->from(), rsp_msg->to(), rsp_msg->proposed_num(), rsp_msg->promised_num(), static_cast<int>(rsp_msg->type())); } assert(false == vec_msg.empty()); vec_msg = apply(map_paxos, vec_msg, 0, 0); logdebug("LIVE LOCK id %" PRIu64 " map_msg[id].size %zu vec_msg.size %zu", id, map_msg[id].size(), vec_msg.size()); for (auto& rsp_msg : vec_msg) { logdebug("INFO from %" PRIu64 " to %" PRIu64 " proposed_num %" PRIu64 " promised_num %" PRIu64 " msg_type %d", rsp_msg->from(), rsp_msg->to(), rsp_msg->proposed_num(), rsp_msg->promised_num(), static_cast<int>(rsp_msg->type())); } assert(false == vec_msg.empty()); map_msg[id].swap(vec_msg); } } // 3. prop_index still not chosen for (auto id : group_ids) { auto& paxos = map_paxos[id]; assert(nullptr != paxos); assert(false == paxos->IsChosen(prop_index)); assert(paxos->GetMaxIndex() == prop_index); assert(paxos->GetCommitedIndex() < paxos->GetMaxIndex()); } } TEST(PaxosImplTest, PropTestWithMsgDrop) { auto logid = LOGID; auto group_ids = GROUP_IDS; auto map_paxos = build_paxos(logid, group_ids); assert(map_paxos.size() == group_ids.size()); auto selfid = 1ull; auto& paxos = map_paxos[selfid]; assert(nullptr != paxos); // test times const int drop_ratio = 40; for (int i = 0; i < 30; ++i) { string prop_value; vector<unique_ptr<Message>> vec_msg; auto prop_index = paxos->NextProposingIndex(); assert(0ull < prop_index); // 1. prop with msg drop ratio 40 + i auto prop_msg = buildMsgProp(logid, selfid, prop_index); assert(nullptr != prop_msg); prop_value = prop_msg->accepted_value().data(); vec_msg.emplace_back(move(prop_msg)); auto iter_drop_ratio = min(drop_ratio + i, 70); auto iter_count = 0; while (true) { ++iter_count; apply_until(map_paxos, move(vec_msg), 10, iter_drop_ratio); if (paxos->IsChosen(prop_index)) { break; } auto peer_id = 2ull; assert(peer_id != selfid); prop_msg = buildMsgProp(logid, peer_id, prop_index); assert(nullptr != prop_msg); prop_msg->set_type(MessageType::TRY_PROP); assert(true == vec_msg.empty()); vec_msg.emplace_back(move(prop_msg)); } auto ins = paxos->GetInstance(prop_index, false); assert(nullptr != ins); if (false == ins->GetAcceptedValue().data().empty()) { assert(prop_value == ins->GetAcceptedValue().data()); } logdebug("DROP TEST prop_index %" PRIu64 " iter_count %d" " accepted_value.size %zu prop_value.size %zu", prop_index, iter_count, ins->GetAcceptedValue().data().size(), prop_value.size()); for (auto id : group_ids) { auto& peer_paxos = map_paxos[id]; assert(nullptr != peer_paxos); if (true == peer_paxos->IsChosen(prop_index)) { continue; } while (false == peer_paxos->IsChosen(prop_index)) { prop_msg = buildMsgProp(logid, id, prop_index); assert(nullptr != prop_msg); prop_msg->set_type(MessageType::TRY_PROP); vec_msg.clear(); vec_msg.emplace_back(move(prop_msg)); apply_until(map_paxos, move(vec_msg), 10, iter_drop_ratio); } } } } TEST(PaxosImplTest, SimpleHSDeque) { auto logid = LOGID; auto group_ids = GROUP_IDS; auto selfid = 1ull; deque<unique_ptr<HardState>> hs_deque; auto paxos = cutils::make_unique<PaxosImpl>(logid, selfid, group_ids, hs_deque, true); assert(nullptr != paxos); assert(0ull == paxos->GetMaxIndex()); assert(0ull == paxos->GetCommitedIndex()); assert(selfid == paxos->GetSelfId()); assert(LOGID == paxos->GetLogId()); assert(group_ids == paxos->GetGroupIds()); } TEST(PaxosImplTest, HSDequeConstructTest) { auto logid = LOGID; auto group_ids = GROUP_IDS; auto selfid = 1ull; auto test_index = 10ull; RandomStrGen<10, 50> tRGen; deque<unique_ptr<HardState>> hs_deque; for (uint64_t index = 2ull; index <= test_index; ++index) { auto hs = cutils::make_unique<HardState>(); hs->set_index(index); hs->set_logid(logid); hs->set_proposed_num( prop_num_compose(static_cast<uint8_t>(selfid), 0ull)); hs->set_promised_num(hs->proposed_num()); hs->set_accepted_num(hs->proposed_num()); hs->set_seq(1ull); { auto entry = hs->mutable_accepted_value(); assert(nullptr != entry); entry->set_type(paxos::EntryType::EntryNormal); entry->set_data(tRGen.Next()); } hs_deque.push_back(move(hs)); assert(nullptr == hs); } // case 1 { auto paxos = cutils::make_unique<PaxosImpl>( logid, selfid, group_ids, hs_deque, false); assert(nullptr != paxos); assert(test_index == paxos->GetMaxIndex()); assert(test_index-1 == paxos->GetCommitedIndex()); assert(nullptr == paxos->GetInstance(hs_deque.front()->index()-1, false)); for (auto& hs : hs_deque) { assert(nullptr != hs); auto ins = paxos->GetInstance(hs->index(), false); assert(nullptr != ins); assert((hs->index() != test_index) == ins->IsChosen()); assert(0 == ins->GetPendingSeq()); assert(hs->proposed_num() == ins->GetProposeNum()); assert(hs->promised_num() == ins->GetPromisedNum()); assert(hs->accepted_num() == ins->GetAcceptedNum()); assert(true == hs->has_accepted_value()); assert(hs->accepted_value().type() == ins->GetAcceptedValue().type()); assert(hs->accepted_value().data() == ins->GetAcceptedValue().data()); } assert(nullptr == paxos->GetInstance(test_index+1, false)); } // case 2 { auto paxos = cutils::make_unique<PaxosImpl>( logid, selfid, group_ids, hs_deque, true); assert(nullptr != paxos); assert(test_index == paxos->GetMaxIndex()); assert(test_index == paxos->GetCommitedIndex()); assert(nullptr == paxos->GetInstance(hs_deque.front()->index()-1, false)); for (auto& hs : hs_deque) { assert(nullptr != hs); auto ins = paxos->GetInstance(hs->index(), false); assert(nullptr != ins); assert(true == ins->IsChosen()); assert(0 == ins->GetPendingSeq()); assert(hs->proposed_num() == ins->GetProposeNum()); assert(hs->promised_num() == ins->GetPromisedNum()); assert(hs->accepted_num() == ins->GetAcceptedNum()); assert(true == hs->has_accepted_value()); assert(hs->accepted_value().type() == ins->GetAcceptedValue().type()); assert(hs->accepted_value().data() == ins->GetAcceptedValue().data()); } assert(nullptr == paxos->GetInstance(test_index+1, false)); } }
36.422427
90
0.548311
[ "vector" ]
10d1b45a625d9eae32d73249b39366e7f1efd25c
10,804
hpp
C++
include/Manifold.hpp
sdmg15/CDT-plusplus
13071b61677e0c1db077f252dcab25ea672bbe9d
[ "BSD-3-Clause" ]
1
2019-10-05T10:58:34.000Z
2019-10-05T10:58:34.000Z
include/Manifold.hpp
sdmg15/CDT-plusplus
13071b61677e0c1db077f252dcab25ea672bbe9d
[ "BSD-3-Clause" ]
null
null
null
include/Manifold.hpp
sdmg15/CDT-plusplus
13071b61677e0c1db077f252dcab25ea672bbe9d
[ "BSD-3-Clause" ]
1
2020-07-13T03:39:34.000Z
2020-07-13T03:39:34.000Z
/// Causal Dynamical Triangulations in C++ using CGAL /// /// Copyright © 2018-2019 Adam Getchell /// /// Simplicial Manifold data structures /// /// @file Manifold.hpp /// @brief Data structures for manifolds /// @author Adam Getchell #ifndef CDT_PLUSPLUS_MANIFOLD_HPP #define CDT_PLUSPLUS_MANIFOLD_HPP #include "Foliated_triangulation.hpp" #include "Geometry.hpp" #include <cstddef> #include <functional> #include <unordered_set> #include <utility> /// Manifold class template /// @tparam dimension Dimensionality of manifold template <size_t dimension> class Manifold; /// 3D Manifold template <> class Manifold<3> { public: /// @brief Default ctor Manifold() = default; /// @brief Construct manifold from a Delaunay triangulation /// Pass-by-value-then-move /// @param delaunay_triangulation Triangulation used to construct manifold explicit Manifold(Delaunay3 delaunay_triangulation) : triangulation_{FoliatedTriangulation3( std::move(delaunay_triangulation))} , geometry_{get_triangulation()} {} /// @brief Construct manifold from a Foliated triangulation /// Pass-by-value-then-move /// @param foliated_triangulation Triangulation used to construct manifold explicit Manifold(FoliatedTriangulation3 foliated_triangulation) : triangulation_{std::move(foliated_triangulation)} , geometry_{get_triangulation()} {} /// @brief Construct manifold using arguments /// @param desired_simplices Number of desired simplices /// @param desired_timeslices Number of desired timeslices Manifold(int_fast32_t desired_simplices, int_fast32_t desired_timeslices) : triangulation_{FoliatedTriangulation3(desired_simplices, desired_timeslices)} , geometry_{get_triangulation()} {} /// @brief Construct manifold using arguments /// @param desired_simplices Number of desired simplices /// @param desired_timeslices Number of desired timeslices /// @param initial_radius Radius of first timeslice /// @param radial_factor Radial separation between timeslices Manifold(int_fast32_t desired_simplices, int_fast32_t desired_timeslices, double initial_radius, double radial_factor) : triangulation_{FoliatedTriangulation3(desired_simplices, desired_timeslices, initial_radius, radial_factor)} , geometry_{get_triangulation()} {} // /// @brief Construct Geometry data from a triangulation // /// @tparam Triangulation Type of triangulation // /// @param triangulation The triangulation to use // /// @return The geometry data of the triangulation // template <typename Triangulation> // [[nodiscard]] Geometry3 make_geometry(Triangulation&& triangulation) // try // { //#ifndef NDEBUG // std::cout << __PRETTY_FUNCTION__ << " called.\n"; //#endif // // Geometry3 geom{std::forward<Triangulation>(triangulation)}; // return geom; // } // catch (std::exception const& e) // { // std::cerr << "make_geometry() failed: " << e.what() << "\n"; // throw; // // std::cout << "Try again to make geometry ...\n"; // // this->update_geometry(); // } /// @brief Update the Manifold data structures void update() try { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << " called.\n"; #endif triangulation_.update(); update_geometry(); } catch (std::exception const& ex) { std::cout << "Exception thrown:\n" << ex.what() << "\n"; } /// @brief Update geometry data of the manifold when the triangulation has /// been changed /// /// Defined here because Geometry depends on FoliatedTriangulation void update_geometry() try { #ifndef NDEBUG std::cout << __PRETTY_FUNCTION__ << " called.\n"; #endif Geometry3 geom(triangulation_); geometry_ = geom; // geometry_ = make_geometry(triangulation_); } catch (std::exception const& ex) { std::cout << "Exception thrown:\n" << ex.what() << "\n"; } /// @return A read-only reference to the triangulation [[nodiscard]] FoliatedTriangulation3 const& get_triangulation() const { return triangulation_; } /// @return A mutable reference to the triangulation [[nodiscard]] auto& triangulation() { return triangulation_; } /// @return A read-only reference to the Geometry [[nodiscard]] Geometry3 const& get_geometry() const { return geometry_; } /// @param cells /// @return All of the vertices contained in the cells [[nodiscard]] auto get_vertices_from_cells( std::vector<Cell_handle> const& cells) const { std::unordered_set<Vertex_handle> vertices; for (auto& cell : cells) { for (int j = 0; j < 4; ++j) { vertices.emplace(cell->vertex(j)); } } std::vector<Vertex_handle> result(vertices.begin(), vertices.end()); return result; } /// @return True if the Manifolds's triangulation is Delaunay [[nodiscard]] auto is_delaunay() const -> bool { return triangulation_.is_delaunay(); } /// @brief Forwarding to FoliatedTriangulation3.is_tds_valid() [[nodiscard]] auto is_valid() const -> bool { return triangulation_.is_tds_valid(); } /// @brief Forwarding to FoliatedTriangulation3.is_foliated() [[nodiscard]] auto is_foliated() const -> bool { return triangulation_.is_foliated(); } /// @brief Perfect forwarding to FoliatedTriangulation3.is_vertex() template <typename Vertex> [[nodiscard]] auto is_vertex(Vertex&& v_candidate) const -> bool { return triangulation_.get_delaunay().is_vertex( std::forward<Vertex>(v_candidate)); } /// @brief Forwarding to FoliatedTriangulation3.is_edge() [[nodiscard]] auto is_edge(Edge_handle const& e_candidate) const -> bool { return triangulation_.get_delaunay().tds().is_edge( e_candidate.first, e_candidate.second, e_candidate.third); } /// @return Dimensionality of triangulation data structure [[nodiscard]] auto dim() const { return triangulation_.dimension(); } /// @return Number of 3D simplices in geometry data structure [[nodiscard]] auto N3() const { return geometry_.N3; } /// @return Number of (3,1) simplices in geometry data structure [[nodiscard]] auto N3_31() const { return geometry_.N3_31; } /// @return Number of (2,2) simplices in geometry data structure [[nodiscard]] auto N3_22() const { return geometry_.N3_22; } /// @return Number of (1,3) simplices in geometry data structure [[nodiscard]] auto N3_13() const { return geometry_.N3_13; } /// @return Number of (3,1) and (1,3) simplices in geometry data structure [[nodiscard]] auto N3_31_13() const { return geometry_.N3_31_13; } /// @return Number of 3D simplices in triangulation data structure [[nodiscard]] auto simplices() const { return triangulation_.number_of_finite_cells(); } /// @return Number of 2D faces in geometry data structure [[nodiscard]] auto N2() const { return geometry_.N2; } /// @return An associative container of spacelike faces indexed by timevalue [[nodiscard]] auto const& N2_SL() const { return triangulation_.N2_SL(); } /// @return Number of 2D faces in triangulation data structure [[nodiscard]] auto faces() const { return triangulation_.number_of_finite_facets(); } /// @return Number of 1D edges in geometry data structure [[nodiscard]] auto N1() const { return geometry_.N1; } /// @return Number of spacelike edges in triangulation data structure [[nodiscard]] auto N1_SL() const { return triangulation_.N1_SL(); } /// @return Number of timelike edges in triangulation data structure [[nodiscard]] auto N1_TL() const { return triangulation_.N1_TL(); } /// @return Number of 1D edges in triangulation data structure [[nodiscard]] auto edges() const { return triangulation_.number_of_finite_edges(); } /// @return Number of vertices in geometry data structure [[nodiscard]] auto N0() const { return geometry_.N0; } /// @return Number of vertices in triangulation data structure [[nodiscard]] auto vertices() const { return triangulation_.number_of_vertices(); } /// @return Minimum time value in geometry data structure [[nodiscard]] auto min_time() const { return triangulation_.min_time(); } /// @return Maximum time value in geometry data structure [[nodiscard]] auto max_time() const { return triangulation_.max_time(); } /// @return True if all cells in geometry are classified and match number in /// triangulation [[nodiscard]] auto check_simplices() const -> bool { return (this->simplices() == this->N3() && triangulation_.check_cells(triangulation_.get_cells())); } /// @param simplices The container of simplices to check /// @return True if all vertices in the container have reasonable timevalues [[nodiscard]] auto are_vertex_timevalues_valid( std::vector<Cell_handle> const& simplices) const -> bool { auto check_vertices = get_vertices_from_cells(simplices); for (auto& vertex : check_vertices) { auto timevalue = vertex->info(); if (timevalue > max_time() || timevalue < min_time()) { return false; } } return true; } /// @param simplices The container of simplices to check /// @return True if all simplices in the container have valid types [[nodiscard]] auto are_simplex_types_valid( std::vector<Cell_handle> const& simplices) const -> bool { return triangulation_.check_cells(simplices); } /// @brief Perfect forwarding to FoliatedTriangulation3.degree() template <typename VertexHandle> [[nodiscard]] decltype(auto) degree(VertexHandle&& vh) const { return triangulation_.degree(std::forward<VertexHandle>(vh)); } /// @brief Perfect forwarding to FoliatedTriangulation3.incident_cells() template <typename... Ts> [[nodiscard]] decltype(auto) incident_cells(Ts&&... args) const { return triangulation_.incident_cells(std::forward<Ts>(args)...); } /// @brief Call to triangulation_.get_timelike_edges() [[nodiscard]] auto const& get_timelike_edges() const { return triangulation_.get_timelike_edges(); } /// @brief Call triangulation.get_spacelike_edges() [[nodiscard]] auto const& get_spacelike_edges() const { return triangulation_.get_spacelike_edges(); } /// @brief Call FoliatedTriangulation3.get_vertices() [[nodiscard]] auto const& get_vertices() const { return triangulation_.get_vertices(); } void print_volume_per_timeslice() const { triangulation_.print_volume_per_timeslice(); } private: FoliatedTriangulation3 triangulation_; Geometry3 geometry_; }; using Manifold3 = Manifold<3>; #endif // CDT_PLUSPLUS_MANIFOLD_HPP
32.739394
78
0.692892
[ "geometry", "vector", "3d" ]
10d46f8a003a57ff9bd504c5d952ff00bc532ba9
5,256
hpp
C++
Source/AllProjects/CQCWebSrv/Client/WebRIVACmp/WebRIVACmp_Data.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/CQCWebSrv/Client/WebRIVACmp/WebRIVACmp_Data.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/CQCWebSrv/Client/WebRIVACmp/WebRIVACmp_Data.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// ---------------------------------------------------------------------------- // FILE: WebRIVACmp_Data.hpp // DATE: Fri, Feb 12 21:14:15 2021 -0500 // // This file was generated by the Charmed Quark CIDIDL compiler. Do not make // changes by hand, because they will be lost if the file is regenerated. // ---------------------------------------------------------------------------- #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // ---------------------------------------------------------------------------- // Constants namespace // ---------------------------------------------------------------------------- namespace kWebRIVACmp { // ------------------------------------------------------------------------ // Some values we look for in the XML file we parse. // // ------------------------------------------------------------------------ const extern TString strAttrName; const extern TString strAttrDir; const extern TString strAttrDirBoth; const extern TString strAttrDirCS; const extern TString strAttrDirSC; const extern TString strAttrAName; const extern TString strAttrType; const extern TString strAttrVal; const extern TString strAttrEnumType; // ------------------------------------------------------------------------ // Some general values used in output generation // // ------------------------------------------------------------------------ const extern TString strVal_False; const extern TString strVal_True; const extern TString strVal_LineSep; const extern TString strVal_CommaFalse; const extern TString strVal_CommaTrue; } // ---------------------------------------------------------------------------- // Types namespace // ---------------------------------------------------------------------------- namespace tWebRIVACmp { // ------------------------------------------------------------------------ // A mapping enum for the types we support for constants. // // ------------------------------------------------------------------------ enum class EConstTypes { Boolean , Int1 , Int2 , Int4 , Int8 , Card1 , Card2 , Card4 , Card8 , Float8 , String , Count , Min = Boolean , Max = String }; [[nodiscard]] EConstTypes eXlatEConstTypes(const TString& strToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::False); [[nodiscard]] const TString& strXlatEConstTypes(const EConstTypes eToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::True); [[nodiscard]] const TString& strAltXlatEConstTypes(const EConstTypes eToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::True); [[nodiscard]] EConstTypes eAltXlatEConstTypes(const TString& strToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::False); [[nodiscard]] tCIDLib::TBoolean bIsValidEnum(const EConstTypes eVal); // ------------------------------------------------------------------------ // A mapping enum for the types we support for structure members. Some // are fundamental types and some are a set of common compound types // that are used in the protocol. // // We use the AltText2 for the actual C++ type, so that we don't have to // special case constantly which are tCIDLib:: prefixed fundamental types // and which are represented as objects on the C++ side. // // And we put all of the fundamental types first, and the object types // at the end. Int8 is the last regular fundamental type. After that are // some special cases, of which enum is the last. // // And then the object types come last. // // ------------------------------------------------------------------------ enum class EMemTypes { Boolean , Card1 , Card2 , Card4 , Card8 , Float8 , Int1 , Int2 , Int4 , Int8 , Opacity , Enum , AlphaColor , Area , Color , Point , Size , String , Passthrough , Count , Min = Boolean , Max = Passthrough , LastFundType = Int8 }; [[nodiscard]] EMemTypes eXlatEMemTypes(const TString& strToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::False); [[nodiscard]] const TString& strXlatEMemTypes(const EMemTypes eToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::True); [[nodiscard]] const TString& strAltXlatEMemTypes(const EMemTypes eToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::True); [[nodiscard]] EMemTypes eAltXlatEMemTypes(const TString& strToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::False); [[nodiscard]] const TString& strAltXlat2EMemTypes(const EMemTypes eToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::True); [[nodiscard]] EMemTypes eAltXlat2EMemTypes(const TString& strToXlat, const tCIDLib::TBoolean bThrowIfNot = kCIDLib::False); [[nodiscard]] tCIDLib::TBoolean bIsValidEnum(const EMemTypes eVal); } #pragma CIDLIB_POPPACK
39.518797
136
0.512747
[ "object" ]
10d7961abc065c908cbd93e5f0576da49e7d9913
3,634
cpp
C++
VulkanAbstractionLayer/ComputeShader.cpp
asc-community/VulkanAbstractionLayer
d020585654ec2168dbe5bdec6ec5ddc773f02700
[ "BSD-3-Clause" ]
16
2021-09-24T11:20:00.000Z
2022-03-10T16:28:27.000Z
VulkanAbstractionLayer/ComputeShader.cpp
MomoDeve/VulkanAbstractionLayer
d020585654ec2168dbe5bdec6ec5ddc773f02700
[ "BSD-3-Clause" ]
16
2021-06-25T22:18:06.000Z
2021-08-17T23:36:50.000Z
VulkanAbstractionLayer/ComputeShader.cpp
vkdev-team/VulkanAbstractionLayer
d020585654ec2168dbe5bdec6ec5ddc773f02700
[ "BSD-3-Clause" ]
1
2022-01-03T01:12:32.000Z
2022-01-03T01:12:32.000Z
// Copyright(c) 2021, #Momo // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met : // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and /or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "ComputeShader.h" #include "VulkanContext.h" namespace VulkanAbstractionLayer { ArrayView<const TypeSPIRV> ComputeShader::GetInputAttributes() const { return { }; } ArrayView<const ShaderUniforms> ComputeShader::GetShaderUniforms() const { return this->shaderUniforms; } const vk::ShaderModule& ComputeShader::GetNativeShader(ShaderType type) const { assert(type == ShaderType::COMPUTE); return this->computeShader; } void ComputeShader::Destroy() { auto& vulkan = GetCurrentVulkanContext(); auto& device = vulkan.GetDevice(); if ((bool)this->computeShader) device.destroyShaderModule(this->computeShader); this->computeShader = vk::ShaderModule{ }; } ComputeShader::ComputeShader(const ShaderData& computeData) { this->Init(computeData); } ComputeShader::~ComputeShader() { this->Destroy(); } void ComputeShader::Init(const ShaderData& computeData) { auto& vulkan = GetCurrentVulkanContext(); vk::ShaderModuleCreateInfo computeShaderInfo; computeShaderInfo.setCode(computeData.Bytecode); this->computeShader = vulkan.GetDevice().createShaderModule(computeShaderInfo); // TODO: support multiple descriptor sets assert(computeData.DescriptorSets.size() < 2); this->shaderUniforms = std::vector{ ShaderUniforms{ computeData.DescriptorSets[0], ShaderType::COMPUTE } }; } ComputeShader::ComputeShader(ComputeShader&& other) noexcept { this->computeShader = other.computeShader; this->shaderUniforms = std::move(other.shaderUniforms); other.computeShader = vk::ShaderModule{ }; } ComputeShader& ComputeShader::operator=(ComputeShader&& other) noexcept { this->Destroy(); this->computeShader = other.computeShader; this->shaderUniforms = std::move(other.shaderUniforms); other.computeShader = vk::ShaderModule{ }; return *this; } }
35.281553
87
0.707485
[ "vector" ]
10d85fba011025ac56b01eb6414e03b99b567195
2,840
cpp
C++
UVA/FrequentValues.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
UVA/FrequentValues.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
UVA/FrequentValues.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <stdio.h> #include <iostream> #include <vector> #include <algorithm> #include <stack> #include <queue> #include <math.h> #include <string.h> #define ll long long #define MAXN 100002 using namespace std; int n, q, a, b, v[MAXN], freq[MAXN], tree[MAXN*4]; void build(int idx, int l, int r){ if(l > r){ return; }else{ if(l == r){ tree[idx] = l; }else{ int mid = (l+r) >> 1; int gol = idx << 1; int gor = (idx << 1) + 1; build(gol, l, mid); build(gor, mid+1, r); int q1 = tree[gol]; int q2 = tree[gor]; if(freq[q1] <= freq[q2]){ tree[idx] = q2; }else{ tree[idx] = q1; } } } } int rmq(int idx, int x, int y, int bl, int br){ if(bl > y || br < x || x > y){ return -1; }else{ if(x == bl && y == br){ return tree[idx]; }else{ int mid = (x+y) >> 1; int gol = idx << 1; int gor = (idx << 1) + 1; int q1 = rmq(gol,x, mid, bl, min(br, mid)); int q2 = rmq(gor, mid+1, y, max(mid + 1, bl), br); if(q1 == -1){ return q2; }else if(q2 == -1){ return q1; }else{ if(freq[q1] <= freq[q2]){ return q2; }else{ return q1; } } } } } int main(void){ while(~scanf("%d", &n) && n){ scanf("%d", &q); scanf("%d", &v[0]); memset(freq,0,sizeof(freq)); freq[0] = 1; for(int i = 1; i < n; i++){ scanf("%d", &v[i]); if(v[i] == v[i-1]){ freq[i] = freq[i-1] + 1; }else{ freq[i] = 1; } } build(1, 0, n-1); for(int i = 0; i < q; i++){ scanf("%d%d", &a, &b); a--; b--; if(a > b){ swap(a,b); } int trueRange = rmq(1,0,n-1,a,b); //cout << trueRange << " " << a << " " << b << endl; if(a == 0 && b == n-1){ printf("%d\n", freq[trueRange]); }else if(v[a] == v[b]){ printf("%d\n", b-a+1); }else{ int v1 = 0; if(trueRange - freq[trueRange] < a){ v1 = trueRange - a + 1; }else{ v1 = freq[trueRange]; } int v2 = freq[rmq(1,0, n-1, trueRange+1, b)]; if(v2 > v1){ printf("%d\n", v2); }else{ printf("%d\n", v1); } } } } return 0; }
25.357143
64
0.335915
[ "vector" ]
10dad8dcf7bb15a736af42ea0b1d8aed5fb56dd1
2,776
cpp
C++
TAO/tests/Bug_2935_Regression/source.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tests/Bug_2935_Regression/source.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tests/Bug_2935_Regression/source.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
//$Id: source.cpp 82911 2008-10-02 19:02:17Z johnnyw $ # include "source_i.h" // A ThreeTier client that calls tick and/or tock const ACE_TCHAR * ior_input_file = 0; char input_ior[5000]; void eat_args (int & argc, ACE_TCHAR *argv[], int argp, int how_many) { for (int marg = argp; marg + how_many < argc; ++marg) { argv[marg] = argv[marg + how_many]; } argc -= how_many; } bool parse_args (int & argc, ACE_TCHAR *argv[]) { int argp = 1; while (argp < argc) { const ACE_TCHAR* arg = argv[argp]; if(arg[0] == '-' && arg[1] == 'f' && argp + 1 < argc) { if (ior_input_file != 0) { ACE_ERROR ((LM_DEBUG, "Sink (%P|%t) duplicate -f options\n")); return false; } // capture input file name // then remove it from arguemnt list ior_input_file = argv[argp + 1]; eat_args (argc, argv, argp, 2); } else { argp += 1; // just ignore unknown arguments } } if (ior_input_file == 0) { ACE_ERROR ((LM_DEBUG, "Sink (%P|%t) missing required -f option\n")); return false; } return true; } int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { int result = 0; ACE_DEBUG ((LM_DEBUG, "Source (%P|%t) started\n")); try { // Initialize the ORB. CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); // Initialize options based on command-line arguments. if (!parse_args (argc, argv)) { return -1; } FILE *input_file = ACE_OS::fopen (ior_input_file, "r"); if (input_file == 0) { ACE_ERROR_RETURN ((LM_ERROR, "Cannot open input IOR file: %s", ior_input_file), -1); } ACE_OS::fread (input_ior, 1, sizeof(input_ior), input_file); ACE_OS::fclose (input_file); // Convert the IOR to an object reference. CORBA::Object_var object = orb->string_to_object (input_ior); // narrow the object reference to a ThreeTier reference ThreeTier_var server = ThreeTier::_narrow (object.in ()); if (CORBA::is_nil (server.in ())) { ACE_ERROR_RETURN ((LM_ERROR, "IOR does not refer to a ThreeTier implementation"), -1); } Source_i source (server.in ()); result = source.run(); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); result = -1; } ACE_DEBUG ((LM_DEBUG, "Source (%P|%t) exits\n")); return result; }
24.785714
83
0.514409
[ "object" ]
10dd7438227b9f872505a477b9d0ce8d9269c8b2
851
cpp
C++
codeforces/1003C - Intense Heat.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
1
2018-12-25T23:55:19.000Z
2018-12-25T23:55:19.000Z
codeforces/1003C - Intense Heat.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
codeforces/1003C - Intense Heat.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
//============================================================================ // Problem : 1003C - Intense Heat // Category : Brute force //============================================================================ #include <bits/stdc++.h> using namespace std; typedef vector<int> vi; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n,k; vi v; while(cin >> n >> k) { v = vi(n); for(int i = 0; i < n; i++) cin >> v[i]; double ans = 0.0; for(int i = 0; i < n; i++) { int sum = 0; for(int j = i; j < n; j++) { sum += v[j]; if(j-i+1 >= k) ans = max(ans, 1.*sum/(j-i+1)); } } cout << fixed << setprecision(8) << ans << '\n'; } return 0; }
25.029412
78
0.319624
[ "vector" ]
10deeff46ba8d3b20e91620fe82de1627c97d1b5
612
cpp
C++
USACO/Bronze/Misc/LemonadeLine.cpp
polarr/competitive-programming
06e41fd72c785eb5621e20669d76ed99fafab901
[ "CC0-1.0" ]
1
2020-12-16T19:08:51.000Z
2020-12-16T19:08:51.000Z
USACO/Bronze/Misc/LemonadeLine.cpp
polarr/competitive-programming
06e41fd72c785eb5621e20669d76ed99fafab901
[ "CC0-1.0" ]
null
null
null
USACO/Bronze/Misc/LemonadeLine.cpp
polarr/competitive-programming
06e41fd72c785eb5621e20669d76ed99fafab901
[ "CC0-1.0" ]
null
null
null
/** Code by 1egend **/ // Problem: #include <bits/stdc++.h> using namespace std; #define pb push_back #define ull unsigned long long const int MAX_N = 1e5 + 1; const int MOD = 1e9 + 7; ifstream fin("lemonade.in"); ofstream fout("lemonade.out"); void solve(){ int x; fin >> x; vector <int> line; for (int i = 0; i < x; ++i){ int t; fin >> t; line.push_back(t); } sort(line.begin(), line.end()); for (int i = 0; i < x; ++i){ if (line[i] >= x - i - 1){ fout << x - i; break; } } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); solve(); return 0; }
16.105263
33
0.560458
[ "vector" ]
10e8e58ff5bfc4a5d6eed5aa2c0f33ea296a1953
44,615
cpp
C++
src/svgren/renderer.cpp
igagis/svgren
9eaa993992aa28aab6453d920adab281299f3dcc
[ "MIT" ]
133
2015-10-30T08:38:38.000Z
2020-11-12T09:08:29.000Z
src/svgren/renderer.cpp
igagis/svgren
9eaa993992aa28aab6453d920adab281299f3dcc
[ "MIT" ]
78
2016-02-15T12:12:44.000Z
2020-11-27T09:22:29.000Z
src/svgren/renderer.cpp
igagis/svgren
9eaa993992aa28aab6453d920adab281299f3dcc
[ "MIT" ]
34
2016-07-14T04:06:17.000Z
2020-11-28T01:33:35.000Z
/* The MIT License (MIT) Copyright (c) 2015-2021 Ivan Gagis <igagis@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* ================ LICENSE END ================ */ #include "renderer.hxx" #include <utki/math.hpp> #include <svgdom/elements/coordinate_units.hpp> #include "util.hxx" #include "config.hxx" #include "filter_applier.hxx" using namespace svgren; namespace{ const std::string fake_svg_element_tag = "fake_svg_element"; } real renderer::length_to_px(const svgdom::length& l)const noexcept{ if(l.is_percent()){ return this->viewport.x() * (l.value / 100); } return real(l.to_px(this->dpi)); } r4::vector2<real> renderer::length_to_px(const svgdom::length& x, const svgdom::length& y)const noexcept{ return r4::vector2<real>{ x.is_percent() ? (this->viewport.x() * (x.value / 100)) : x.to_px(this->dpi), y.is_percent() ? (this->viewport.y() * (y.value / 100)) : y.to_px(this->dpi) }; } void renderer::apply_transformation(const svgdom::transformable::transformation& t){ // TRACE(<< "renderer::applyCairoTransformation(): applying transformation " << unsigned(t.type) << std::endl) switch (t.type_) { case svgdom::transformable::transformation::type::translate: // TRACE(<< "translate x,y = (" << t.x << ", " << t.y << ")" << std::endl) this->canvas.translate(t.x, t.y); break; case svgdom::transformable::transformation::type::matrix: this->canvas.transform({ {t.a, t.c, t.e}, {t.b, t.d, t.f} }); break; case svgdom::transformable::transformation::type::scale: // TRACE(<< "scale transformation factors = (" << t.x << ", " << t.y << ")" << std::endl) this->canvas.scale(t.x, t.y); break; case svgdom::transformable::transformation::type::rotate: this->canvas.translate(t.x, t.y); this->canvas.rotate(deg_to_rad(t.angle)); this->canvas.translate(-t.x, -t.y); break; case svgdom::transformable::transformation::type::skewx: { using std::tan; this->canvas.transform({ { 1, tan(deg_to_rad(t.angle)), 0 }, { 0, 1, 0 } }); } break; case svgdom::transformable::transformation::type::skewy: { using std::tan; this->canvas.transform({ { 1, 0, 0 }, { tan(deg_to_rad(t.angle)), 1, 0 } }); } break; default: ASSERT(false) break; } #if SVGREN_BACKEND == SVGREN_BACKEND_CAIRO // WORKAROUND: Due to cairo/pixman bug https://bugs.freedesktop.org/show_bug.cgi?id=102966 // we have to limit the maximum value of matrix element by 16 bit integer (+-0x7fff). auto m = this->canvas.get_matrix(); for(auto& r : m){ using std::min; using std::max; const real max_value = 0x7fff; r = max(-max_value, min(r, max_value)); } this->canvas.set_matrix(m); #endif } void renderer::apply_transformations(const decltype(svgdom::transformable::transformations)& transformations){ for(auto& t : transformations){ this->apply_transformation(t); } } void renderer::apply_viewbox(const svgdom::view_boxed& e, const svgdom::aspect_ratioed& ar){ // TRACE(<< "vb = " << e.view_box[0] << ", " << e.view_box[1] << ", " << e.view_box[2] << ", " << e.view_box[3] << std::endl) if(!e.is_view_box_specified()){ return; } if(ar.preserve_aspect_ratio.preserve != svgdom::aspect_ratioed::aspect_ratio_preservation::none){ if(e.view_box[3] >= 0 && this->viewport[1] >= 0){ // if viewBox width and viewport width are not 0 real scaleFactor, dx, dy; real viewBoxAspect = e.view_box[2] / e.view_box[3]; real viewportAspect = this->viewport[0] / this->viewport[1]; if((viewBoxAspect >= viewportAspect && ar.preserve_aspect_ratio.slice) || (viewBoxAspect < viewportAspect && !ar.preserve_aspect_ratio.slice)){ // fit by Y scaleFactor = this->viewport[1] / e.view_box[3]; dx = e.view_box[2] - this->viewport[0]; dy = 0; }else{ // viewBoxAspect < viewportAspect // fit by X scaleFactor = this->viewport[0] / e.view_box[2]; dx = 0; dy = e.view_box[3] - this->viewport[1]; } switch(ar.preserve_aspect_ratio.preserve){ case svgdom::aspect_ratioed::aspect_ratio_preservation::none: ASSERT(false) default: break; case svgdom::aspect_ratioed::aspect_ratio_preservation::x_min_y_max: this->canvas.translate(0, dy); break; case svgdom::aspect_ratioed::aspect_ratio_preservation::x_min_y_mid: this->canvas.translate(0, dy / 2); break; case svgdom::aspect_ratioed::aspect_ratio_preservation::x_min_y_min: break; case svgdom::aspect_ratioed::aspect_ratio_preservation::x_mid_y_max: this->canvas.translate(dx / 2, dy); break; case svgdom::aspect_ratioed::aspect_ratio_preservation::x_mid_y_mid: this->canvas.translate(dx / 2, dy / 2); break; case svgdom::aspect_ratioed::aspect_ratio_preservation::x_mid_y_min: this->canvas.translate(dx / 2, 0); break; case svgdom::aspect_ratioed::aspect_ratio_preservation::x_max_y_max: this->canvas.translate(dx, dy); break; case svgdom::aspect_ratioed::aspect_ratio_preservation::x_max_y_mid: this->canvas.translate(dx, dy / 2); break; case svgdom::aspect_ratioed::aspect_ratio_preservation::x_max_y_min: this->canvas.translate(dx, 0); break; } this->canvas.scale(scaleFactor, scaleFactor); } }else{ // if no preserveAspectRatio enforced if(e.view_box[2] != 0 && e.view_box[3] != 0){ // if viewBox width and height are not 0 this->canvas.scale(this->viewport.comp_div({e.view_box[2], e.view_box[3]})); } } this->canvas.translate(-e.view_box[0], -e.view_box[1]); } void renderer::set_gradient_properties(canvas::gradient& gradient, const svgdom::gradient& g, const svgdom::style_stack& ss){ // Gradient inherits all attributes from other gradients it refers via href. // Here we need to make sure that the gradient inherits 'styles', 'class' and all possible presentation attributes. // For that we need to replace the gradient element in the style stack with the one which has those inherited // attributes substituted. The currently handled gradient element is at the top of the style stack. svgdom::style_stack gradient_ss(ss); // copy style stack, so that we are able to modify it struct dummy_styleable : public svgdom::styleable{ const svgdom::gradient& g; dummy_styleable(const svgdom::gradient& g) : g(g) {} const std::string& get_id()const override{ return this->g.get_id(); } const std::string& get_tag()const override{ return static_cast<const svgdom::element&>(this->g).get_tag(); } } effective_gradient_styleable(g); effective_gradient_styleable.styles = this->gradient_get_styles(g); effective_gradient_styleable.classes = this->gradient_get_classes(g); effective_gradient_styleable.presentation_attributes = this->gradient_get_presentation_attributes(g); ASSERT(!gradient_ss.stack.empty()) gradient_ss.stack.pop_back(); gradient_ss.stack.push_back(effective_gradient_styleable); struct gradient_stops_adder : public svgdom::const_visitor{ std::vector<canvas::gradient::stop> stops; svgdom::style_stack& ss; gradient_stops_adder(svgdom::style_stack& ss) : ss(ss) {} void visit(const svgdom::gradient::stop_element& stop)override{ svgdom::style_stack::push stylePush(this->ss, stop); r4::vector3<real> rgb; if(auto p = this->ss.get_style_property(svgdom::style_property::stop_color)){ rgb = svgdom::get_rgb(*p).to<real>(); }else{ rgb.set(0); } svgdom::real opacity = 1; if(auto p = this->ss.get_style_property(svgdom::style_property::stop_opacity)){ if(std::holds_alternative<svgdom::real>(*p)){ opacity = real(*std::get_if<svgdom::real>(p)); } } this->stops.push_back(canvas::gradient::stop{ {rgb, opacity}, real(stop.offset) }); } } visitor(gradient_ss); for(auto& stop : this->gradient_get_stops(g)){ stop->accept(visitor); } gradient.set_stops(utki::make_span(visitor.stops)); gradient.set_spread_method(this->gradient_get_spread_method(g)); } void renderer::apply_filter(){ if(auto filter = this->style_stack.get_style_property(svgdom::style_property::filter)){ if(std::holds_alternative<std::string>(*filter)){ this->apply_filter(svgdom::get_local_id_from_iri(*filter)); } } } void renderer::apply_filter(const std::string& id){ auto e = this->finder_by_id.find(id); if(!e){ return; } filter_applier visitor(*this); ASSERT(e) e->accept(visitor); this->blit(visitor.get_last_result()); } void renderer::set_gradient(const std::string& id){ auto ss = this->style_stack_cache.find(id); auto e = this->finder_by_id.find(id); ASSERT((ss && e) || !ss) if(!ss){ this->canvas.set_source(r4::vector4<real>(0)); return; } ASSERT(e) struct common_gradient_push{ canvas_matrix_push matrix_push; std::unique_ptr<renderer_viewport_push> viewport_push; common_gradient_push(renderer& r, const svgdom::gradient& gradient) : matrix_push(r.canvas) { if(r.gradient_get_units(gradient) == svgdom::coordinate_units::object_bounding_box){ r.canvas.translate(r.user_space_bounding_box.p); // apply scale only if bounding box dimensions are not zero to avoid non-invertible matrix if(r.user_space_bounding_box.d.is_positive()){ r.canvas.scale(r.user_space_bounding_box.d); } ASSERT(r.canvas.get_matrix().det() != 0, [&](auto&o){o << "matrix =\n" << r.canvas.get_matrix();}) this->viewport_push = std::make_unique<renderer_viewport_push>(r, real(1)); } r.apply_transformations(r.gradient_get_transformations(gradient)); } ~common_gradient_push()noexcept{} }; struct gradient_setter : public svgdom::const_visitor{ renderer& r; const svgdom::style_stack& ss; gradient_setter(renderer& r, const svgdom::style_stack& ss) : r(r), ss(ss) {} void visit(const svgdom::linear_gradient_element& gradient)override{ common_gradient_push commonPush(this->r, gradient); auto g = std::make_shared<canvas::linear_gradient>( this->r.length_to_px( this->r.gradient_get_x1(gradient), this->r.gradient_get_y1(gradient) ), this->r.length_to_px( this->r.gradient_get_x2(gradient), this->r.gradient_get_y2(gradient) ) ); this->r.set_gradient_properties(*g, gradient, this->ss); this->r.canvas.set_source(g); } void visit(const svgdom::radial_gradient_element& gradient)override{ common_gradient_push commonPush(this->r, gradient); auto cx = this->r.gradient_get_cx(gradient); auto cy = this->r.gradient_get_cy(gradient); auto radius = this->r.gradient_get_r(gradient); auto fx = this->r.gradient_get_fx(gradient); auto fy = this->r.gradient_get_fy(gradient); if(!fx.is_valid()){ fx = cx; } if(!fy.is_valid()){ fy = cy; } auto g = std::make_shared<canvas::radial_gradient>( this->r.length_to_px(fx, fy), this->r.length_to_px(cx, cy), this->r.length_to_px(radius) ); this->r.set_gradient_properties(*g, gradient, this->ss); this->r.canvas.set_source(g); } void default_visit(const svgdom::element&)override{ this->r.canvas.set_source(r4::vector4<real>{0}); } } visitor(*this, *ss); e->accept(visitor); } void renderer::update_bounding_box(){ this->user_space_bounding_box = this->canvas.get_shape_bounding_box(); // TRACE(<< "bb = " << this->user_space_bounding_box << std::endl) if(this->user_space_bounding_box.d[0] == 0){ // empty path return; } // set device space bounding box std::array<r4::vector2<real>, 4> rect_vertices = {{ this->user_space_bounding_box.p, this->user_space_bounding_box.x2_y2(), this->user_space_bounding_box.x1_y2(), this->user_space_bounding_box.x2_y1() }}; for(auto& vertex : rect_vertices){ vertex = this->canvas.matrix_mul(vertex); r4::segment2<real> bb; bb.p1.x() = decltype(bb.p1.x())(vertex.x()); bb.p2.x() = decltype(bb.p2.x())(vertex.x()); bb.p1.y() = decltype(bb.p1.y())(vertex.y()); bb.p2.y() = decltype(bb.p2.y())(vertex.y()); this->device_space_bounding_box.unite(bb); } } void renderer::render_shape(bool isCairoGroupPushed){ this->update_bounding_box(); { auto p = this->style_stack.get_style_property(svgdom::style_property::fill_rule); if(p && std::holds_alternative<svgdom::fill_rule>(*p)){ this->canvas.set_fill_rule(*std::get_if<svgdom::fill_rule>(p)); }else{ this->canvas.set_fill_rule(svgdom::fill_rule::nonzero); } } svgdom::style_value blackFill; auto fill = this->style_stack.get_style_property(svgdom::style_property::fill); if (!fill) { blackFill = svgdom::parse_paint("black"); fill = &blackFill; } auto stroke = this->style_stack.get_style_property(svgdom::style_property::stroke); // OPTIMIZATION: in case there is 'opacity' style property and only one of // 'stroke' or 'fill' is not none and is a solid color (not pattern/gradient), // then there is no need to push cairo group, but just multiply // the 'stroke-opacity' or 'fill-opacity' by 'opacity' value. auto opacity = svgdom::real(1); if(!isCairoGroupPushed){ auto p = this->style_stack.get_style_property(svgdom::style_property::opacity); if(p && std::holds_alternative<svgdom::real>(*p)){ opacity = *std::get_if<svgdom::real>(p); } } ASSERT(fill) if(!svgdom::is_none(*fill)){ if(std::holds_alternative<std::string>(*fill)){ this->set_gradient(svgdom::get_local_id_from_iri(*fill)); }else{ svgdom::real fillOpacity = 1; auto p = this->style_stack.get_style_property(svgdom::style_property::fill_opacity); if(p && std::holds_alternative<svgdom::real>(*p)){ fillOpacity = *std::get_if<svgdom::real>(p); } auto fillRgb = svgdom::get_rgb(*fill).to<real>(); this->canvas.set_source(r4::vector4<real>{fillRgb, fillOpacity * opacity}); } this->canvas.fill(); } if(stroke && !svgdom::is_none(*stroke)){ { auto p = this->style_stack.get_style_property(svgdom::style_property::stroke_width); if(p && std::holds_alternative<svgdom::length>(*p)){ this->canvas.set_line_width(this->length_to_px(*std::get_if<svgdom::length>(p))); }else{ this->canvas.set_line_width(1); } } { auto p = this->style_stack.get_style_property(svgdom::style_property::stroke_linecap); if(p && std::holds_alternative<svgdom::stroke_line_cap>(*p)){ this->canvas.set_line_cap(*std::get_if<svgdom::stroke_line_cap>(p)); }else{ this->canvas.set_line_cap(svgdom::stroke_line_cap::butt); } } { auto p = this->style_stack.get_style_property(svgdom::style_property::stroke_linejoin); if(p && std::holds_alternative<svgdom::stroke_line_join>(*p)){ this->canvas.set_line_join(*std::get_if<svgdom::stroke_line_join>(p)); }else{ this->canvas.set_line_join(svgdom::stroke_line_join::miter); } } { auto dasharray_prop = this->style_stack.get_style_property(svgdom::style_property::stroke_dasharray); if(dasharray_prop && std::holds_alternative<std::vector<svgdom::length>>(*dasharray_prop)){ auto dashoffset_prop = this->style_stack.get_style_property(svgdom::style_property::stroke_dashoffset); real dashoffset = 0; if(dashoffset_prop && std::holds_alternative<svgdom::length>(*dashoffset_prop)){ dashoffset = this->length_to_px(*std::get_if<svgdom::length>(dashoffset_prop)); } const auto& lenarr = *std::get_if<std::vector<svgdom::length>>(dasharray_prop); // convert lengthes to pixels std::vector<real> dasharray(lenarr.size()); auto dst = dasharray.begin(); for(auto src = lenarr.begin(); src != lenarr.end(); ++src, ++dst){ ASSERT(dst != dasharray.end()) *dst = this->length_to_px(*src); } ASSERT(dst == dasharray.end()) this->canvas.set_dash_pattern(utki::make_span(dasharray), dashoffset); }else{ this->canvas.set_dash_pattern(nullptr, 0); // no dashing } } ASSERT(stroke) if(std::holds_alternative<std::string>(*stroke)){ this->set_gradient(svgdom::get_local_id_from_iri(*std::get_if<std::string>(stroke))); }else{ svgdom::real strokeOpacity = 1; auto p = this->style_stack.get_style_property(svgdom::style_property::stroke_opacity); if(p && std::holds_alternative<svgdom::real>(*p)){ strokeOpacity = *std::get_if<svgdom::real>(p); } auto rgb = svgdom::get_rgb(*stroke).to<real>(); this->canvas.set_source(r4::vector4<real>{rgb, strokeOpacity * opacity}); } this->canvas.stroke(); } // clear path if any left this->canvas.clear_path(); this->apply_filter(); } void renderer::render_svg_element( const svgdom::container& e, const svgdom::styleable& s, const svgdom::view_boxed& v, const svgdom::aspect_ratioed& a, const svgdom::length& x, const svgdom::length& y, const svgdom::length& width, const svgdom::length& height ) { svgdom::style_stack::push pushStyles(this->style_stack, s); if(this->is_group_invisible()){ return; } common_element_push group_push(*this, true); if(!this->is_outermost_element){ this->canvas.translate(this->length_to_px(x, y)); } renderer_viewport_push viewport_push(*this, this->length_to_px(width, height)); this->apply_viewbox(v, a); { bool oldOutermostElementFlag = this->is_outermost_element; this->is_outermost_element = false; utki::scope_exit scope_exit([oldOutermostElementFlag, this](){ this->is_outermost_element = oldOutermostElementFlag; }); this->relay_accept(e); } this->apply_filter(); } renderer::renderer( svgren::canvas& canvas, unsigned dpi, r4::vector2<real> viewport, const svgdom::svg_element& root ) : canvas(canvas), finder_by_id(root), style_stack_cache(root), dpi(real(dpi)), viewport(viewport) { this->device_space_bounding_box.set_empty_bounding_box(); this->background = this->canvas.get_sub_surface(); #ifdef SVGREN_BACKGROUND this->canvas.set_source( r4::vector4<real>{ unsigned((SVGREN_BACKGROUND >> 0) & 0xff), unsigned((SVGREN_BACKGROUND >> 8) & 0xff), unsigned((SVGREN_BACKGROUND >> 16) & 0xff), unsigned((SVGREN_BACKGROUND >> 24) & 0xff) } / 0xff ); this->canvas.rectangle({0, viewport}); this->canvas.fill(); this->canvas.clear_path(); this->canvas.set_source({0, 0, 0, 0}); #endif } void renderer::visit(const svgdom::g_element& e){ // TRACE(<< "rendering GElement: id = " << e.id << std::endl) svgdom::style_stack::push pushStyles(this->style_stack, e); if(this->is_group_invisible()){ return; } common_element_push group_push(*this, true); this->apply_transformations(e.transformations); this->relay_accept(e); this->apply_filter(); } void renderer::visit(const svgdom::use_element& e){ // TRACE(<< "rendering UseElement" << std::endl) auto ref = this->finder_by_id.find(e.get_local_id_from_iri()); if(!ref){ return; } struct ref_renderer : public svgdom::const_visitor{ renderer& r; const svgdom::use_element& ue; svgdom::g_element fake_g_element; ref_renderer(renderer& r, const svgdom::use_element& e) : r(r), ue(e) { this->fake_g_element.styles = e.styles; this->fake_g_element.presentation_attributes = e.presentation_attributes; this->fake_g_element.transformations = e.transformations; // add x and y transformation { svgdom::transformable::transformation t; t.type_ = svgdom::transformable::transformation::type::translate; auto p = this->r.length_to_px(e.x, e.y); t.x = p.x(); t.y = p.y(); this->fake_g_element.transformations.push_back(t); } } void visit(const svgdom::symbol_element& symbol)override{ struct fake_svg_element : public svgdom::element{ renderer& r; const svgdom::use_element& ue; const svgdom::symbol_element& se; fake_svg_element(renderer& r, const svgdom::use_element& ue, const svgdom::symbol_element& se) : r(r), ue(ue), se(se) {} void accept(svgdom::visitor& visitor)override{ ASSERT(false) } void accept(svgdom::const_visitor& visitor)const override{ const auto hundred_percent = svgdom::length(100, svgdom::length_unit::percent); this->r.render_svg_element( this->se, this->se, this->se, this->se, svgdom::length(0), svgdom::length(0), this->ue.width.is_valid() ? this->ue.width : hundred_percent, this->ue.height.is_valid() ? this->ue.height : hundred_percent ); } const std::string& get_tag()const override{ return fake_svg_element_tag; } }; this->fake_g_element.children.push_back(std::make_unique<fake_svg_element>(this->r, this->ue, symbol)); this->fake_g_element.accept(this->r); } void visit(const svgdom::svg_element& svg)override{ struct fake_svg_element : public svgdom::element{ renderer& r; const svgdom::use_element& ue; const svgdom::svg_element& se; fake_svg_element(renderer& r, const svgdom::use_element& ue, const svgdom::svg_element& se) : r(r), ue(ue), se(se) {} void accept(svgdom::visitor& visitor)override{ ASSERT(false) } void accept(svgdom::const_visitor& visitor) const override{ // width and height of <use> element override those of <svg> element. this->r.render_svg_element( this->se, this->se, this->se, this->se, this->se.x, this->se.y, this->ue.width.is_valid() ? this->ue.width : this->se.width, this->ue.height.is_valid() ? this->ue.height : this->se.height ); } const std::string& get_tag()const override{ return fake_svg_element_tag; } }; this->fake_g_element.children.push_back(std::make_unique<fake_svg_element>(this->r, this->ue, svg)); this->fake_g_element.accept(this->r); } void default_visit(const svgdom::element& element)override{ struct fake_svg_element : public svgdom::element{ renderer& r; const svgdom::element& e; fake_svg_element(renderer& r, const svgdom::element& e) : r(r), e(e) {} void accept(svgdom::visitor& visitor)override{ ASSERT(false) } void accept(svgdom::const_visitor& visitor) const override{ this->e.accept(this->r); } const std::string& get_tag()const override{ return fake_svg_element_tag; } }; this->fake_g_element.children.push_back(std::make_unique<fake_svg_element>(this->r, element)); this->fake_g_element.accept(this->r); } void default_visit(const svgdom::element& element, const svgdom::container& c)override{ this->default_visit(element); } } visitor(*this, e); ASSERT(ref) ref->accept(visitor); } void renderer::visit(const svgdom::svg_element& e){ // TRACE(<< "rendering SvgElement" << std::endl) render_svg_element(e, e, e, e, e.x, e.y, e.width, e.height); } bool renderer::is_invisible(){ auto p = this->style_stack.get_style_property(svgdom::style_property::visibility); if(p && std::holds_alternative<svgdom::visibility>(*p)){ if(*std::get_if<svgdom::visibility>(p) != svgdom::visibility::visible){ return true; } } return this->is_group_invisible(); } bool renderer::is_group_invisible(){ auto p = this->style_stack.get_style_property(svgdom::style_property::display); if(p && std::holds_alternative<svgdom::display>(*p)){ if(*std::get_if<svgdom::display>(p) == svgdom::display::none){ return true; } } return false; } void renderer::visit(const svgdom::path_element& e){ // TRACE(<< "rendering PathElement" << std::endl) svgdom::style_stack::push pushStyles(this->style_stack, e); if(this->is_invisible()){ return; } common_element_push group_push(*this, false); this->apply_transformations(e.transformations); r4::vector2<real> prev_quadratic_p = 0; const svgdom::path_element::step* prevStep = nullptr; for(auto& s : e.path){ switch(s.type_){ case svgdom::path_element::step::type::move_abs: this->canvas.move_abs({real(s.x), real(s.y)}); break; case svgdom::path_element::step::type::move_rel: this->canvas.move_rel({real(s.x), real(s.y)}); break; case svgdom::path_element::step::type::line_abs: this->canvas.line_abs({real(s.x), real(s.y)}); break; case svgdom::path_element::step::type::line_rel: this->canvas.line_rel({real(s.x), real(s.y)}); break; case svgdom::path_element::step::type::horizontal_line_abs: this->canvas.line_abs({ real(s.x), this->canvas.get_current_point().y() }); break; case svgdom::path_element::step::type::horizontal_line_rel: this->canvas.line_rel({real(s.x), 0}); break; case svgdom::path_element::step::type::vertical_line_abs: this->canvas.line_abs({ this->canvas.get_current_point().x(), real(s.y) }); break; case svgdom::path_element::step::type::vertical_line_rel: this->canvas.line_rel({0, real(s.y)}); break; case svgdom::path_element::step::type::close: this->canvas.close_path(); break; case svgdom::path_element::step::type::quadratic_abs: this->canvas.quadratic_curve_abs({real(s.x1), real(s.y1)}, {real(s.x), real(s.y)}); break; case svgdom::path_element::step::type::quadratic_rel: this->canvas.quadratic_curve_rel({real(s.x1), real(s.y1)}, {real(s.x), real(s.y)}); break; case svgdom::path_element::step::type::quadratic_smooth_abs: { auto cur_p = this->canvas.get_current_point(); r4::vector2<real> p; r4::vector2<real> p1; if(prevStep){ p = {real(prevStep->x), real(prevStep->y)}; p1 = {real(prevStep->x1), real(prevStep->y1)}; }else{ p = real(0); p1 = real(0); } r4::vector2<real> cp1; // control point switch(prevStep ? prevStep->type_ : svgdom::path_element::step::type::unknown){ case svgdom::path_element::step::type::quadratic_abs: cp1 = -(p1 - cur_p) + cur_p; break; case svgdom::path_element::step::type::quadratic_smooth_abs: cp1 = -(prev_quadratic_p - cur_p) + cur_p; break; case svgdom::path_element::step::type::quadratic_rel: cp1 = -(p1 - p) + cur_p; break; case svgdom::path_element::step::type::quadratic_smooth_rel: cp1 = -(prev_quadratic_p - p) + cur_p; break; default: // No previous step or previous step is not a quadratic Bezier curve. // Set first control point equal to current point cp1 = cur_p; break; } prev_quadratic_p = cp1; this->canvas.quadratic_curve_abs(cp1, {real(s.x), real(s.y)}); } break; case svgdom::path_element::step::type::quadratic_smooth_rel: { auto cur_p = this->canvas.get_current_point(); r4::vector2<real> p; r4::vector2<real> p1; if(prevStep){ p = {real(prevStep->x), real(prevStep->y)}; p1 = {real(prevStep->x1), real(prevStep->y1)}; }else{ p = real(0); p1 = real(0); } r4::vector2<real> cp1; // control point switch(prevStep ? prevStep->type_ : svgdom::path_element::step::type::unknown){ case svgdom::path_element::step::type::quadratic_smooth_abs: cp1 = -(prev_quadratic_p - cur_p); break; case svgdom::path_element::step::type::quadratic_abs: cp1 = -(p1 - cur_p); break; case svgdom::path_element::step::type::quadratic_smooth_rel: cp1 = -(prev_quadratic_p - p); break; case svgdom::path_element::step::type::quadratic_rel: cp1 = -(p1 - p); break; default: // No previous step or previous step is not a quadratic Bezier curve. // Set first control point equal to current point, i.e. 0 because this is Relative step. cp1.set(0); break; } prev_quadratic_p = cp1; this->canvas.quadratic_curve_rel(cp1, {real(s.x), real(s.y)}); } break; case svgdom::path_element::step::type::cubic_abs: this->canvas.cubic_curve_abs( {real(s.x1), real(s.y1)}, {real(s.x2), real(s.y2)}, {real(s.x), real(s.y)} ); break; case svgdom::path_element::step::type::cubic_rel: this->canvas.cubic_curve_rel( {real(s.x1), real(s.y1)}, {real(s.x2), real(s.y2)}, {real(s.x), real(s.y)} ); break; case svgdom::path_element::step::type::cubic_smooth_abs: { auto cur_p = this->canvas.get_current_point(); r4::vector2<real> p; r4::vector2<real> p2; if(prevStep){ p = {real(prevStep->x), real(prevStep->y)}; p2 = {real(prevStep->x2), real(prevStep->y2)}; }else{ p = real(0); p2 = real(0); } r4::vector2<real> cp1; // first control point switch(prevStep ? prevStep->type_ : svgdom::path_element::step::type::unknown){ case svgdom::path_element::step::type::cubic_smooth_abs: case svgdom::path_element::step::type::cubic_abs: cp1 = -(p2 - cur_p) + cur_p; break; case svgdom::path_element::step::type::cubic_smooth_rel: case svgdom::path_element::step::type::cubic_rel: cp1 = -(p2 - p) + cur_p; break; default: // No previous step or previous step is not a cubic Bezier curve. // Set first control point equal to current point cp1 = cur_p; break; } this->canvas.cubic_curve_abs( cp1, {real(s.x2), real(s.y2)}, {real(s.x), real(s.y)} ); } break; case svgdom::path_element::step::type::cubic_smooth_rel: { auto cur_p = this->canvas.get_current_point(); r4::vector2<real> p; r4::vector2<real> p2; if(prevStep){ p = {real(prevStep->x), real(prevStep->y)}; p2 = {real(prevStep->x2), real(prevStep->y2)}; }else{ p = real(0); p2 = real(0); } r4::vector2<real> cp1; // first control point switch(prevStep ? prevStep->type_ : svgdom::path_element::step::type::unknown){ case svgdom::path_element::step::type::cubic_smooth_abs: case svgdom::path_element::step::type::cubic_abs: cp1 = -(p2 - cur_p); break; case svgdom::path_element::step::type::cubic_smooth_rel: case svgdom::path_element::step::type::cubic_rel: cp1 = -(p2 - p); break; default: // No previous step or previous step is not a cubic Bezier curve. // Set first control point equal to current point, i.e. 0 because this is Relative step. cp1.set(0); break; } this->canvas.cubic_curve_rel( cp1, {real(s.x2), real(s.y2)}, {real(s.x), real(s.y)} ); } break; case svgdom::path_element::step::type::arc_abs: this->canvas.arc_abs( {real(s.x), real(s.y)}, {real(s.rx), real(s.ry)}, deg_to_rad(real(s.x_axis_rotation)), s.flags.large_arc, s.flags.sweep ); break; case svgdom::path_element::step::type::arc_rel: this->canvas.arc_rel( {real(s.x), real(s.y)}, {real(s.rx), real(s.ry)}, deg_to_rad(real(s.x_axis_rotation)), s.flags.large_arc, s.flags.sweep ); break; default: ASSERT_INFO(false, "unknown path step type: " << unsigned(s.type_)) break; } prevStep = &s; } this->render_shape(group_push.is_group_pushed()); } void renderer::visit(const svgdom::circle_element& e){ // TRACE(<< "rendering CircleElement" << std::endl) svgdom::style_stack::push pushStyles(this->style_stack, e); if(this->is_invisible()){ return; } common_element_push group_push(*this, false); this->apply_transformations(e.transformations); auto c = this->length_to_px(e.cx, e.cy); auto r = this->length_to_px(e.r); this->canvas.circle(c, r); this->render_shape(group_push.is_group_pushed()); } void renderer::visit(const svgdom::polyline_element& e){ // TRACE(<< "rendering PolylineElement" << std::endl) svgdom::style_stack::push pushStyles(this->style_stack, e); if(this->is_invisible()){ return; } common_element_push group_push(*this, false); this->apply_transformations(e.transformations); if(e.points.empty()){ return; } auto i = e.points.begin(); this->canvas.move_abs(i->to<real>()); ++i; for(; i != e.points.end(); ++i){ this->canvas.line_abs(i->to<real>()); } this->render_shape(group_push.is_group_pushed()); } void renderer::visit(const svgdom::polygon_element& e){ // TRACE(<< "rendering PolygonElement" << std::endl) svgdom::style_stack::push pushStyles(this->style_stack, e); if(this->is_invisible()){ return; } common_element_push group_push(*this, false); this->apply_transformations(e.transformations); if (e.points.size() == 0) { return; } auto i = e.points.begin(); this->canvas.move_abs(i->to<real>()); ++i; for (; i != e.points.end(); ++i) { this->canvas.line_abs(i->to<real>()); } this->canvas.close_path(); this->render_shape(group_push.is_group_pushed()); } void renderer::visit(const svgdom::line_element& e){ // TRACE(<< "rendering LineElement" << std::endl) svgdom::style_stack::push pushStyles(this->style_stack, e); if(this->is_invisible()){ return; } common_element_push group_push(*this, false); this->apply_transformations(e.transformations); this->canvas.move_abs(this->length_to_px(e.x1, e.y1)); this->canvas.line_abs(this->length_to_px(e.x2, e.y2)); this->render_shape(group_push.is_group_pushed()); } void renderer::visit(const svgdom::ellipse_element& e){ // TRACE(<< "rendering EllipseElement" << std::endl) svgdom::style_stack::push pushStyles(this->style_stack, e); if(this->is_invisible()){ return; } common_element_push group_push(*this, false); this->apply_transformations(e.transformations); auto c = this->length_to_px(e.cx, e.cy); auto r = this->length_to_px(e.rx, e.ry); this->canvas.move_abs(c + r4::vector2<real>{r.x(), 0}); // move to start point this->canvas.arc_abs(c, r, 0, real(2) * utki::pi<real>()); this->canvas.close_path(); this->render_shape(group_push.is_group_pushed()); } void renderer::visit(const svgdom::style_element& e){ this->style_stack.add_css(e.css); } void renderer::visit(const svgdom::rect_element& e){ // TRACE(<< "rendering RectElement" << std::endl) svgdom::style_stack::push pushStyles(this->style_stack, e); if(this->is_invisible()){ return; } common_element_push group_push(*this, false); this->apply_transformations(e.transformations); auto dims = this->length_to_px(e.width, e.height); // NOTE: see SVG sect: https://www.w3.org/TR/SVG/shapes.html#RectElementWidthAttribute // Zero values disable rendering of the element. if(dims.x() == real(0) || dims.y() == real(0)){ return; } if((e.rx.value == 0 || !e.rx.is_valid()) & (e.ry.value == 0 || !e.ry.is_valid())){ this->canvas.rectangle({this->length_to_px(e.x, e.y), dims}); }else{ // compute real rx and ry auto rx = e.rx; auto ry = e.ry; if(!ry.is_valid() && rx.is_valid()){ ry = rx; }else if(!rx.is_valid() && ry.is_valid()){ rx = ry; } ASSERT(rx.is_valid() && ry.is_valid()) auto r = this->length_to_px(rx, ry); if(r.x() > dims.x() / 2){ rx = e.width; rx.value /= 2; } if(r.y() > dims.y() / 2){ ry = e.height; ry.value /= 2; } r = this->length_to_px(rx, ry); auto p = this->length_to_px(e.x, e.y); this->canvas.rectangle({p, dims}, r); } this->render_shape(group_push.is_group_pushed()); } const decltype(svgdom::transformable::transformations)& renderer::gradient_get_transformations(const svgdom::gradient& g){ if(g.transformations.size() != 0){ return g.transformations; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.gradient){ return this->gradient_get_transformations(*caster.gradient); } } } return g.transformations; } svgdom::coordinate_units renderer::gradient_get_units(const svgdom::gradient& g){ if(g.units != svgdom::coordinate_units::unknown){ return g.units; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.gradient){ return this->gradient_get_units(*caster.gradient); } } } return svgdom::coordinate_units::object_bounding_box; // object bounding box is default } svgdom::length renderer::gradient_get_x1(const svgdom::linear_gradient_element& g){ if(g.x1.is_valid()){ return g.x1; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.linear){ return this->gradient_get_x1(*caster.linear); } } } return svgdom::length(0, svgdom::length_unit::percent); } svgdom::length renderer::gradient_get_y1(const svgdom::linear_gradient_element& g){ if(g.y1.is_valid()){ return g.y1; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.linear){ return this->gradient_get_y1(*caster.linear); } } } return svgdom::length(0, svgdom::length_unit::percent); } svgdom::length renderer::gradient_get_x2(const svgdom::linear_gradient_element& g) { if(g.x2.is_valid()){ return g.x2; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.linear){ return this->gradient_get_x2(*caster.linear); } } } return svgdom::length(100, svgdom::length_unit::percent); } svgdom::length renderer::gradient_get_y2(const svgdom::linear_gradient_element& g) { if(g.y2.is_valid()){ return g.y2; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.linear){ return this->gradient_get_y2(*caster.linear); } } } return svgdom::length(0, svgdom::length_unit::percent); } svgdom::length renderer::gradient_get_cx(const svgdom::radial_gradient_element& g){ if(g.cx.is_valid()){ return g.cx; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.radial){ return this->gradient_get_cx(*caster.radial); } } } return svgdom::length(50, svgdom::length_unit::percent); } svgdom::length renderer::gradient_get_cy(const svgdom::radial_gradient_element& g){ if(g.cy.is_valid()){ return g.cy; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.radial){ return this->gradient_get_cy(*caster.radial); } } } return svgdom::length(50, svgdom::length_unit::percent); } svgdom::length renderer::gradient_get_r(const svgdom::radial_gradient_element& g) { if(g.r.is_valid()){ return g.r; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.radial){ return this->gradient_get_r(*caster.radial); } } } return svgdom::length(50, svgdom::length_unit::percent); } svgdom::length renderer::gradient_get_fx(const svgdom::radial_gradient_element& g) { if(g.fx.is_valid()){ return g.fx; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.radial){ return this->gradient_get_fx(*caster.radial); } } } return svgdom::length(0, svgdom::length_unit::unknown); } svgdom::length renderer::gradient_get_fy(const svgdom::radial_gradient_element& g) { if(g.fy.is_valid()){ return g.fy; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.radial){ return this->gradient_get_fy(*caster.radial); } } } return svgdom::length(0, svgdom::length_unit::unknown); } const decltype(svgdom::container::children)& renderer::gradient_get_stops(const svgdom::gradient& g) { if(g.children.size() != 0){ return g.children; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.gradient){ return this->gradient_get_stops(*caster.gradient); } } } return g.children; } const decltype(svgdom::styleable::styles)& renderer::gradient_get_styles(const svgdom::gradient& g){ if(g.styles.size() != 0){ return g.styles; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.gradient){ return this->gradient_get_styles(*caster.gradient); } } } return g.styles; } const decltype(svgdom::styleable::classes)& renderer::gradient_get_classes(const svgdom::gradient& g){ if(!g.classes.empty()){ return g.classes; } auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.gradient){ return this->gradient_get_classes(*caster.gradient); } } } return g.classes; } svgdom::gradient::spread_method renderer::gradient_get_spread_method(const svgdom::gradient& g){ if(g.spread_method_ != svgdom::gradient::spread_method::default_){ return g.spread_method_; } ASSERT(g.spread_method_ == svgdom::gradient::spread_method::default_) auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.gradient){ return this->gradient_get_spread_method(*caster.gradient); } } } return svgdom::gradient::spread_method::pad; } decltype(svgdom::styleable::presentation_attributes) renderer::gradient_get_presentation_attributes(const svgdom::gradient& g){ decltype(svgdom::styleable::presentation_attributes) ret = g.presentation_attributes; // copy decltype(svgdom::styleable::presentation_attributes) ref_attrs; auto ref_id = g.get_local_id_from_iri(); if(ref_id.size() != 0){ auto ref = this->finder_by_id.find(ref_id); if(ref){ gradient_caster caster; ref->accept(caster); if(caster.gradient){ ref_attrs = this->gradient_get_presentation_attributes(*caster.gradient); } } } for(auto& ra : ref_attrs){ if(ret.find(ra.first) == ret.end()){ ret.insert(std::make_pair(ra.first, std::move(ra.second))); } } return ret; } void renderer::blit(const surface& s){ if(s.span.empty() || s.d.x() == 0 || s.d.y() == 0){ TRACE(<< "renderer::blit(): source image is empty" << std::endl) return; } ASSERT(!s.span.empty() && s.d.x() != 0 && s.d.y() != 0) auto dst = this->canvas.get_sub_surface(); if(s.p.x() >= dst.d.x() || s.p.y() >= dst.d.y()){ TRACE(<< "renderer::blit(): source image is out of canvas" << std::endl) return; } auto dstp = dst.span.data() + s.p.y() * dst.stride + s.p.x(); auto srcp = s.span.data(); using std::min; auto dp = min(s.d, dst.d - s.p); for(unsigned y = 0; y != dp.y(); ++y){ auto p = dstp + y * dst.stride; auto sp = srcp + y * s.stride; for(unsigned x = 0; x != dp.x(); ++x, ++p, ++sp){ *p = *sp; } } }
28.201643
146
0.66964
[ "object", "vector", "transform", "solid" ]
10f5b86ec50f423a23509792a467d7f9d3894a98
3,647
cpp
C++
game/code/common/engine/render/ogles1.1/fixedogldepthstencilstate.cpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/engine/render/ogles1.1/fixedogldepthstencilstate.cpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/engine/render/ogles1.1/fixedogldepthstencilstate.cpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
2
2019-03-08T03:02:45.000Z
2019-05-14T08:41:26.000Z
#if defined( RENDER_PLAT_OGLES1_1) ////////////////////////////////////////////////////// // INCLUDES ////////////////////////////////////////////////////// #include "iphone/render/ogles1.1/fixedogldepthstencilstate.hpp" #include "iphone/render/ogles1.1/fixedoglwrapper.hpp" #include "common/engine/game/gameapp.hpp" #include "common/engine/render/renderstatemanager.hpp" #include "common/engine/render/renderstateshadowing.hpp" ////////////////////////////////////////////////////// // GLOBALS ////////////////////////////////////////////////////// static int gCompareFunctionTranslation[] = { GL_NEVER, //CompareFunc_Never GL_LESS, //CompareFunc_Less GL_EQUAL, //CompareFunc_Equal GL_LEQUAL, //CompareFunc_Less_Equal GL_GREATER, //CompareFunc_Greater GL_NOTEQUAL, //CompareFunc_Not_Equal GL_GEQUAL, //CompareFunc_Greater_Equal GL_ALWAYS //CompareFunc_Always }; static GLenum gStencilOpTranslation[] = { GL_KEEP, //StencilOp_Keep GL_ZERO, //StencilOp_Zero GL_REPLACE, //StencilOp_Replace GL_ZERO, //StencilOp_Increase_Saturate GL_ZERO, //StencilOp_Decrease_Saturate GL_INVERT, //StencilOp_Invert GL_INCR, //StencilOp_Increase GL_DECR, //StencilOp_Decrease }; ////////////////////////////////////////////////////// // CLASS METHODS ////////////////////////////////////////////////////// FixedOGLDepthStencilState::FixedOGLDepthStencilState() { } //============================================================================ FixedOGLDepthStencilState::~FixedOGLDepthStencilState() { } //============================================================================ void FixedOGLDepthStencilState::Dispatch( RenderStateShadowing* renderStateShadowing, void* /*context*/, bool forceUpload ) { const DepthStencilState* currentState = renderStateShadowing->GetCurrentDepthStencilState(); const DepthStencilStateStruct* currentStateData = NULL; if ( currentState == this ) { return; } if ( currentState != NULL ) { currentStateData = currentState->GetData(); } else { forceUpload = true; } if ( forceUpload == true || mData.mDepthEnable != currentStateData->mDepthEnable || mData.mDepthFunc != currentStateData->mDepthFunc ) { if ( mData.mDepthEnable ) { FixedOGL::oglEnable( GL_DEPTH_TEST ); FixedOGL::oglDepthFunc( gCompareFunctionTranslation[mData.mDepthFunc] ); } else { FixedOGL::oglDisable( GL_DEPTH_TEST ); } } if ( forceUpload == true || mData.mDepthWriteMask != currentStateData->mDepthWriteMask ) { FixedOGL::oglDepthMask( mData.mDepthWriteMask ); } if ( forceUpload == true || mData.mStencilEnable != currentStateData->mStencilEnable || mData.mStencilRef != currentStateData->mStencilRef || mData.mStencilReadMask != currentStateData->mStencilReadMask || mData.mFrontFace.mStencilFailOp != currentStateData->mFrontFace.mStencilFailOp || mData.mFrontFace.mStencilDepthFailOp != currentStateData->mFrontFace.mStencilDepthFailOp || mData.mFrontFace.mStencilPassOp != currentStateData->mFrontFace.mStencilPassOp ) { if ( mData.mStencilEnable ) { FixedOGL::oglEnable( GL_STENCIL_TEST ); FixedOGL::oglStencilFunc( gCompareFunctionTranslation[mData.mFrontFace.mStencilFunc], mData.mStencilRef, mData.mStencilReadMask ); FixedOGL::oglStencilOp( gStencilOpTranslation[mData.mFrontFace.mStencilFailOp], gStencilOpTranslation[mData.mFrontFace.mStencilDepthFailOp], gStencilOpTranslation[mData.mFrontFace.mStencilPassOp] ); } else { FixedOGL::oglDisable( GL_STENCIL_TEST ); } } renderStateShadowing->SetCurrentDepthStencilState( this ); } #endif
27.014815
94
0.654236
[ "render" ]
10fb7af9b1d6062537dda8c3763eb88bcd821508
15,387
cpp
C++
earth_enterprise/src/common/packetfile/packetindexwriter.cpp
seamusdunlop123/earthenterprise
a2651b1c00dd6230fd5d3d47502d228dbfca0f63
[ "Apache-2.0" ]
3
2017-12-21T05:40:09.000Z
2018-05-16T11:18:25.000Z
earth_enterprise/src/common/packetfile/packetindexwriter.cpp
seamusdunlop123/earthenterprise
a2651b1c00dd6230fd5d3d47502d228dbfca0f63
[ "Apache-2.0" ]
null
null
null
earth_enterprise/src/common/packetfile/packetindexwriter.cpp
seamusdunlop123/earthenterprise
a2651b1c00dd6230fd5d3d47502d228dbfca0f63
[ "Apache-2.0" ]
1
2020-06-21T09:36:13.000Z
2020-06-21T09:36:13.000Z
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <vector> #include <algorithm> #include <sstream> #include <khGuard.h> #include <khSimpleException.h> #include <khFileUtils.h> #include <notify.h> #include <third_party/rsa_md5/crc32.h> #include <merge/merge.h> #include <filebundle/filebundlewriter.h> #include <packetfile/packetindexwriter.h> #include <packetfile/packetfile.h> #include <khEndian.h> static const int kWriteBufferSize = 10 * 1024 * 1024; // PacketIndexWriter - create index for packet file. Used internally // by PacketFileWriter and PacketFilePackIndexer. See packetwriter.h // for information about index ordering. // Constructor - create the writer and write the index header. Path // is the path to the PacketFile directory. Execute permissions are // stripped from mode before creating the index file. Always // overwrites any existing index. PacketIndexWriter::PacketIndexWriter(geFilePool &file_pool, const std::string &path, mode_t mode, bool data_has_crc) : file_pool_(file_pool), mode_(mode), data_has_crc_(data_has_crc), index_path_(path + PacketFile::kIndexBase), index_temp_path_(index_path_ + ".tmp"), index_pos_(0), entry_count_(0), is_preorder_(true), is_level_ordered_(true), level_region_(QuadtreePath::kMaxLevel + 1) { // Delete the final version of the index if it already exists. This // will avoid problems if the writer dies before completion. if (khExists(index_path_)) { khUnlink(index_path_); } // Create a writer for the temporary index file CreateIndexWriter(index_temp_path_, index_writer_, &index_pos_); } PacketIndexWriter::~PacketIndexWriter() { if (index_writer_) { notify(NFY_WARN, "PacketIndexWriter: error, not closed properly: %s", index_path_.c_str()); } } // CreateIndexWriter - create the writer, write the index header, and return // position just after header. void PacketIndexWriter::CreateIndexWriter( const std::string &index_path, khDeleteGuard<geFilePool::Writer> &new_writer, off64_t *position) { // Create a writer for the index file new_writer = TransferOwnership( new geFilePool::Writer(geFilePool::Writer::ReadWrite, geFilePool::Writer::Truncate, file_pool_, index_path, mode_ & ~FileBundleWriter::kExecuteMode)); LittleEndianWriteBuffer le_buffer; le_buffer << FixedLengthString(PacketFile::kSignature, PacketFile::kSignature.size()) << PacketFile::kFormatVersion << EncodeAs<uint16>(data_has_crc_); le_buffer << Crc32(le_buffer.data(), le_buffer.size()); new_writer->Pwrite(le_buffer.data(), le_buffer.size(), 0); *position = le_buffer.size(); assert(*position == (off64_t)PacketFile::kIndexHeaderSize); } // WriteAppend - add entry to end of index, return position written void PacketIndexWriter::WriteAppend(const PacketIndexEntry &index_entry) { WriteAt(AllocateAppend(index_entry.qt_path()), index_entry); } uint64 PacketIndexWriter::AllocateAppend(const QuadtreePath &qt_path) { // Update index progress off64_t index_write_pos; { khLockGuard lock(modify_lock_); // Reserve position in index index_write_pos = index_pos_; index_pos_ += PacketIndexEntry::kStoreSize; // Update input ordering information UpdatePreorder(qt_path); UpdateLevelOrdered(qt_path, index_write_pos); last_path_ = qt_path; } return index_write_pos; } void PacketIndexWriter::WriteAt(uint64 pos, const PacketIndexEntry &index_entry) { // Create buffer for index entry LittleEndianWriteBuffer le_buffer; le_buffer << index_entry; assert(le_buffer.size() == PacketIndexEntry::kStoreSize); // Write new record to index if (!index_writer_) { throw khSimpleException( "PacketIndexWriter::WriteAt write to closed pack file ") << index_temp_path_; } index_writer_->Pwrite(le_buffer.data(), le_buffer.size(), pos); } // UpdatePreorder - check if the new record is still in preorder, // updating the is_preorder_ flag. void PacketIndexWriter::UpdatePreorder(const QuadtreePath &new_path) { is_preorder_ = is_preorder_ && !(new_path < last_path_); } // UpdateLevelOrdered - check if the new record is consistent with a // level ordered file. If it is the same level as the previous // record, it must not precede that record. If at a different level, // no records from that level must have been seen previously. // // The vector level_region_ is used to track the start of index records // for each level seen. This information is used to merge the records // when the writer is closed. void PacketIndexWriter::UpdateLevelOrdered(const QuadtreePath &new_path, off64_t index_pos) { if (is_level_ordered_) { uint32 level = new_path.Level(); SortedRegion &region = level_region_.at(level); if ((new_path.Level() == last_path_.Level()) ? (new_path < last_path_) : (region.count != 0)) { // if out of order is_level_ordered_ = false; } else { if (0 == region.count) { // none previous at this level assert(index_pos != 0); region.position = index_pos; } ++region.count; } } } //------------------------------------------------------------------------------- // SortIndex - takes an unsorted index in index_temp_path_ and // produces an index sorted in preorder in index_path_. If index is // too big to sort in memory, a second temporary file will be // generated to hold intermediate results. // // TODO: the intermediate results could be written back in-place in // the temporary index, but right now geFilePool doesn't support read // and write on the same file, or opening a file for rewrite. void PacketIndexWriter::SortIndex(size_t max_sort_buffer) { // Make sure we are allowed at least a minimum amount of memory if (max_sort_buffer < kMinSortBuffer) { notify(NFY_NOTICE, "PacketIndexWriter::SortIndex: buffer size limit specified (%lu) " "is less than minimum (%lu), using minimum", static_cast<unsigned long>(max_sort_buffer), static_cast<unsigned long>(kMinSortBuffer)); max_sort_buffer = kMinSortBuffer; } // Open the unsorted index for reading, and create a secondary temp // index khDeleteGuard<PacketIndexReader> unsorted_index( TransferOwnership(new PacketIndexReader(file_pool_, index_temp_path_))); const std::string region_index_path(index_path_ + ".sort.tmp"); khDeleteGuard<geFilePool::Writer> region_index; off64_t write_pos; CreateIndexWriter(region_index_path, region_index, &write_pos); region_index->BufferWrites(kWriteBufferSize); // Set up memory buffer and vector of regions. entry_count is the // total number of index entries, buffer_count is the count of // entries which will fit in the memory buffer. ssize_t entry_count = (unsorted_index->Filesize() - PacketFile::kIndexHeaderSize) / PacketIndexEntry::kStoreSize; ssize_t buffer_count = std::min(entry_count, static_cast<ssize_t>(max_sort_buffer / PacketIndexEntry::kStoreSize)); ssize_t region_count = (entry_count + buffer_count - 1) / buffer_count; std::vector<SortedRegion> region; region.reserve(region_count); std::vector<PacketIndexEntry> index_entry(buffer_count); // Sort each region of the file, and write to intermediate file for (ssize_t remaining = entry_count; remaining > 0;) { ssize_t read_count = std::min(remaining, buffer_count); // Read index entries into memory from input file for (ssize_t i = 0; i < read_count; ++i) { unsorted_index->ReadNext(&index_entry[i]); } std::sort(index_entry.begin(), index_entry.begin() + read_count); // Save region data for merge, and write sorted index entries to // intermediate output file region.push_back(SortedRegion(write_pos, read_count)); LittleEndianWriteBuffer le_buffer(PacketIndexEntry::kStoreSize); for (ssize_t i = 0; i < read_count; ++i) { le_buffer.reset(); le_buffer << index_entry.at(i); region_index->Pwrite(le_buffer.data(), le_buffer.size(), write_pos); write_pos += le_buffer.size(); } remaining -= read_count; } region_index->SyncAndClose(); // done writing region_index.clear(); unsorted_index.clear(); // done reading // Delete the input file if (!khUnlink(index_temp_path_)) { notify(NFY_WARN, "PacketIndexWriter::SortIndex: failed to unlink %s", index_temp_path_.c_str()); } // Move intermediate sort results to final index if (region.size() == 1) { // Only one segment, just rename to final index file if (!khRename(region_index_path, index_path_)) { throw khSimpleException("PacketIndexWriter::SortIndex: index rename failed, ") << region_index_path << " -> " << index_path_; } notify(NFY_DEBUG, "PacketIndexWriter::SortIndex: sorted %ld entries in memory", static_cast<long int>(entry_count)); } else { // Multiple segments, merge into final index file MergeIndex(region_index_path, region); if (!khUnlink(region_index_path)) { notify(NFY_WARN, "PacketIndexWriter::SortIndex: failed to unlink %s", region_index_path.c_str()); } notify(NFY_DEBUG, "PacketIndexWriter::SortIndex: sorted %ld entries " "using merge", static_cast<long int>(entry_count)); } } //------------------------------------------------------------------------------- // MergeIndex and related classes - input is a temporary index file // with multiple sorted regions. Output is a merged final index file. class PacketIndexWriter::SortedRegionMergeSource : public MergeSource<PacketIndexEntry> { public: SortedRegionMergeSource(const std::string &name, geFilePool &file_pool, const std::string &index_path, const SortedRegion &region) : MergeSource<PacketIndexEntry>(name), valid_(true), index_path_(index_path), index_reader_(TransferOwnership( new PacketIndexReader(file_pool, index_path))), remaining_(region.count) { assert(remaining_ > 0); index_reader_->Seek(region.position); index_reader_->ReadNext(&current_); --remaining_; } virtual ~SortedRegionMergeSource() {} virtual const PacketIndexEntry &Current() const { if (valid_) { return current_; } else { throw khSimpleException("SortedRegionMergeSource::Current: no valid value") << " in source " << name() << " reading index " << index_path_; } } virtual bool Advance() { if (valid_ && remaining_ > 0) { index_reader_->ReadNext(&current_); --remaining_; } else { valid_ = false; } return valid_; } virtual void Close() { index_reader_.clear(); remaining_ = 0; } private: bool valid_; std::string index_path_; khDeleteGuard<PacketIndexReader> index_reader_; uint32 remaining_; // remaining records PacketIndexEntry current_; DISALLOW_COPY_AND_ASSIGN(SortedRegionMergeSource); }; void PacketIndexWriter::MergeIndex(const std::string &source_path, const std::vector<SortedRegion> &regions) { // Build a Merge with a source for each region Merge<PacketIndexEntry> index_merge("Merge_to_" + index_path_); size_t source_count = 0; for (size_t i = 0; i < regions.size(); ++i) { const SortedRegion &region = regions.at(i); if (region.count != 0) { std::ostringstream source_name; source_name << "IndexMerge:" << region.position << ":" << region.count; index_merge.AddSource( TransferOwnership( new SortedRegionMergeSource(source_name.str(), file_pool_, source_path, region))); ++source_count; } } notify(NFY_DEBUG, "PacketIndexWriter::MergeIndex: merging %llu regions", static_cast<long long unsigned>(source_count)); index_merge.Start(); // Create the final index output file khDeleteGuard<geFilePool::Writer> index_writer; off64_t index_pos; CreateIndexWriter(index_path_, index_writer, &index_pos); index_writer->BufferWrites(kWriteBufferSize); // Write the merged records to the final index LittleEndianWriteBuffer le_buffer(PacketIndexEntry::kStoreSize); do { le_buffer.reset(); le_buffer << index_merge.Current(); index_writer->Pwrite(le_buffer.data(), le_buffer.size(), index_pos); index_pos += le_buffer.size(); } while (index_merge.Advance()); index_merge.Close(); index_writer->SyncAndClose(); } // Close - close the index. If the index was written in sorted order, // just rename the temporary index to be the permanent index. If the // index was written sorted by levels, do a merge into the final // index. If the index was not sorted in any recognizable way, do a // full sort. void PacketIndexWriter::Close(size_t max_sort_buffer) { khLockGuard lock(modify_lock_); // Flush and close the temporary index file index_writer_->SyncAndClose(); index_writer_.clear(); // Check if index is empty if (index_pos_ == (off64_t)PacketFile::kIndexHeaderSize) { // no sorting to do when empty, just rename if (!khRename(index_temp_path_, index_path_)) { throw khSimpleException("PacketIndexWriter::Close: index rename failed, ") << index_temp_path_ << " -> " << index_path_; } } else { // not empty, we need to sort it // Determine if sorting is needed if (is_preorder_) { // Already in preorder, just rename the temporary index if (!khRename(index_temp_path_, index_path_)) { throw khSimpleException("PacketIndexWriter::Close: index rename failed, ") << index_temp_path_ << " -> " << index_path_; } } else if (is_level_ordered_) { // Multiple levels, sorted within each level. Do a merge of sorted // levels. MergeIndex(index_temp_path_, level_region_); // Delete the temporary index file if (!khUnlink(index_temp_path_)) { notify(NFY_WARN, "PacketIndexWriter::Close: failed to unlink %s", index_temp_path_.c_str()); } } else { // Not written in any recognizeable order - sort whole index SortIndex(max_sort_buffer); } } }
36.290094
84
0.669006
[ "vector" ]
10fbce2a5ca108ee3efc61cfaa1dd99251c27073
888
cpp
C++
algorithm/algorithm/1/209_minimum-size-subarray-sum/main.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
1
2020-10-01T14:52:45.000Z
2020-10-01T14:52:45.000Z
algorithm/algorithm/1/209_minimum-size-subarray-sum/main.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
3
2020-08-13T07:51:54.000Z
2021-01-29T11:17:25.000Z
algorithm/algorithm/1/209_minimum-size-subarray-sum/main.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int minSubArrayLen(int target, vector<int>& nums) { int n = nums.size(); int count = 0; int ret = n + 1; int len = 0; for(int i = 0; i < n; i++) { count = 0; len = 0; for(int k = i; k < n; k++) { len += nums[k]; count++; if(len >= target) { cout << "len = " << len << endl; ret = ret < count ? ret : count; break; } } } return ret == n + 1 ? 0 : ret; } }; int main() { Solution a; vector<int> vec = {1,1,1,1,1,1,1,1}; int target = 11; int ret = a.minSubArrayLen(target, vec); std::cout << ret << std::endl; }
21.658537
55
0.385135
[ "vector" ]
80054b6edabd50db90607b093db6b3e32d5002e9
8,344
cpp
C++
Source/Material.cpp
findux/ToolKit
3caa97441318d19fe0a6e3d13d88dfbdb60afb44
[ "MIT" ]
32
2020-10-16T00:17:14.000Z
2022-03-02T18:25:58.000Z
Source/Material.cpp
findux/ToolKit
3caa97441318d19fe0a6e3d13d88dfbdb60afb44
[ "MIT" ]
1
2021-09-19T12:18:17.000Z
2022-02-23T06:53:30.000Z
Source/Material.cpp
findux/ToolKit
3caa97441318d19fe0a6e3d13d88dfbdb60afb44
[ "MIT" ]
5
2020-09-18T09:04:40.000Z
2022-02-11T12:44:55.000Z
#include "stdafx.h" #include "Material.h" #include "ToolKit.h" #include "Util.h" #include "rapidxml.hpp" #include "rapidxml_utils.hpp" #include "DebugNew.h" namespace ToolKit { Material::Material() { m_color = Vec3(1.0f); m_type = ResourceType::Material; } Material::Material(String file) : Material() { m_file = file; } Material::~Material() { UnInit(); } void Material::Load() { if (m_loaded) { return; } XmlFile file(m_file.c_str()); XmlDocument doc; doc.parse<0>(file.data()); XmlNode* rootNode = doc.first_node("material"); DeSerialize(&doc, rootNode); m_loaded = true; } void Material::Save(bool onlyIfDirty) { Resource::Save(onlyIfDirty); m_vertexShader->Save(onlyIfDirty); m_fragmetShader->Save(onlyIfDirty); } void Material::Init(bool flushClientSideArray) { if (m_initiated) { return; } if (m_diffuseTexture) { m_diffuseTexture->Init(flushClientSideArray); m_renderState.diffuseTexture = m_diffuseTexture->m_textureId; m_renderState.diffuseTextureInUse = true; } if (m_cubeMap) { m_cubeMap->Init(flushClientSideArray); m_renderState.cubeMap = m_cubeMap->m_textureId; m_renderState.cubeMapInUse = true; } if (m_vertexShader) { m_vertexShader->Init(); } else { m_vertexShader = GetShaderManager()->Create<Shader>(ShaderPath("defaultVertex.shader", true)); m_vertexShader->Init(); } if (m_fragmetShader) { m_fragmetShader->Init(); } else { if (m_diffuseTexture) { m_fragmetShader = GetShaderManager()->Create<Shader>(ShaderPath("defaultFragment.shader", true)); } else { m_fragmetShader = GetShaderManager()->Create<Shader>(ShaderPath("solidColorFrag.shader", true)); } m_fragmetShader->Init(); } m_initiated = true; } void Material::UnInit() { m_initiated = false; } void Material::CopyTo(Resource* other) { Resource::CopyTo(other); Material* cpy = static_cast<Material*> (other); cpy->m_cubeMap = m_cubeMap; cpy->m_diffuseTexture = m_diffuseTexture; cpy->m_vertexShader = m_vertexShader; cpy->m_fragmetShader = m_fragmetShader; cpy->m_color = m_color; cpy->m_dirty = true; } RenderState* Material::GetRenderState() { if (m_diffuseTexture) { m_renderState.diffuseTextureInUse = true; m_renderState.diffuseTexture = m_diffuseTexture->m_textureId; } else { m_renderState.diffuseTextureInUse = false; } if (m_cubeMap) { m_renderState.cubeMap = m_cubeMap->m_textureId; } else { m_renderState.cubeMap = false; } return &m_renderState; } void Material::Serialize(XmlDocument* doc, XmlNode* parent) const { XmlNode* container = doc->allocate_node ( rapidxml::node_type::node_element, "material" ); if (parent != nullptr) { parent->append_node(container); } else { doc->append_node(container); } if (m_diffuseTexture) { XmlNode* node = doc->allocate_node ( rapidxml::node_type::node_element, "diffuseTexture" ); container->append_node(node); String file = GetRelativeResourcePath(m_diffuseTexture->m_file); WriteAttr(node, doc, "name", file); } if (m_cubeMap) { XmlNode* node = doc->allocate_node ( rapidxml::node_type::node_element, "cubeMap" ); container->append_node(node); String file = GetRelativeResourcePath(m_cubeMap->m_file); WriteAttr(node, doc, "name", file); } if (m_vertexShader) { XmlNode* node = doc->allocate_node ( rapidxml::node_type::node_element, "shader" ); container->append_node(node); String file = GetRelativeResourcePath(m_vertexShader->m_file); WriteAttr(node, doc, "name", file); } if (m_fragmetShader) { XmlNode* node = doc->allocate_node ( rapidxml::node_type::node_element, "shader" ); container->append_node(node); String file = GetRelativeResourcePath(m_fragmetShader->m_file); WriteAttr(node, doc, "name", file); } XmlNode* node = doc->allocate_node ( rapidxml::node_type::node_element, "color" ); container->append_node(node); WriteVec(node, doc, m_color); } void Material::DeSerialize(XmlDocument* doc, XmlNode* parent) { if (parent == nullptr) { return; } XmlNode* rootNode = parent; for (XmlNode* node = rootNode->first_node(); node; node = node->next_sibling()) { if (String("diffuseTexture").compare(node->name()) == 0) { XmlAttribute* attr = node->first_attribute("name"); m_diffuseTexture = GetTextureManager()->Create<Texture>(TexturePath(attr->value())); } else if (String("cubeMap").compare(node->name()) == 0) { XmlAttribute* attr = node->first_attribute("name"); m_cubeMap = GetTextureManager()->Create<CubeMap>(TexturePath(attr->value())); } else if (String("shader").compare(node->name()) == 0) { XmlAttribute* attr = node->first_attribute("name"); ShaderPtr shader = GetShaderManager()->Create<Shader>(ShaderPath(attr->value())); if (shader->m_shaderType == GL_VERTEX_SHADER) { m_vertexShader = shader; } else if (shader->m_shaderType == GL_FRAGMENT_SHADER) { m_fragmetShader = shader; } else { assert(false); } } else if (String("color").compare(node->name()) == 0) { ReadVec(node, m_color); } else { assert(false); } } } MaterialManager::MaterialManager() { m_type = ResourceType::Material; } MaterialManager::~MaterialManager() { } void MaterialManager::Init() { ResourceManager::Init(); Material* material = new Material(); material->m_vertexShader = GetShaderManager()->Create<Shader>(ShaderPath("defaultVertex.shader", true)); material->m_fragmetShader = GetShaderManager()->Create<Shader>(ShaderPath("defaultFragment.shader", true)); material->m_diffuseTexture = GetTextureManager()->Create<Texture>(TexturePath("default.png", true)); material->Init(); m_storage[MaterialPath("default.material", true)] = MaterialPtr(material); material = new Material(); material->m_vertexShader = GetShaderManager()->Create<Shader>(ShaderPath("defaultVertex.shader", true)); material->m_fragmetShader = GetShaderManager()->Create<Shader>(ShaderPath("unlitFrag.shader", true)); material->m_diffuseTexture = GetTextureManager()->Create<Texture>(TexturePath("default.png", true)); material->Init(); m_storage[MaterialPath("unlit.material", true)] = MaterialPtr(material); material = new Material(); material->m_vertexShader = GetShaderManager()->Create<Shader>(ShaderPath("defaultVertex.shader", true)); material->m_fragmetShader = GetShaderManager()->Create<Shader>(ShaderPath("solidColorFrag.shader", true)); material->Init(); m_storage[MaterialPath("solid.material", true)] = MaterialPtr(material); material = new Material(); material->m_vertexShader = GetShaderManager()->Create<Shader>(ShaderPath("defaultVertex.shader", true)); material->m_fragmetShader = GetShaderManager()->Create<Shader>(ShaderPath("unlitColorFrag.shader", true)); material->Init(); m_storage[MaterialPath("unlitSolid.material", true)] = MaterialPtr(material); } MaterialPtr MaterialManager::GetCopyOfUnlitMaterial() { return m_storage[MaterialPath("unlit.material", true)]->Copy<Material>(); } MaterialPtr MaterialManager::GetCopyOfUnlitColorMaterial() { return m_storage[MaterialPath("unlitSolid.material", true)]->Copy<Material>(); } MaterialPtr MaterialManager::GetCopyOfSolidMaterial() { return m_storage[MaterialPath("solid.material", true)]->Copy<Material>(); } MaterialPtr MaterialManager::GetCopyOfDefaultMaterial() { return m_storage[MaterialPath("default.material", true)]->Copy<Material>(); } }
24.759644
111
0.635427
[ "solid" ]
80096b18fbcf34f31fe498af7665c71ec9b88b00
17,576
cc
C++
GeneratorInterface/HydjetInterface/src/HydjetHadronizer.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
GeneratorInterface/HydjetInterface/src/HydjetHadronizer.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
GeneratorInterface/HydjetInterface/src/HydjetHadronizer.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
/* ######################## # Hydjet1 # # version: 1.9 patch1 # ######################## * Interface to the HYDJET generator, produces HepMC events * * Original Author: Camelia Mironov */ #include <iostream> #include <cmath> #include "boost/lexical_cast.hpp" #include "FWCore/Concurrency/interface/SharedResourceNames.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/EDMException.h" #include "GeneratorInterface/Core/interface/FortranInstance.h" #include "GeneratorInterface/HydjetInterface/interface/HydjetHadronizer.h" #include "GeneratorInterface/HydjetInterface/interface/HydjetWrapper.h" #include "GeneratorInterface/Pythia6Interface/interface/Pythia6Declarations.h" #include "GeneratorInterface/Pythia6Interface/interface/Pythia6Service.h" #include "HepMC/PythiaWrapper6_4.h" #include "HepMC/GenEvent.h" #include "HepMC/HeavyIon.h" #include "HepMC/SimpleVector.h" #include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h" #include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h" #include "SimDataFormats/GeneratorProducts/interface/GenRunInfoProduct.h" #include "SimDataFormats/HiGenData/interface/GenHIEvent.h" using namespace edm; using namespace std; using namespace gen; namespace { int convertStatus(int st){ if(st<= 0) return 0; if(st<=10) return 1; if(st<=20) return 2; if(st<=30) return 3; else return st; } } const std::vector<std::string> HydjetHadronizer::theSharedResources = { edm::SharedResourceNames::kPythia6, gen::FortranInstance::kFortranInstance }; //_____________________________________________________________________ HydjetHadronizer::HydjetHadronizer(const ParameterSet &pset) : BaseHadronizer(pset), evt(0), pset_(pset), abeamtarget_(pset.getParameter<double>("aBeamTarget")), angularspecselector_(pset.getParameter<int>("angularSpectrumSelector")), bfixed_(pset.getParameter<double>("bFixed")), bmax_(pset.getParameter<double>("bMax")), bmin_(pset.getParameter<double>("bMin")), cflag_(pset.getParameter<int>("cFlag")), embedding_(pset.getParameter<bool>("embeddingMode")), comenergy(pset.getParameter<double>("comEnergy")), doradiativeenloss_(pset.getParameter<bool>("doRadiativeEnLoss")), docollisionalenloss_(pset.getParameter<bool>("doCollisionalEnLoss")), fracsoftmult_(pset.getParameter<double>("fracSoftMultiplicity")), hadfreeztemp_(pset.getParameter<double>("hadronFreezoutTemperature")), hymode_(pset.getParameter<string>("hydjetMode")), maxEventsToPrint_(pset.getUntrackedParameter<int>("maxEventsToPrint", 1)), maxlongy_(pset.getParameter<double>("maxLongitudinalRapidity")), maxtrany_(pset.getParameter<double>("maxTransverseRapidity")), nsub_(0), nhard_(0), nmultiplicity_(pset.getParameter<int>("nMultiplicity")), nsoft_(0), nquarkflavor_(pset.getParameter<int>("qgpNumQuarkFlavor")), pythiaPylistVerbosity_(pset.getUntrackedParameter<int>("pythiaPylistVerbosity", 0)), qgpt0_(pset.getParameter<double>("qgpInitialTemperature")), qgptau0_(pset.getParameter<double>("qgpProperTimeFormation")), phi0_(0.), sinphi0_(0.), cosphi0_(1.), rotate_(pset.getParameter<bool>("rotateEventPlane")), shadowingswitch_(pset.getParameter<int>("shadowingSwitch")), signn_(pset.getParameter<double>("sigmaInelNN")), pythia6Service_(new Pythia6Service(pset)) { // Default constructor // PYLIST Verbosity Level // Valid PYLIST arguments are: 1, 2, 3, 5, 7, 11, 12, 13 pythiaPylistVerbosity_ = pset.getUntrackedParameter<int>("pythiaPylistVerbosity",0); LogDebug("PYLISTverbosity") << "Pythia PYLIST verbosity level = " << pythiaPylistVerbosity_; //Max number of events printed on verbosity level maxEventsToPrint_ = pset.getUntrackedParameter<int>("maxEventsToPrint",0); LogDebug("Events2Print") << "Number of events to be printed = " << maxEventsToPrint_; if(embedding_) src_ = pset.getParameter<edm::InputTag>("backgroundLabel"); } //_____________________________________________________________________ HydjetHadronizer::~HydjetHadronizer() { // destructor call_pystat(1); delete pythia6Service_; } //_____________________________________________________________________ void HydjetHadronizer::doSetRandomEngine(CLHEP::HepRandomEngine* v) { pythia6Service_->setRandomEngine(v); } //_____________________________________________________________________ void HydjetHadronizer::add_heavy_ion_rec(HepMC::GenEvent *evt) { // heavy ion record in the final CMSSW Event double npart = hyfpar.npart; int nproj = static_cast<int>(npart / 2); int ntarg = static_cast<int>(npart - nproj); HepMC::HeavyIon* hi = new HepMC::HeavyIon( nsub_, // Ncoll_hard/N of SubEvents nproj, // Npart_proj ntarg, // Npart_targ static_cast<int>(hyfpar.nbcol), // Ncoll 0, // spectator_neutrons 0, // spectator_protons 0, // N_Nwounded_collisions 0, // Nwounded_N_collisions 0, // Nwounded_Nwounded_collisions hyfpar.bgen * nuclear_radius(), // impact_parameter in [fm] phi0_, // event_plane_angle 0,//hypsi3.psi3, // eccentricity hyjpar.sigin // sigma_inel_NN ); evt->set_heavy_ion(*hi); delete hi; } //___________________________________________________________________ HepMC::GenParticle* HydjetHadronizer::build_hyjet(int index, int barcode) { // Build particle object corresponding to index in hyjets (soft+hard) double x0 = hyjets.phj[0][index]; double y0 = hyjets.phj[1][index]; double x = x0*cosphi0_-y0*sinphi0_; double y = y0*cosphi0_+x0*sinphi0_; HepMC::GenParticle* p = new HepMC::GenParticle( HepMC::FourVector(x, // px y, // py hyjets.phj[2][index], // pz hyjets.phj[3][index]), // E hyjets.khj[1][index], // id convertStatus(hyjets.khj[0][index] // status ) ); p->suggest_barcode(barcode); return p; } //___________________________________________________________________ HepMC::GenVertex* HydjetHadronizer::build_hyjet_vertex(int i,int id) { // build verteces for the hyjets stored events double x0=hyjets.vhj[0][i]; double y0=hyjets.vhj[1][i]; double x = x0*cosphi0_-y0*sinphi0_; double y = y0*cosphi0_+x0*sinphi0_; double z=hyjets.vhj[2][i]; double t=hyjets.vhj[4][i]; HepMC::GenVertex* vertex = new HepMC::GenVertex(HepMC::FourVector(x,y,z,t),id); return vertex; } //___________________________________________________________________ bool HydjetHadronizer::generatePartonsAndHadronize() { Pythia6Service::InstanceWrapper guard(pythia6Service_); // generate single event if(embedding_){ cflag_ = 0; const edm::Event& e = getEDMEvent(); Handle<HepMCProduct> input; e.getByLabel(src_,input); const HepMC::GenEvent * inev = input->GetEvent(); const HepMC::HeavyIon* hi = inev->heavy_ion(); if(hi){ bfixed_ = hi->impact_parameter(); phi0_ = hi->event_plane_angle(); sinphi0_ = sin(phi0_); cosphi0_ = cos(phi0_); }else{ LogWarning("EventEmbedding")<<"Background event does not have heavy ion record!"; } }else if(rotate_) rotateEvtPlane(); nsoft_ = 0; nhard_ = 0; edm::LogInfo("HYDJETmode") << "##### HYDJET nhsel = " << hyjpar.nhsel; edm::LogInfo("HYDJETfpart") << "##### HYDJET fpart = " << hyflow.fpart; edm::LogInfo("HYDJETtf") << "##### HYDJET hadron freez-out temp, Tf = " << hyflow.Tf; edm::LogInfo("HYDJETinTemp") << "##### HYDJET: QGP init temperature, T0 ="<<pyqpar.T0u; edm::LogInfo("HYDJETinTau") << "##### HYDJET: QGP formation time,tau0 ="<<pyqpar.tau0u; // generate a HYDJET event int ntry = 0; while(nsoft_ == 0 && nhard_ == 0){ if(ntry > 100){ edm::LogError("HydjetEmptyEvent") << "##### HYDJET: No Particles generated, Number of tries ="<<ntry; // Throw an exception. Use the EventCorruption exception since it maps onto SkipEvent // which is what we want to do here. std::ostringstream sstr; sstr << "HydjetHadronizerProducer: No particles generated after " << ntry << " tries.\n"; edm::Exception except(edm::errors::EventCorruption, sstr.str()); throw except; } else { HYEVNT(); nsoft_ = hyfpar.nhyd; nsub_ = hyjpar.njet; nhard_ = hyfpar.npyt; ++ntry; } } if(hyjpar.nhsel < 3) nsub_++; // event information HepMC::GenEvent *evt = new HepMC::GenEvent(); if(nhard_>0 || nsoft_>0) get_particles(evt); evt->set_signal_process_id(pypars.msti[0]); // type of the process evt->set_event_scale(pypars.pari[16]); // Q^2 add_heavy_ion_rec(evt); event().reset(evt); return true; } //_____________________________________________________________________ bool HydjetHadronizer::get_particles(HepMC::GenEvent *evt ) { // Hard particles. The first nhard_ lines from hyjets array. // Pythia/Pyquen sub-events (sub-collisions) for a given event // Return T/F if success/failure // Create particles from lujet entries, assign them into vertices and // put the vertices in the GenEvent, for each SubEvent // The SubEvent information is kept by storing indeces of main vertices // of subevents as a vector in GenHIEvent. LogDebug("SubEvent")<< "Number of sub events "<<nsub_; LogDebug("Hydjet")<<"Number of hard events "<<hyjpar.njet; LogDebug("Hydjet")<<"Number of hard particles "<<nhard_; LogDebug("Hydjet")<<"Number of soft particles "<<nsoft_; vector<HepMC::GenVertex*> sub_vertices(nsub_); int ihy = 0; for(int isub=0;isub<nsub_;isub++){ LogDebug("SubEvent") <<"Sub Event ID : "<<isub; int sub_up = (isub+1)*50000; // Upper limit in mother index, determining the range of Sub-Event vector<HepMC::GenParticle*> particles; vector<int> mother_ids; vector<HepMC::GenVertex*> prods; sub_vertices[isub] = new HepMC::GenVertex(HepMC::FourVector(0,0,0,0),isub); evt->add_vertex(sub_vertices[isub]); if(!evt->signal_process_vertex()) evt->set_signal_process_vertex(sub_vertices[isub]); while(ihy<nhard_+nsoft_ && (hyjets.khj[2][ihy] < sub_up || ihy > nhard_ )){ particles.push_back(build_hyjet(ihy,ihy+1)); prods.push_back(build_hyjet_vertex(ihy,isub)); mother_ids.push_back(hyjets.khj[2][ihy]); LogDebug("DecayChain")<<"Mother index : "<<hyjets.khj[2][ihy]; ihy++; } //Produce Vertices and add them to the GenEvent. Remember that GenParticles are adopted by //GenVertex and GenVertex is adopted by GenEvent. LogDebug("Hydjet")<<"Number of particles in vector "<<particles.size(); for (unsigned int i = 0; i<particles.size(); i++) { HepMC::GenParticle* part = particles[i]; //The Fortran code is modified to preserve mother id info, by seperating the beginning //mother indices of successive subevents by 5000 int mid = mother_ids[i]-isub*50000-1; LogDebug("DecayChain")<<"Particle "<<i; LogDebug("DecayChain")<<"Mother's ID "<<mid; LogDebug("DecayChain")<<"Particle's PDG ID "<<part->pdg_id(); if(mid <= 0){ sub_vertices[isub]->add_particle_out(part); continue; } if(mid > 0){ HepMC::GenParticle* mother = particles[mid]; LogDebug("DecayChain")<<"Mother's PDG ID "<<mother->pdg_id(); HepMC::GenVertex* prod_vertex = mother->end_vertex(); if(!prod_vertex){ prod_vertex = prods[i]; prod_vertex->add_particle_in(mother); evt->add_vertex(prod_vertex); prods[i]=0; // mark to protect deletion } prod_vertex->add_particle_out(part); } } // cleanup vertices not assigned to evt for (unsigned int i = 0; i<prods.size(); i++) { if(prods[i]) delete prods[i]; } } return true; } //______________________________________________________________ bool HydjetHadronizer::call_hyinit(double energy,double a, int ifb, double bmin, double bmax,double bfix,int nh) { // initialize hydjet pydatr.mrpy[2]=1; HYINIT(energy,a,ifb,bmin,bmax,bfix,nh); return true; } //______________________________________________________________ bool HydjetHadronizer::hydjet_init(const ParameterSet &pset) { // set hydjet options // hydjet running mode mode // kHydroOnly --- nhsel=0 jet production off (pure HYDRO event), nhsel=0 // kHydroJets --- nhsle=1 jet production on, jet quenching off (HYDRO+njet*PYTHIA events) // kHydroQJet --- nhsel=2 jet production & jet quenching on (HYDRO+njet*PYQUEN events) // kJetsOnly --- nhsel=3 jet production on, jet quenching off, HYDRO off (njet*PYTHIA events) // kQJetsOnly --- nhsel=4 jet production & jet quenching on, HYDRO off (njet*PYQUEN events) if(hymode_ == "kHydroOnly") hyjpar.nhsel=0; else if ( hymode_ == "kHydroJets") hyjpar.nhsel=1; else if ( hymode_ == "kHydroQJets") hyjpar.nhsel=2; else if ( hymode_ == "kJetsOnly") hyjpar.nhsel=3; else if ( hymode_ == "kQJetsOnly") hyjpar.nhsel=4; else hyjpar.nhsel=2; // fraction of soft hydro induced multiplicity hyflow.fpart = fracsoftmult_; // hadron freez-out temperature hyflow.Tf = hadfreeztemp_; // maximum longitudinal collective rapidity hyflow.ylfl = maxlongy_; // maximum transverse collective rapidity hyflow.ytfl = maxtrany_; // shadowing on=1, off=0 hyjpar.ishad = shadowingswitch_; // set inelastic nucleon-nucleon cross section hyjpar.sigin = signn_; // angular emitted gluon spectrum selection pyqpar.ianglu = angularspecselector_; // number of active quark flavors in qgp pyqpar.nfu = nquarkflavor_; // initial temperature of QGP pyqpar.T0u = qgpt0_; // proper time of QGP formation pyqpar.tau0u = qgptau0_; // type of medium induced partonic energy loss if( doradiativeenloss_ && docollisionalenloss_ ){ edm::LogInfo("HydjetEnLoss") << "##### Radiative AND Collisional partonic energy loss ON ####"; pyqpar.ienglu = 0; } else if ( doradiativeenloss_ ) { edm::LogInfo("HydjetenLoss") << "##### Only RADIATIVE partonic energy loss ON ####"; pyqpar.ienglu = 1; } else if ( docollisionalenloss_ ) { edm::LogInfo("HydjetEnLoss") << "##### Only COLLISIONAL partonic energy loss ON ####"; pyqpar.ienglu = 2; } else { edm::LogInfo("HydjetEnLoss") << "##### Radiative AND Collisional partonic energy loss ON ####"; pyqpar.ienglu = 0; } return true; } //_____________________________________________________________________ bool HydjetHadronizer::readSettings( int ) { Pythia6Service::InstanceWrapper guard(pythia6Service_); pythia6Service_->setGeneralParams(); return true; } //_____________________________________________________________________ bool HydjetHadronizer::initializeForInternalPartons(){ Pythia6Service::InstanceWrapper guard(pythia6Service_); // pythia6Service_->setGeneralParams(); // the input impact parameter (bxx_) is in [fm]; transform in [fm/RA] for hydjet usage const float ra = nuclear_radius(); LogInfo("RAScaling")<<"Nuclear radius(RA) = "<<ra; bmin_ /= ra; bmax_ /= ra; bfixed_ /= ra; // hydjet running options hydjet_init(pset_); // initialize hydjet LogInfo("HYDJETinAction") << "##### Calling HYINIT("<<comenergy<<","<<abeamtarget_<<"," <<cflag_<<","<<bmin_<<","<<bmax_<<","<<bfixed_<<","<<nmultiplicity_<<") ####"; call_hyinit(comenergy,abeamtarget_,cflag_,bmin_,bmax_,bfixed_,nmultiplicity_); return true; } bool HydjetHadronizer::declareStableParticles(const std::vector<int>& _pdg ) { std::vector<int> pdg = _pdg; for ( size_t i=0; i < pdg.size(); i++ ) { int pyCode = pycomp_( pdg[i] ); std::ostringstream pyCard ; pyCard << "MDCY(" << pyCode << ",1)=0"; std::cout << pyCard.str() << std::endl; call_pygive( pyCard.str() ); } return true; } //________________________________________________________________ void HydjetHadronizer::rotateEvtPlane() { const double pi = 3.14159265358979; phi0_ = 2.*pi*gen::pyr_(0) - pi; sinphi0_ = sin(phi0_); cosphi0_ = cos(phi0_); } //________________________________________________________________ bool HydjetHadronizer::hadronize() { return false; } bool HydjetHadronizer::decay() { return true; } bool HydjetHadronizer::residualDecay() { return true; } void HydjetHadronizer::finalizeEvent() { } void HydjetHadronizer::statistics() { } const char* HydjetHadronizer::classname() const { return "gen::HydjetHadronizer"; }
34.261209
113
0.663291
[ "object", "vector", "transform" ]
8017b4bf35cce8d49f58115839060e027df22943
3,974
cpp
C++
baselines/1_CCGrid15/src/model/spliter.cpp
JinYang88/LogZip
796bd632623d010989fb7dfa61f51c72ea6b68b4
[ "MIT" ]
1
2019-10-06T07:31:14.000Z
2019-10-06T07:31:14.000Z
baselines/1_CCGrid15/src/model/spliter.cpp
JinYang88/LogZip
796bd632623d010989fb7dfa61f51c72ea6b68b4
[ "MIT" ]
null
null
null
baselines/1_CCGrid15/src/model/spliter.cpp
JinYang88/LogZip
796bd632623d010989fb7dfa61f51c72ea6b68b4
[ "MIT" ]
null
null
null
/* Cowic is a C++ library to compress formatted log like Apache access log. * * Cowic is released under the New BSD license (see LICENSE.txt). Go to the * project home page for more info: * * https://github.com/linhao1990/cowic.git */ //spliter.cpp #include "spliter.h" const string openChars = "([{'\""; const string closeChars = ")]}'\""; const unsigned char columnDelimiter = ' '; const unsigned char escape = '\\'; const unsigned int MAX_WORD_LEN = 255; const unsigned int MAX_NUMBER_LEN = 3; const unsigned char EOL = 128; //end of line const string EOL_STR(1, EOL); void checkFirstOpen(size_t& lastOpenPos, unsigned char c){ size_t pos = openChars.find(c); if(pos != string::npos){ lastOpenPos = pos; } } void checkMatchClose(size_t& lastOpenPos, unsigned char c){ if(c == closeChars[lastOpenPos]){ lastOpenPos = string::npos; } } void setLastOpenPos(size_t& lastOpenPos, unsigned char c){ if(lastOpenPos == string::npos){ checkFirstOpen(lastOpenPos, c); } else{ checkMatchClose(lastOpenPos, c); } } inline bool isSplittable(const size_t lastOpenPos){ return lastOpenPos == string::npos; } inline bool isColumnDelimiter(unsigned char c){ return c == columnDelimiter; } void Spliter::splitLine2Columns(const string& line, vector<string>& columns){ size_t lastOpenPos = string::npos; bool isDelimiterFound = false; unsigned int lastSplitPos = 0; for(unsigned int i = 0; i < line.size(); i++){ unsigned char c = line[i]; if(c == escape){ //ignore the escape and next character. i++; continue; } if(isDelimiterFound && !isColumnDelimiter(c)){ //split the column and move to next columns.push_back(line.substr(lastSplitPos, i - lastSplitPos)); lastSplitPos = i; isDelimiterFound = false; } setLastOpenPos(lastOpenPos, c); if(isSplittable(lastOpenPos) && isColumnDelimiter(c)){ isDelimiterFound = true; } } if(lastSplitPos < line.size()){ columns.push_back(line.substr(lastSplitPos)); } } enum class CharacterType{ Number, Alphabet, Special }; CharacterType characterType(unsigned char c){ if(c >= '0' && c <= '9') return CharacterType::Number; else if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_') return CharacterType::Alphabet; else return CharacterType::Special; } inline bool reachMaxNumberLength(CharacterType type, unsigned int pos, unsigned int lastPos){ return type == CharacterType::Number && pos - lastPos >= MAX_NUMBER_LEN; } inline bool reachMaxWordLengh(unsigned int pos, unsigned int lastPos){ return pos - lastPos >= MAX_WORD_LEN; } void Spliter::splitColumn2Words(const string& column, vector<string>& words){ if(column.size() == 0) return; unsigned int lastSplitPos = 0; CharacterType lastType = characterType(column[0]); for(unsigned int i = 1; i < column.size(); i++){ CharacterType currType = characterType(column[i]); if(lastType!= currType || reachMaxNumberLength(currType, i, lastSplitPos) || reachMaxWordLengh(i, lastSplitPos)){ words.push_back(column.substr(lastSplitPos, i - lastSplitPos)); lastSplitPos = i; } lastType = currType; } if(lastSplitPos < column.size()){ words.push_back(column.substr(lastSplitPos)); } } bool Spliter::isNewColumn(size_t& lastOpenPos, const string& word){ //TODO try some aggresive improvement for(unsigned int i = 0; i < word.size(); i++){ unsigned char c = word[i]; if(c == escape){ //ignore the escape and next character. i++; continue; } setLastOpenPos(lastOpenPos, c); if((isSplittable(lastOpenPos) && isColumnDelimiter(c)) || c == EOL) return true; } return false; }
29.656716
121
0.632612
[ "vector" ]
801c2004fccd431d3142355c1c3aa9af9288272d
36,867
cpp
C++
src/mame/drivers/gp_2.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/gp_2.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/gp_2.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Robbbert /***************************************************************************************** PINBALL Game Plan MPU-2 When first turned on, you need to press num-0 to enter the setup program, then keep pressing num-0 until 06 shows in the credits display. Press the credit button to set the first high score at which a free credit is awarded. Then press num-0 to set the 2nd high score, then num-0 to set the 3rd high score. Keep pressing num-0 until you exit back to normal operation. If this setup is not done, each player will get 3 free games at the start of ball 1. All the Z80 "maincpu" code is copied from gp_1.cpp Any bug fixes need to be applied both here and there. Sound boards: (each game has its own custom sounds) ------------------------------------------------------------------------------- Old Coney Island 3x SN76477 Sharpshooter 3x SN76477 Super Nova 4x SN76477 Andromeda/Cyclopes 6808/6802/6810 + 6821 + 1 rom + ZN428 Lady Sharpshooter 6808/6802/6810 + 2x6821 + 2xROM + 6840 + discrete (no schematics for the others) Status: - All games are working without sound, except: - gwarfare stops responding to inputs after a while - mbossy rom missing, black screen - andromep, andromepa, cyclopes, cyclopes1 cannot be started with the credit button ToDo: - Sound - Inputs vary per machine ******************************************************************************************/ #include "emu.h" #include "machine/genpin.h" #include "cpu/z80/z80.h" #include "machine/z80daisy.h" #include "machine/i8255.h" #include "machine/clock.h" #include "machine/z80ctc.h" //#include "sound/sn76477.h" //#include "speaker.h" #include "gp_2.lh" namespace { class gp_2_state : public genpin_class { public: gp_2_state(const machine_config &mconfig, device_type type, const char *tag) : genpin_class(mconfig, type, tag) , m_maincpu(*this, "maincpu") , m_ppi(*this, "ppi") , m_ctc(*this, "ctc") , m_io_dsw0(*this, "DSW0") , m_io_dsw1(*this, "DSW1") , m_io_dsw2(*this, "DSW2") , m_io_dsw3(*this, "DSW3") , m_io_x7(*this, "X7") , m_io_x8(*this, "X8") , m_io_x9(*this, "X9") , m_io_xa(*this, "XA") , m_io_xb(*this, "XB") , m_digits(*this, "digit%d", 0U) , m_io_outputs(*this, "out%d", 0U) { } void gp_2(machine_config &config); private: void porta_w(u8 data); void portc_w(u8 data); u8 portb_r(); void io_map(address_map &map); void mem_map(address_map &map); u8 m_u14 = 0U; u8 m_digit = 0U; u8 m_segment[16]{}; u8 m_last_solenoid = 15U; virtual void machine_reset() override; virtual void machine_start() override; required_device<z80_device> m_maincpu; required_device<i8255_device> m_ppi; required_device<z80ctc_device> m_ctc; required_ioport m_io_dsw0; required_ioport m_io_dsw1; required_ioport m_io_dsw2; required_ioport m_io_dsw3; required_ioport m_io_x7; required_ioport m_io_x8; required_ioport m_io_x9; required_ioport m_io_xa; required_ioport m_io_xb; output_finder<40> m_digits; output_finder<64> m_io_outputs; // 16 solenoids + 48 lamps }; void gp_2_state::mem_map(address_map &map) { map(0x0000, 0x3fff).rom(); map(0x8c00, 0x8dff).ram().share("nvram"); } void gp_2_state::io_map(address_map &map) { map.global_mask(0x0f); map(0x04, 0x07).rw(m_ppi, FUNC(i8255_device::read), FUNC(i8255_device::write)); map(0x08, 0x0b).rw(m_ctc, FUNC(z80ctc_device::read), FUNC(z80ctc_device::write)); } static INPUT_PORTS_START( gp_common ) PORT_START("X7") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_3_PAD) PORT_NAME("Accounting Reset") // This pushbutton on the MPU board is called "S33" PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_0) PORT_NAME("Slam Tilt") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_A) PORT_NAME("INP04") PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_COIN3 ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_9) PORT_NAME("Tilt") PORT_START("X8") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_B) PORT_NAME("INP09") PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_C) PORT_NAME("INP10") PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_X) PORT_NAME("Outhole") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_D) PORT_NAME("INP12") PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_E) PORT_NAME("INP13") PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_F) PORT_NAME("INP14") PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_G) PORT_NAME("INP15") PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_H) PORT_NAME("INP16") PORT_START("X9") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_I) PORT_NAME("INP17") PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_J) PORT_NAME("INP18") PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_K) PORT_NAME("INP19") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_L) PORT_NAME("INP20") PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_M) PORT_NAME("INP21") PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_N) PORT_NAME("INP22") PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_O) PORT_NAME("INP23") PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_P) PORT_NAME("INP24") PORT_START("XA") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_Q) PORT_NAME("INP25") PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_0_PAD) PORT_NAME("Setup") PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_R) PORT_NAME("INP27") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_S) PORT_NAME("INP28") PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_T) PORT_NAME("INP29") PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_U) PORT_NAME("INP30") PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_V) PORT_NAME("INP31") PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_W) PORT_NAME("INP32") PORT_START("XB") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_Y) PORT_NAME("INP33") PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_Z) PORT_NAME("INP34") PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_COMMA) PORT_NAME("INP35") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_STOP) PORT_NAME("INP36") PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_SLASH) PORT_NAME("INP37") PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_COLON) PORT_NAME("INP38") PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_QUOTE) PORT_NAME("INP39") PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_KEYPAD ) PORT_CODE(KEYCODE_ENTER) PORT_NAME("INP40") INPUT_PORTS_END static INPUT_PORTS_START( gp_1 ) PORT_START("DSW0") PORT_DIPNAME( 0x1f, 0x02, "Coin Slot 1") PORT_DIPSETTING( 0x00, DEF_STR( 2C_3C )) // same as 01 PORT_DIPSETTING( 0x02, DEF_STR( 1C_1C )) PORT_DIPSETTING( 0x03, DEF_STR( 2C_1C )) PORT_DIPSETTING( 0x04, DEF_STR( 1C_2C )) PORT_DIPSETTING( 0x05, DEF_STR( 2C_2C )) PORT_DIPSETTING( 0x06, DEF_STR( 1C_3C )) PORT_DIPSETTING( 0x07, DEF_STR( 2C_3C )) PORT_DIPSETTING( 0x08, DEF_STR( 1C_4C )) PORT_DIPSETTING( 0x09, DEF_STR( 2C_4C )) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_5C )) PORT_DIPSETTING( 0x0b, DEF_STR( 2C_5C )) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_6C )) PORT_DIPSETTING( 0x0d, DEF_STR( 2C_6C )) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_7C )) PORT_DIPSETTING( 0x0f, DEF_STR( 2C_7C )) PORT_DIPSETTING( 0x10, DEF_STR( 1C_8C )) PORT_DIPSETTING( 0x11, DEF_STR( 2C_8C )) PORT_DIPSETTING( 0x12, DEF_STR( 1C_9C )) PORT_DIPSETTING( 0x13, "2 coins 9 credits") PORT_DIPSETTING( 0x14, "1 coin 10 credits") PORT_DIPSETTING( 0x15, "2 coins 10 credits") PORT_DIPSETTING( 0x16, "1 coin 11 credits") PORT_DIPSETTING( 0x17, "2 coins 11 credits") PORT_DIPSETTING( 0x18, "1 coin 12 credits") PORT_DIPSETTING( 0x19, "2 coins 12 credits") PORT_DIPSETTING( 0x1a, "1 coin 13 credits") PORT_DIPSETTING( 0x1b, "2 coins 13 credits") PORT_DIPSETTING( 0x1c, "1 coin 14 credits") PORT_DIPSETTING( 0x1d, "2 coins 14 credits") PORT_DIPSETTING( 0x1e, "1 coin 15 credits") PORT_DIPSETTING( 0x1f, "2 coins 15 credits") PORT_DIPNAME( 0x20, 0x00, "S06") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x20, DEF_STR( On )) PORT_DIPNAME( 0x40, 0x00, "S07") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x40, DEF_STR( On )) PORT_DIPNAME( 0x80, 0x00, "Free Play") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x80, DEF_STR( On )) PORT_START("DSW1") PORT_DIPNAME( 0x0f, 0x00, "Coin Slot 2") // S09-12 determine coinage for slot 2 PORT_DIPSETTING( 0x00, "Same as Slot 1") PORT_DIPSETTING( 0x01, DEF_STR( 1C_1C )) PORT_DIPSETTING( 0x02, DEF_STR( 1C_2C )) PORT_DIPSETTING( 0x03, DEF_STR( 1C_3C )) PORT_DIPSETTING( 0x04, DEF_STR( 1C_4C )) PORT_DIPSETTING( 0x05, DEF_STR( 1C_5C )) PORT_DIPSETTING( 0x06, DEF_STR( 1C_6C )) PORT_DIPSETTING( 0x07, DEF_STR( 1C_7C )) PORT_DIPSETTING( 0x08, DEF_STR( 1C_8C )) PORT_DIPSETTING( 0x09, DEF_STR( 1C_9C )) PORT_DIPSETTING( 0x0a, "1 coin 10 credits") PORT_DIPSETTING( 0x0b, "1 coin 11 credits") PORT_DIPSETTING( 0x0c, "1 coin 12 credits") PORT_DIPSETTING( 0x0d, "1 coin 13 credits") PORT_DIPSETTING( 0x0e, "1 coin 14 credits") PORT_DIPSETTING( 0x0f, "1 coin 15 credits") PORT_DIPNAME( 0x10, 0x00, "S13") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x10, DEF_STR( On )) PORT_DIPNAME( 0x20, 0x00, "S14") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x20, DEF_STR( On )) PORT_DIPNAME( 0x40, 0x00, "S15") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x40, DEF_STR( On )) PORT_DIPNAME( 0x80, 0x00, "Play Tunes") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x80, DEF_STR( On )) PORT_START("DSW2") PORT_DIPNAME( 0x1f, 0x02, "Coin Slot 3") PORT_DIPSETTING( 0x00, DEF_STR( 2C_3C )) // same as 01 PORT_DIPSETTING( 0x02, DEF_STR( 1C_1C )) PORT_DIPSETTING( 0x03, DEF_STR( 2C_1C )) PORT_DIPSETTING( 0x04, DEF_STR( 1C_2C )) PORT_DIPSETTING( 0x05, DEF_STR( 2C_2C )) PORT_DIPSETTING( 0x06, DEF_STR( 1C_3C )) PORT_DIPSETTING( 0x07, DEF_STR( 2C_3C )) PORT_DIPSETTING( 0x08, DEF_STR( 1C_4C )) PORT_DIPSETTING( 0x09, DEF_STR( 2C_4C )) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_5C )) PORT_DIPSETTING( 0x0b, DEF_STR( 2C_5C )) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_6C )) PORT_DIPSETTING( 0x0d, DEF_STR( 2C_6C )) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_7C )) PORT_DIPSETTING( 0x0f, DEF_STR( 2C_7C )) PORT_DIPSETTING( 0x10, DEF_STR( 1C_8C )) PORT_DIPSETTING( 0x11, DEF_STR( 2C_8C )) PORT_DIPSETTING( 0x12, DEF_STR( 1C_9C )) PORT_DIPSETTING( 0x13, "2 coins 9 credits") PORT_DIPSETTING( 0x14, "1 coin 10 credits") PORT_DIPSETTING( 0x15, "2 coins 10 credits") PORT_DIPSETTING( 0x16, "1 coin 11 credits") PORT_DIPSETTING( 0x17, "2 coins 11 credits") PORT_DIPSETTING( 0x18, "1 coin 12 credits") PORT_DIPSETTING( 0x19, "2 coins 12 credits") PORT_DIPSETTING( 0x1a, "1 coin 13 credits") PORT_DIPSETTING( 0x1b, "2 coins 13 credits") PORT_DIPSETTING( 0x1c, "1 coin 14 credits") PORT_DIPSETTING( 0x1d, "2 coins 14 credits") PORT_DIPSETTING( 0x1e, "1 coin 15 credits") PORT_DIPSETTING( 0x1f, "2 coins 15 credits") PORT_DIPNAME( 0x20, 0x00, "S22") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x20, DEF_STR( On )) PORT_DIPNAME( 0x40, 0x00, "S23") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x40, DEF_STR( On )) PORT_DIPNAME( 0x80, 0x00, "S24") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x80, DEF_STR( On )) PORT_START("DSW3") PORT_DIPNAME( 0x07, 0x02, "Max number of credits") PORT_DIPSETTING( 0x00, "5" ) PORT_DIPSETTING( 0x01, "10") PORT_DIPSETTING( 0x02, "15") PORT_DIPSETTING( 0x03, "20") PORT_DIPSETTING( 0x04, "25") PORT_DIPSETTING( 0x05, "30") PORT_DIPSETTING( 0x06, "35") PORT_DIPSETTING( 0x07, "40") PORT_DIPNAME( 0x08, 0x00, "Balls") PORT_DIPSETTING( 0x00, "3") PORT_DIPSETTING( 0x08, "5") PORT_DIPNAME( 0x10, 0x10, "Award") PORT_DIPSETTING( 0x00, "Extra Ball") PORT_DIPSETTING( 0x10, "Replay") PORT_DIPNAME( 0x20, 0x20, "Match") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x20, DEF_STR( On )) PORT_DIPNAME( 0xC0, 0x80, "Credits for exceeding high score") PORT_DIPSETTING( 0x00, "0") PORT_DIPSETTING( 0x40, "1") PORT_DIPSETTING( 0x80, "2") PORT_DIPSETTING( 0xC0, "3") PORT_INCLUDE(gp_common) INPUT_PORTS_END static INPUT_PORTS_START( gp_2 ) PORT_START("DSW0") PORT_DIPNAME( 0x1f, 0x02, "Coin Slot 1") PORT_DIPSETTING( 0x00, DEF_STR( 2C_3C )) // same as 01 PORT_DIPSETTING( 0x02, DEF_STR( 1C_1C )) PORT_DIPSETTING( 0x03, DEF_STR( 2C_1C )) PORT_DIPSETTING( 0x04, DEF_STR( 1C_2C )) PORT_DIPSETTING( 0x05, DEF_STR( 2C_2C )) PORT_DIPSETTING( 0x06, DEF_STR( 1C_3C )) PORT_DIPSETTING( 0x07, DEF_STR( 2C_3C )) PORT_DIPSETTING( 0x08, DEF_STR( 1C_4C )) PORT_DIPSETTING( 0x09, DEF_STR( 2C_4C )) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_5C )) PORT_DIPSETTING( 0x0b, DEF_STR( 2C_5C )) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_6C )) PORT_DIPSETTING( 0x0d, DEF_STR( 2C_6C )) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_7C )) PORT_DIPSETTING( 0x0f, DEF_STR( 2C_7C )) PORT_DIPSETTING( 0x10, DEF_STR( 1C_8C )) PORT_DIPSETTING( 0x11, DEF_STR( 2C_8C )) PORT_DIPSETTING( 0x12, DEF_STR( 1C_9C )) PORT_DIPSETTING( 0x13, "2 coins 9 credits") PORT_DIPSETTING( 0x14, "1 coin 10 credits") PORT_DIPSETTING( 0x15, "2 coins 10 credits") PORT_DIPSETTING( 0x16, "1 coin 11 credits") PORT_DIPSETTING( 0x17, "2 coins 11 credits") PORT_DIPSETTING( 0x18, "1 coin 12 credits") PORT_DIPSETTING( 0x19, "2 coins 12 credits") PORT_DIPSETTING( 0x1a, "1 coin 13 credits") PORT_DIPSETTING( 0x1b, "2 coins 13 credits") PORT_DIPSETTING( 0x1c, "1 coin 14 credits") PORT_DIPSETTING( 0x1d, "2 coins 14 credits") PORT_DIPSETTING( 0x1e, "1 coin 15 credits") PORT_DIPSETTING( 0x1f, "2 coins 15 credits") PORT_DIPNAME( 0x60, 0x00, "Special lights at") PORT_DIPSETTING( 0x60, "60000") PORT_DIPSETTING( 0x40, "90000") PORT_DIPSETTING( 0x20, "120000") PORT_DIPSETTING( 0x00, "150000") PORT_DIPNAME( 0x80, 0x00, "Free Play") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x80, DEF_STR( On )) PORT_START("DSW1") PORT_DIPNAME( 0x0f, 0x00, "Coin Slot 2") // S09-12 determine coinage for slot 2 PORT_DIPSETTING( 0x00, "Same as Slot 1") PORT_DIPSETTING( 0x01, DEF_STR( 1C_1C )) PORT_DIPSETTING( 0x02, DEF_STR( 1C_2C )) PORT_DIPSETTING( 0x03, DEF_STR( 1C_3C )) PORT_DIPSETTING( 0x04, DEF_STR( 1C_4C )) PORT_DIPSETTING( 0x05, DEF_STR( 1C_5C )) PORT_DIPSETTING( 0x06, DEF_STR( 1C_6C )) PORT_DIPSETTING( 0x07, DEF_STR( 1C_7C )) PORT_DIPSETTING( 0x08, DEF_STR( 1C_8C )) PORT_DIPSETTING( 0x09, DEF_STR( 1C_9C )) PORT_DIPSETTING( 0x0a, "1 coin 10 credits") PORT_DIPSETTING( 0x0b, "1 coin 11 credits") PORT_DIPSETTING( 0x0c, "1 coin 12 credits") PORT_DIPSETTING( 0x0d, "1 coin 13 credits") PORT_DIPSETTING( 0x0e, "1 coin 14 credits") PORT_DIPSETTING( 0x0f, "1 coin 15 credits") PORT_DIPNAME( 0x10, 0x10, "Music") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x10, DEF_STR( On )) PORT_DIPNAME( 0x20, 0x20, "Extra Ball") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x20, DEF_STR( On )) PORT_DIPNAME( 0x40, 0x40, "Remember Saucer Values") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x40, DEF_STR( On )) PORT_DIPNAME( 0x80, 0x80, "Extra Ball lights at") PORT_DIPSETTING( 0x80, "100000") PORT_DIPSETTING( 0x00, "150000") PORT_START("DSW2") PORT_DIPNAME( 0x1f, 0x02, "Coin Slot 3") PORT_DIPSETTING( 0x00, DEF_STR( 2C_3C )) // same as 01 PORT_DIPSETTING( 0x02, DEF_STR( 1C_1C )) PORT_DIPSETTING( 0x03, DEF_STR( 2C_1C )) PORT_DIPSETTING( 0x04, DEF_STR( 1C_2C )) PORT_DIPSETTING( 0x05, DEF_STR( 2C_2C )) PORT_DIPSETTING( 0x06, DEF_STR( 1C_3C )) PORT_DIPSETTING( 0x07, DEF_STR( 2C_3C )) PORT_DIPSETTING( 0x08, DEF_STR( 1C_4C )) PORT_DIPSETTING( 0x09, DEF_STR( 2C_4C )) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_5C )) PORT_DIPSETTING( 0x0b, DEF_STR( 2C_5C )) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_6C )) PORT_DIPSETTING( 0x0d, DEF_STR( 2C_6C )) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_7C )) PORT_DIPSETTING( 0x0f, DEF_STR( 2C_7C )) PORT_DIPSETTING( 0x10, DEF_STR( 1C_8C )) PORT_DIPSETTING( 0x11, DEF_STR( 2C_8C )) PORT_DIPSETTING( 0x12, DEF_STR( 1C_9C )) PORT_DIPSETTING( 0x13, "2 coins 9 credits") PORT_DIPSETTING( 0x14, "1 coin 10 credits") PORT_DIPSETTING( 0x15, "2 coins 10 credits") PORT_DIPSETTING( 0x16, "1 coin 11 credits") PORT_DIPSETTING( 0x17, "2 coins 11 credits") PORT_DIPSETTING( 0x18, "1 coin 12 credits") PORT_DIPSETTING( 0x19, "2 coins 12 credits") PORT_DIPSETTING( 0x1a, "1 coin 13 credits") PORT_DIPSETTING( 0x1b, "2 coins 13 credits") PORT_DIPSETTING( 0x1c, "1 coin 14 credits") PORT_DIPSETTING( 0x1d, "2 coins 14 credits") PORT_DIPSETTING( 0x1e, "1 coin 15 credits") PORT_DIPSETTING( 0x1f, "2 coins 15 credits") PORT_DIPNAME( 0x20, 0x00, "Remember Bonus Multiplier") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x20, DEF_STR( On )) PORT_DIPNAME( 0xc0, 0x80, "Balls") PORT_DIPSETTING( 0x00, "1") PORT_DIPSETTING( 0x40, "2") PORT_DIPSETTING( 0x80, "3") PORT_DIPSETTING( 0xc0, "5") PORT_START("DSW3") PORT_DIPNAME( 0x01, 0x00, "Remember Special and Extra Ball lanes") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x01, DEF_STR( On )) PORT_DIPNAME( 0x06, 0x04, "Max number of credits") PORT_DIPSETTING( 0x00, "10") PORT_DIPSETTING( 0x02, "20") PORT_DIPSETTING( 0x04, "30") PORT_DIPSETTING( 0x06, "40") PORT_DIPNAME( 0x18, 0x18, "Award") PORT_DIPSETTING( 0x00, DEF_STR( None )) PORT_DIPSETTING( 0x08, "50000 points") PORT_DIPSETTING( 0x10, "Extra Ball") PORT_DIPSETTING( 0x18, "Replay") PORT_DIPNAME( 0x20, 0x20, "Match") PORT_DIPSETTING( 0x00, DEF_STR( Off )) PORT_DIPSETTING( 0x20, DEF_STR( On )) PORT_DIPNAME( 0xC0, 0x80, "Credits for exceeding high score") PORT_DIPSETTING( 0x00, "0") PORT_DIPSETTING( 0x40, "1") PORT_DIPSETTING( 0x80, "2") PORT_DIPSETTING( 0xC0, "3") PORT_INCLUDE(gp_common) INPUT_PORTS_END u8 gp_2_state::portb_r() { switch (m_u14) { case 7: return m_io_x7->read(); case 8: return m_io_x8->read(); case 9: return m_io_x9->read(); case 10: return m_io_xa->read(); case 11: return m_io_xb->read(); case 12: return m_io_dsw0->read(); case 13: return m_io_dsw1->read(); case 14: return m_io_dsw2->read(); case 15: return m_io_dsw3->read(); } return 0; } void gp_2_state::porta_w(u8 data) { m_u14 = data >> 4; if (m_last_solenoid < 15) m_io_outputs[m_last_solenoid] = 0; m_u14 = data >> 4; // Solenoids are different per game, no point allocating anything specific if ((m_u14 >= 1) && (m_u14 <= 2)) { if ((data & 15) < 15) m_io_outputs[data & 15] = 1; m_last_solenoid = data & 15; } else m_last_solenoid = 15; static const u8 patterns[16] = { 0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7c,0x07,0x7f,0x67,0x58,0x4c,0x62,0x69,0x78,0 }; // 7448 if (m_digit == 7) m_segment[m_u14] = data & 15; else if (m_u14 == 7) { m_digits[m_digit] = patterns[m_segment[7]]; m_digits[m_digit+8] = patterns[m_segment[8]]; m_digits[m_digit+16] = patterns[m_segment[9]]; m_digits[m_digit+24] = patterns[m_segment[10]]; m_digits[m_digit+32] = patterns[m_segment[11]]; } // Lamps if ((m_u14 >= 3) && (m_u14 <= 5)) for (u8 i = 0; i < 16; i++) m_io_outputs[(m_u14 - 3) * 16 + 16 + i] = ((data & 15) == i); } void gp_2_state::portc_w(u8 data) { output().set_value("led0", !BIT(data, 3)); m_digit = data & 7; } void gp_2_state::machine_start() { genpin_class::machine_start(); m_digits.resolve(); m_io_outputs.resolve(); save_item(NAME(m_u14)); save_item(NAME(m_digit)); save_item(NAME(m_segment)); save_item(NAME(m_last_solenoid)); } void gp_2_state::machine_reset() { genpin_class::machine_reset(); m_u14 = 0; m_digit = 0xff; m_last_solenoid = 15; for (u8 i = 0; i < m_io_outputs.size(); i++) m_io_outputs[i] = 0; for (u8 i = 0; i < std::size(m_segment); i++) m_segment[i] = 0; } static const z80_daisy_config daisy_chain[] = { { "ctc" }, { nullptr } }; void gp_2_state::gp_2(machine_config &config) { /* basic machine hardware */ Z80(config, m_maincpu, 2457600); m_maincpu->set_addrmap(AS_PROGRAM, &gp_2_state::mem_map); m_maincpu->set_addrmap(AS_IO, &gp_2_state::io_map); m_maincpu->set_daisy_config(daisy_chain); NVRAM(config, "nvram", nvram_device::DEFAULT_ALL_0); /* Video */ config.set_default_layout(layout_gp_2); /* Sound */ genpin_audio(config); /* Devices */ I8255A(config, m_ppi); m_ppi->out_pa_callback().set(FUNC(gp_2_state::porta_w)); m_ppi->in_pb_callback().set(FUNC(gp_2_state::portb_r)); m_ppi->out_pc_callback().set(FUNC(gp_2_state::portc_w)); Z80CTC(config, m_ctc, 2457600); m_ctc->intr_callback().set_inputline(m_maincpu, INPUT_LINE_IRQ0); // Todo: absence of ints will cause a watchdog reset clock_device &cpoint_clock(CLOCK(config, "cpoint_clock", 120)); // crosspoint detector cpoint_clock.signal_handler().set(m_ctc, FUNC(z80ctc_device::trg2)); } /* ========== ALTERNATE ROMS ======================================================================= This is a list of known alternate roms. Nothing has been tested. Agents 777 ROM_LOAD( "770ab", 0x0000, 0x1000, CRC(e7f901c4) SHA1(c28c472e7890aaa10a6a47d8729bd6aebd15a20e) ) Andromeda ROM_LOAD( "850.c", 0x1000, 0x0800, CRC(75dc73c4) SHA1(79fadec7650a1419f47b22875dee6f678114b439) ) // used by mbossy Attila the Hun ROM_LOAD( "260.a_b", 0x0000, 0x1000, CRC(0030ce7f) SHA1(44921f3c771c90f09cac3c927915aa8ff70bd782) ) Captain Hook ROM_LOAD( "780a-b.13", 0x0000, 0x1000, CRC(ec757bb7) SHA1(0a10143cf7a60f2a39f36e8c40b5ce52cab04d0b) ) Lady Sharpshooter ROM_LOAD( "830co.716", 0x0000, 0x1000, CRC(e3970bab) SHA1(f5be9a51c382a87dd304c39b27fc468a7f0a74f3) ) ROM_LOAD( "830ab.732", 0x0000, 0x1000, CRC(9ca19183) SHA1(83e73e809c2484396348990bfdfae143ac371f9a) ) Mike Bossy ROM_LOAD( "snd-ic9.a", 0x0000, 0x1000, CRC(b0541739) SHA1(5392fa6a405ba2e09ad4d0ec52c48675bf507532) ) Pinball Lizard ROM_LOAD( "9316b.lef", 0x0000, 0x0895, CRC(c0fb2543) SHA1(8e44f513e8f2afed2a40a6a3bb8637ab18631d2b) ) // not a rom */ /*------------------------------------------------------------------- / Agents 777 (November 1984) - Model #770 /-------------------------------------------------------------------*/ ROM_START(agent777) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "770a", 0x0000, 0x0800, CRC(fc4eebcd) SHA1(742a201e89c1357d2a1f24b0acf3b78ffec96c74)) ROM_LOAD( "770b", 0x0800, 0x0800, CRC(ea62aece) SHA1(32be10bc76a59e03c3fd3294daefc8d28c20386a)) ROM_LOAD( "770c", 0x1000, 0x0800, CRC(59280db7) SHA1(8f199be7bfbc01466541c07dc4c365e20055a66c)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD ("770snd", 0x3800, 0x0800, CRC(e4e66c9f) SHA1(f373facefb18c64377da47308a8bbd5fc80e9c2d)) ROM_CONTINUE(0x7800, 0x0800) ROM_RELOAD (0xf000, 0x1000) ROM_END /*------------------------------------------------------------------- / Andromeda (August 1985) - Model #850 /-------------------------------------------------------------------*/ ROM_START(andromep) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "850.a", 0x0000, 0x1000, CRC(67ed03ee) SHA1(efe7c495766ffb73545a77ab24f02925ac0395f1)) ROM_LOAD( "850.b", 0x1000, 0x1000, CRC(37c244e8) SHA1(5cef0a1a6f2c34f2d01bdd12ce11da40c8be4296)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD("850.snd", 0x3800, 0x0800, CRC(18e084a6) SHA1(56efbabe60305f168ca479295577bff7f3a4dace)) ROM_RELOAD(0x7800, 0x0800) ROM_RELOAD(0xf800, 0x0800) ROM_END ROM_START(andromepa) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "850.a", 0x0000, 0x1000, CRC(67ed03ee) SHA1(efe7c495766ffb73545a77ab24f02925ac0395f1)) ROM_LOAD( "850b.rom", 0x1000, 0x1000, CRC(fc1829a5) SHA1(9761543d17c0a5c08b0fec45c35648ce769a3463)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD("850.snd", 0x3800, 0x0800, CRC(18e084a6) SHA1(56efbabe60305f168ca479295577bff7f3a4dace)) ROM_RELOAD(0x7800, 0x0800) ROM_RELOAD(0xf800, 0x0800) ROM_END /*------------------------------------------------------------------- / Attila the Hun (April 1984) - Model #260 /-------------------------------------------------------------------*/ ROM_START(attila) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "260.a", 0x0000, 0x0800, CRC(b31c11d8) SHA1(d3f2ad84cc28e99acb54349b232dbf8abdf15b21)) ROM_LOAD( "260.b", 0x0800, 0x0800, CRC(e8cca86d) SHA1(ed0797175a573537be2d5119ad68b1847e49e578)) ROM_LOAD( "260.c", 0x1000, 0x0800, CRC(206605c3) SHA1(14f61a2f43c29370bcb6db29969e8dfcfe3da1ab)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD ("260.snd", 0x3800, 0x0800, CRC(21e6b188) SHA1(84148942e6007d49bb4085ec3678954d48e4439e)) ROM_CONTINUE(0x7800, 0x0800) ROM_RELOAD (0xf000, 0x1000) ROM_END /*------------------------------------------------------------------- / Captain Hook (April 1985) - Model #780 /-------------------------------------------------------------------*/ ROM_START(cpthook) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "780.a", 0x0000, 0x0800, CRC(6bd5a495) SHA1(8462e0c68176daee6b23dce9091f5aee99e62631)) ROM_LOAD( "780.b", 0x0800, 0x0800, CRC(3d1c5555) SHA1(ecb0d40f5e6e37acfc8589816e24b26525273393)) ROM_LOAD( "780.c", 0x1000, 0x0800, CRC(e54bc51f) SHA1(3480e0cdd43f9ac3fda8cd466b2f039210525e8b)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD ("780.snd", 0x3800, 0x0800, CRC(95af3392) SHA1(73a2b583b7fc423c2e4390667aebc90ad41f4f93)) ROM_CONTINUE(0x7800, 0x0800) ROM_RELOAD (0xf000, 0x1000) ROM_END /*------------------------------------------------------------------- / Cyclopes (November 1985) - Model #800 /-------------------------------------------------------------------*/ ROM_START(cyclopes) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "800.a", 0x0000, 0x1000, CRC(3e9628e5) SHA1(4dad9e082a9f4140162bc155f2b0f0a948ba012f)) ROM_LOAD( "800.b", 0x1000, 0x1000, CRC(3f945c46) SHA1(25eb543e0b0edcd0a0dcf8e4aa1405cda55ebe2e)) ROM_LOAD( "800.c", 0x2000, 0x1000, CRC(7ea18e65) SHA1(e86d82e3ba659499dfbf14920b196252784724f7)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD ("800.snd", 0x3800, 0x0800, CRC(290db3d2) SHA1(a236594f7a89969981bd5707d6dfbb5120fb8f46)) ROM_CONTINUE(0x7800, 0x0800) ROM_RELOAD (0xf000, 0x1000) ROM_END ROM_START(cyclopes1) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "800a.111585", 0x0000, 0x1000, CRC(13131b90) SHA1(33f6c4aaaa2511a9c78e68f8df9a6461cd92c23f)) ROM_LOAD( "800b.111585", 0x1000, 0x1000, CRC(3d515632) SHA1(2c4a7f18760b591a85331fa0304177a730540489)) ROM_LOAD( "800c.111585", 0x2000, 0x1000, CRC(2078bd3f) SHA1(fed719ffdbd71242393c0786ad6e763a9e25ff8e)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD ("800.snd", 0x3800, 0x0800, CRC(290db3d2) SHA1(a236594f7a89969981bd5707d6dfbb5120fb8f46)) ROM_CONTINUE(0x7800, 0x0800) ROM_RELOAD (0xf000, 0x1000) ROM_END /*------------------------------------------------------------------- / Global Warfare (June 1981) - Model #240 /-------------------------------------------------------------------*/ ROM_START(gwarfare) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "240a.716", 0x0000, 0x0800, CRC(30206428) SHA1(7a9029e4fd4c4c00da3256ed06464c0bd8022168)) ROM_LOAD( "240b.716", 0x0800, 0x0800, CRC(a54eb15d) SHA1(b9235bd188c1251eb213789800b7686b5e3c557f)) ROM_LOAD( "240c.716", 0x1000, 0x0800, CRC(60d115a8) SHA1(e970fdd7cbbb2c81ab8c8209edfb681798c683b9)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD("gw240bot.rom", 0x3800, 0x0800, CRC(3245a206) SHA1(b321b2d276fbd74199eff2d8c0d1b8a2f5c93604)) ROM_RELOAD(0xf800, 0x0800) ROM_LOAD("gw240top.rom",0x3000, 0x0800, CRC(faaf3de1) SHA1(9c984d1ac696eb16f7bf35463a69a470344314a7)) ROM_END /*------------------------------------------------------------------- / Lady Sharpshooter (May 1985) - Cocktail Model #830 /-------------------------------------------------------------------*/ ROM_START(ladyshot) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "830a.716", 0x0000, 0x0800, CRC(c055b993) SHA1(a9a7156e5ec0a32db1ffe36b3c6280953a2606ff)) ROM_LOAD( "830b.716", 0x0800, 0x0800, CRC(1e3308ea) SHA1(a5955a6a15b33c4cf35105ab524a8e7e03d748b6)) ROM_LOAD( "830c.716", 0x1000, 0x0800, CRC(f5e1db15) SHA1(e8168ab37ba30211045fc96b23dad5f06592b38d)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD ("830.snd", 0x3800, 0x0800, NO_DUMP) ROM_CONTINUE(0x7800, 0x0800) ROM_RELOAD (0xf000, 0x1000) ROM_END ROM_START(ladyshota) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "830a2.716", 0x0000, 0x0800, CRC(2c1f1629) SHA1(9233ce4328d779ff6548cdd5d6819cd368bef313)) ROM_LOAD( "830b2.716", 0x0800, 0x0800, CRC(2105a538) SHA1(0360d3e740d8b6f816cfe7fe1fb32ac476251b9f)) ROM_LOAD( "830c2.716", 0x1000, 0x0800, CRC(2d96bdde) SHA1(7c03a29a91f03fba9ed5e53a93335113a7cbafb3)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD ("830.snd", 0x3800, 0x0800, NO_DUMP) ROM_CONTINUE(0x7800, 0x0800) ROM_RELOAD (0xf000, 0x1000) ROM_END /*------------------------------------------------------------------- / Loch Ness Monster (November 1985) - Model #??? (prototype only) /-------------------------------------------------------------------*/ // 1 prototype exists. Company closed down just as game was about to go into production. /*------------------------------------------------------------------- / Mike Bossy (January 1982) - Model #??? (prototype only) /-------------------------------------------------------------------*/ ROM_START(mbossy) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "mb_a.716", 0x0000, 0x0800, CRC(a811f936) SHA1(f44fed7acd26a621f105925d52405e985d0b5e5d) ) ROM_LOAD( "mb_b.716", 0x0800, 0x0800, CRC(75ec7247) SHA1(10fa1e3ac2adbd7b24744a4fb0149bcc74df6b4c) ) ROM_LOAD( "mb_c.716", 0x1000, 0x0800, CRC(75dc73c4) SHA1(79fadec7650a1419f47b22875dee6f678114b439) ) ROM_LOAD( "mb_d.716", 0x1800, 0x0800, NO_DUMP) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD("mb.u9", 0x3800, 0x0800, CRC(dfa98db5) SHA1(65361630f530383e67837c428050bcdb15373c0b)) ROM_RELOAD(0xf800, 0x0800) ROM_LOAD("mb.u10",0x3000, 0x0800, CRC(2d3c91f9) SHA1(7e1f067af29d9e484da234382d7dc821ca07b6c4)) ROM_END /*------------------------------------------------------------------- / Old Coney Island! (December 1979) - Model #180 /-------------------------------------------------------------------*/ ROM_START(coneyis) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "130a.716", 0x0000, 0x0800, CRC(dc402b37) SHA1(90c46391a1e5f000f3b235d580463bf96b45bd3e)) ROM_LOAD( "130b.716", 0x0800, 0x0800, CRC(19a86f5e) SHA1(bc4a87314fc9c4e74e492c3f6e44d5d6cae72939)) ROM_LOAD( "130c.716", 0x1000, 0x0800, CRC(b956f67b) SHA1(ff64383d7f59e9bbec588553e35a21fb94c7203b)) ROM_END /*------------------------------------------------------------------- / Pinball Lizard (June / July 1980) - Model #210 /-------------------------------------------------------------------*/ ROM_START(lizard) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "130a.716", 0x0000, 0x0800, CRC(dc402b37) SHA1(90c46391a1e5f000f3b235d580463bf96b45bd3e)) // u12 ROM_LOAD( "130b.716", 0x0800, 0x0800, CRC(19a86f5e) SHA1(bc4a87314fc9c4e74e492c3f6e44d5d6cae72939)) // u13 ROM_LOAD( "130c.716", 0x1000, 0x0800, CRC(b956f67b) SHA1(ff64383d7f59e9bbec588553e35a21fb94c7203b)) // u26 ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD("lizard.u9", 0x3800, 0x0800, CRC(2d121b24) SHA1(55c16951538229571165c35a353da53e22d11f81)) ROM_RELOAD(0xf800, 0x0800) ROM_LOAD("lizard.u10",0x3000, 0x0800, CRC(28b8f1f0) SHA1(db6d816366e0bca59376f6f8bf87e6a2d849aa72)) ROM_END /*------------------------------------------------------------------- / Sharp Shooter II (November 1983) - Model #730 /-------------------------------------------------------------------*/ ROM_START(sshootr2) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "130a.716", 0x0000, 0x0800, CRC(dc402b37) SHA1(90c46391a1e5f000f3b235d580463bf96b45bd3e)) ROM_LOAD( "130b.716", 0x0800, 0x0800, CRC(19a86f5e) SHA1(bc4a87314fc9c4e74e492c3f6e44d5d6cae72939)) ROM_LOAD( "730c", 0x1000, 0x0800, CRC(d1af712b) SHA1(9dce2ec1c2d9630a29dd21f4685c09019e59b147)) ROM_REGION(0x10000, "cpu2", 0) ROM_LOAD("730u9.snd", 0x3800, 0x0800, CRC(dfa98db5) SHA1(65361630f530383e67837c428050bcdb15373c0b)) ROM_RELOAD(0xf800, 0x0800) ROM_LOAD("730u10.snd",0x3000, 0x0800, CRC(6d3dcf44) SHA1(3703313d4172ebfec1dcacca949076541ee35cb7)) ROM_END /*------------------------------------------------------------------- / Sharpshooter (May 1979) - Model #130 /-------------------------------------------------------------------*/ ROM_START(sshootep) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "130a.716", 0x0000, 0x0800, CRC(dc402b37) SHA1(90c46391a1e5f000f3b235d580463bf96b45bd3e)) ROM_LOAD( "130b.716", 0x0800, 0x0800, CRC(19a86f5e) SHA1(bc4a87314fc9c4e74e492c3f6e44d5d6cae72939)) ROM_LOAD( "130c.716", 0x1000, 0x0800, CRC(b956f67b) SHA1(ff64383d7f59e9bbec588553e35a21fb94c7203b)) ROM_END /*------------------------------------------------------------------- / Super Nova (May 1982) - Model #150 /-------------------------------------------------------------------*/ ROM_START(suprnova) ROM_REGION(0x4000, "maincpu", ROMREGION_ERASEFF) ROM_LOAD( "130a.716", 0x0000, 0x0800, CRC(dc402b37) SHA1(90c46391a1e5f000f3b235d580463bf96b45bd3e)) ROM_LOAD( "150b.716", 0x0800, 0x0800, CRC(8980a8bb) SHA1(129816fe85681b760307a713c667737a750b0c04)) ROM_LOAD( "150c.716", 0x1000, 0x0800, CRC(6fe08f96) SHA1(1309619a2400674fa1d05dc9214fdb85419fd1c3)) ROM_END } // anonymous namespace // GP1 dips GAME( 1979, sshootep, 0, gp_2, gp_1, gp_2_state, empty_init, ROT0, "Game Plan", "Sharpshooter (Game Plan)", MACHINE_IS_SKELETON_MECHANICAL ) GAME( 1979, coneyis, 0, gp_2, gp_1, gp_2_state, empty_init, ROT0, "Game Plan", "Old Coney Island!", MACHINE_IS_SKELETON_MECHANICAL ) GAME( 1980, lizard, 0, gp_2, gp_1, gp_2_state, empty_init, ROT0, "Game Plan", "Pinball Lizard", MACHINE_IS_SKELETON_MECHANICAL ) GAME( 1982, suprnova, 0, gp_2, gp_1, gp_2_state, empty_init, ROT0, "Game Plan", "Super Nova (Game Plan)", MACHINE_IS_SKELETON_MECHANICAL ) GAME( 1983, sshootr2, 0, gp_2, gp_1, gp_2_state, empty_init, ROT0, "Game Plan", "Sharp Shooter II", MACHINE_IS_SKELETON_MECHANICAL ) // GP2 dips GAME( 1981, gwarfare, 0, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Global Warfare", MACHINE_IS_SKELETON_MECHANICAL ) GAME( 1982, mbossy, 0, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Mike Bossy", MACHINE_IS_SKELETON_MECHANICAL) GAME( 1984, attila, 0, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Attila The Hun", MACHINE_IS_SKELETON_MECHANICAL ) // revolving match GAME( 1984, agent777, 0, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Agents 777", MACHINE_IS_SKELETON_MECHANICAL ) GAME( 1985, cpthook, 0, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Captain Hook", MACHINE_IS_SKELETON_MECHANICAL ) GAME( 1985, ladyshot, 0, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Lady Sharpshooter (set 1)", MACHINE_IS_SKELETON_MECHANICAL ) GAME( 1985, ladyshota, ladyshot, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Lady Sharpshooter (set 2)", MACHINE_IS_SKELETON_MECHANICAL ) // credit (start) button not working GAME( 1985, andromep, 0, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Andromeda (set 1)", MACHINE_IS_SKELETON_MECHANICAL) GAME( 1985, andromepa, andromep, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Andromeda (set 2)", MACHINE_IS_SKELETON_MECHANICAL) GAME( 1985, cyclopes, 0, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Cyclopes (12/85)", MACHINE_IS_SKELETON_MECHANICAL) GAME( 1985, cyclopes1, cyclopes, gp_2, gp_2, gp_2_state, empty_init, ROT0, "Game Plan", "Cyclopes (11/85)", MACHINE_IS_SKELETON_MECHANICAL)
42.868605
152
0.684542
[ "model" ]
801c4fbe28237727e20141d483eb34cd120ddfd3
91,148
cpp
C++
cheats/menu.cpp
xsoma/Legendware-V3
de63ad96fe233f81c5952c327469239de223f08c
[ "Unlicense" ]
13
2021-03-12T14:30:32.000Z
2022-02-22T12:25:08.000Z
cheats/menu.cpp
xsoma/Legendware-V3
de63ad96fe233f81c5952c327469239de223f08c
[ "Unlicense" ]
2
2021-07-19T20:51:14.000Z
2021-11-21T06:15:25.000Z
cheats/menu.cpp
CSGOLeaks/Legendware-V3
de63ad96fe233f81c5952c327469239de223f08c
[ "Unlicense" ]
17
2021-02-10T08:33:02.000Z
2022-03-03T17:14:24.000Z
#include <ShlObj_core.h> #include "menu.h" #include "../ImGui/code_editor.h" #include "../constchars.h" #include "../cheats/misc/logs.h" #define ALPHA (ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaBar| ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_Float) #define NOALPHA (ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_Float) // TODO: crypt_str check for all strings std::vector <std::string> files; std::vector <std::string> scripts; int selected_script = 0; static bool menu_setupped = false; IDirect3DTexture9* all_skins[36]; std::string get_wep(int id, int custom_index = -1, bool knife = true) { if (custom_index > -1) { if (knife) { switch (custom_index) { case 0: return "weapon_knife"; case 1: return "weapon_bayonet"; case 2: return "weapon_knife_css"; case 3: return "weapon_knife_skeleton"; case 4: return "weapon_knife_outdoor"; case 5: return "weapon_knife_cord"; case 6: return "weapon_knife_canis"; case 7: return "weapon_knife_flip"; case 8: return "weapon_knife_gut"; case 9: return "weapon_knife_karambit"; case 10: return "weapon_knife_m9_bayonet"; case 11: return "weapon_knife_tactical"; case 12: return "weapon_knife_falchion"; case 13: return "weapon_knife_survival_bowie"; case 14: return "weapon_knife_butterfly"; case 15: return "weapon_knife_push"; case 16: return "weapon_knife_ursus"; case 17: return "weapon_knife_gypsy_jackknife"; case 18: return "weapon_knife_stiletto"; case 19: return "weapon_knife_widowmaker"; } } else { switch (custom_index) { case 0: return "ct_gloves"; case 1: return "studded_bloodhound_gloves"; case 2: return "t_gloves"; case 3: return "ct_gloves"; case 4: return "sporty_gloves"; case 5: return "slick_gloves"; case 6: return "leather_handwraps"; case 7: return "motorcycle_gloves"; case 8: return "specialist_gloves"; case 9: return "studded_hydra_gloves"; } } } else { switch (id) { case 0: return "knife"; case 1: return "gloves"; case 2: return "weapon_ak47"; case 3: return "weapon_aug"; case 4: return "weapon_awp"; case 5: return "weapon_cz75a"; case 6: return "weapon_deagle"; case 7: return "weapon_elite"; case 8: return "weapon_famas"; case 9: return "weapon_fiveseven"; case 10: return "weapon_g3sg1"; case 11: return "weapon_galilar"; case 12: return "weapon_glock"; case 13: return "weapon_m249"; case 14: return "weapon_m4a1_silencer"; case 15: return "weapon_m4a1"; case 16: return "weapon_mac10"; case 17: return "weapon_mag7"; case 18: return "weapon_mp5sd"; case 19: return "weapon_mp7"; case 20: return "weapon_mp9"; case 21: return "weapon_negev"; case 22: return "weapon_nova"; case 23: return "weapon_hkp2000"; case 24: return "weapon_p250"; case 25: return "weapon_p90"; case 26: return "weapon_bizon"; case 27: return "weapon_revolver"; case 28: return "weapon_sawedoff"; case 29: return "weapon_scar20"; case 30: return "weapon_ssg08"; case 31: return "weapon_sg556"; case 32: return "weapon_tec9"; case 33: return "weapon_ump45"; case 34: return "weapon_usp_silencer"; case 35: return "weapon_xm1014"; default: return "unknown"; } } } IDirect3DTexture9* get_skin_preview(const char* weapon_name, std::string skin_name, IDirect3DDevice9* device) { IDirect3DTexture9* skin_image = nullptr; if (!skin_image) { std::string vpk_path; if (strcmp(weapon_name, "unknown") && strcmp(weapon_name, "knife") && strcmp(weapon_name, "gloves")) { if (skin_name == "" || skin_name == "default") vpk_path = "resource/flash/econ/weapons/base_weapons/" + std::string(weapon_name) + ".png"; else vpk_path = "resource/flash/econ/default_generated/" + std::string(weapon_name) + "_" + std::string(skin_name) + "_light_large.png"; } else { if (!strcmp(weapon_name, "knife")) vpk_path = "resource/flash/econ/weapons/base_weapons/weapon_knife.png"; else if (!strcmp(weapon_name, "gloves")) vpk_path = "resource/flash/econ/weapons/base_weapons/ct_gloves.png"; else if (!strcmp(weapon_name, "unknown")) vpk_path = "resource/flash/econ/weapons/base_weapons/weapon_snowball.png"; } const auto handle = m_basefilesys()->Open(vpk_path.c_str(), "r", "GAME"); if (handle) { int file_len = m_basefilesys()->Size(handle); char* image = new char[file_len]; m_basefilesys()->Read(image, file_len, handle); m_basefilesys()->Close(handle); D3DXCreateTextureFromFileInMemory(device, image, file_len, &skin_image); delete[] image; } } if (skin_image != nullptr) return skin_image; else if (!skin_image) { std::string vpk_path; if (strstr(weapon_name, "bloodhound") != NULL || strstr(weapon_name, "hydra") != NULL) vpk_path = "resource/flash/econ/weapons/base_weapons/ct_gloves.png"; else vpk_path = "resource/flash/econ/weapons/base_weapons/" + std::string(weapon_name) + ".png"; const auto handle = m_basefilesys()->Open(vpk_path.c_str(), "r", "GAME"); if (handle) { int file_len = m_basefilesys()->Size(handle); char* image = new char[file_len]; m_basefilesys()->Read(image, file_len, handle); m_basefilesys()->Close(handle); D3DXCreateTextureFromFileInMemory(device, image, file_len, &skin_image); delete[] image; } } return skin_image; } // setup some styles and colors, window size and bg alpha // dpi setup void c_menu::menu_setup(ImGuiStyle &style) { ImGui::StyleColorsClassic(); // colors setup ImGui::SetNextWindowSize(ImVec2(width, height), ImGuiCond_Once); // window pos setup ImGui::SetNextWindowBgAlpha(min(style.Alpha, 0.94f)); // window bg alpha setup styles.WindowPadding = style.WindowPadding; styles.WindowRounding = style.WindowRounding; styles.WindowMinSize = style.WindowMinSize; styles.ChildRounding = style.ChildRounding; styles.PopupRounding = style.PopupRounding; styles.FramePadding = style.FramePadding; styles.FrameRounding = style.FrameRounding; styles.ItemSpacing = style.ItemSpacing; styles.ItemInnerSpacing = style.ItemInnerSpacing; styles.TouchExtraPadding = style.TouchExtraPadding; styles.IndentSpacing = style.IndentSpacing; styles.ColumnsMinSpacing = style.ColumnsMinSpacing; styles.ScrollbarSize = style.ScrollbarSize; styles.ScrollbarRounding = style.ScrollbarRounding; styles.GrabMinSize = style.GrabMinSize; styles.GrabRounding = style.GrabRounding; styles.TabRounding = style.TabRounding; styles.TabMinWidthForUnselectedCloseButton = style.TabMinWidthForUnselectedCloseButton; styles.DisplayWindowPadding = style.DisplayWindowPadding; styles.DisplaySafeAreaPadding = style.DisplaySafeAreaPadding; styles.MouseCursorScale = style.MouseCursorScale; // setup skins preview for (auto i = 0; i < g_cfg.skins.skinChanger.size(); i++) { if (all_skins[i] == nullptr) all_skins[i] = get_skin_preview(get_wep(i, (i == 0 || i == 1) ? g_cfg.skins.skinChanger.at(i).definition_override_vector_index : -1, i == 0).c_str(), g_cfg.skins.skinChanger.at(i).skin_name, device); } dpi_scale = max(1, ImGui::GetIO().DisplaySize.y / 1080); update_dpi = true; menu_setupped = true; // we dont want to setup menu again } // resize current style sizes void c_menu::dpi_resize(float scale_factor, ImGuiStyle &style) { style.WindowPadding = (styles.WindowPadding * scale_factor); style.WindowRounding = (styles.WindowRounding * scale_factor); style.WindowMinSize = (styles.WindowMinSize * scale_factor); style.ChildRounding = (styles.ChildRounding * scale_factor); style.PopupRounding = (styles.PopupRounding * scale_factor); style.FramePadding = (styles.FramePadding * scale_factor); style.FrameRounding = (styles.FrameRounding * scale_factor); style.ItemSpacing = (styles.ItemSpacing * scale_factor); style.ItemInnerSpacing = (styles.ItemInnerSpacing * scale_factor); style.TouchExtraPadding = (styles.TouchExtraPadding * scale_factor); style.IndentSpacing = (styles.IndentSpacing * scale_factor); style.ColumnsMinSpacing = (styles.ColumnsMinSpacing * scale_factor); style.ScrollbarSize = (styles.ScrollbarSize * scale_factor); style.ScrollbarRounding = (styles.ScrollbarRounding * scale_factor); style.GrabMinSize = (styles.GrabMinSize * scale_factor); style.GrabRounding = (styles.GrabRounding * scale_factor); style.TabRounding = (styles.TabRounding * scale_factor); if (styles.TabMinWidthForUnselectedCloseButton != FLT_MAX) style.TabMinWidthForUnselectedCloseButton = (styles.TabMinWidthForUnselectedCloseButton * scale_factor); style.DisplayWindowPadding = (styles.DisplayWindowPadding * scale_factor); style.DisplaySafeAreaPadding = (styles.DisplaySafeAreaPadding * scale_factor); style.MouseCursorScale = (styles.MouseCursorScale * scale_factor); } std::string get_config_dir() { std::string folder; static TCHAR path[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(NULL, 0x001a, NULL, NULL, path))) folder = std::string(path) + crypt_str("\\Legendware\\Configs\\"); CreateDirectory(folder.c_str(), NULL); return folder; } void load_config() { if (cfg_manager->files.empty()) return; cfg_manager->load(cfg_manager->files.at(g_cfg.selected_config), false); c_lua::get().unload_all_scripts(); for (auto& script : g_cfg.scripts.scripts) c_lua::get().load_script(c_lua::get().get_script_id(script)); scripts = c_lua::get().scripts; if (selected_script >= scripts.size()) selected_script = scripts.size() - 1; for (auto& current : scripts) { if (current.size() >= 5 && current.at(current.size() - 1) == 'c') current.erase(current.size() - 5, 5); else if (current.size() >= 4) current.erase(current.size() - 4, 4); } g_cfg.scripts.scripts.clear(); cfg_manager->load(cfg_manager->files.at(g_cfg.selected_config), true); cfg_manager->config_files(); eventlogs::get().add(crypt_str("Loaded ") + files.at(g_cfg.selected_config) + crypt_str(" config"), false); } void save_config() { if (cfg_manager->files.empty()) return; g_cfg.scripts.scripts.clear(); for (auto i = 0; i < c_lua::get().scripts.size(); ++i) { auto script = c_lua::get().scripts.at(i); if (c_lua::get().loaded.at(i)) g_cfg.scripts.scripts.emplace_back(script); } cfg_manager->save(cfg_manager->files.at(g_cfg.selected_config)); cfg_manager->config_files(); eventlogs::get().add(crypt_str("Saved ") + files.at(g_cfg.selected_config) + crypt_str(" config"), false); } void remove_config() { if (cfg_manager->files.empty()) return; eventlogs::get().add(crypt_str("Removed ") + files.at(g_cfg.selected_config) + crypt_str(" config"), false); cfg_manager->remove(cfg_manager->files.at(g_cfg.selected_config)); cfg_manager->config_files(); files = cfg_manager->files; if (g_cfg.selected_config >= files.size()) g_cfg.selected_config = files.size() - 1; for (auto& current : files) if (current.size() > 2) current.erase(current.size() - 3, 3); } void add_config() { auto empty = true; for (auto current : g_cfg.new_config_name) { if (current != ' ') { empty = false; break; } } if (empty) g_cfg.new_config_name = crypt_str("config"); eventlogs::get().add(crypt_str("Added ") + g_cfg.new_config_name + crypt_str(" config"), false); if (g_cfg.new_config_name.find(crypt_str(".lw")) == std::string::npos) g_cfg.new_config_name += crypt_str(".lw"); cfg_manager->save(g_cfg.new_config_name); cfg_manager->config_files(); g_cfg.selected_config = cfg_manager->files.size() - 1; files = cfg_manager->files; for (auto& current : files) if (current.size() > 2) current.erase(current.size() - 3, 3); } __forceinline void padding(float x, float y) { ImGui::SetCursorPosX(ImGui::GetCursorPosX() + x * c_menu::get().dpi_scale); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + y * c_menu::get().dpi_scale); } // title of content child void child_title(const char* label) { ImGui::PushFont(c_menu::get().futura_large); ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.f, 1.f, 1.f, 1.f)); ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (12 * c_menu::get().dpi_scale)); ImGui::Text(label); ImGui::PopStyleColor(); ImGui::PopFont(); } void draw_combo(const char* name, int& variable, const char* labels[], int count) { ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 6 * c_menu::get().dpi_scale); ImGui::Text(name); ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * c_menu::get().dpi_scale); ImGui::Combo(std::string("##COMBO__" + std::string(name)).c_str(), &variable, labels, count); } void draw_multicombo(const char* name, std::vector<int>& variable, const char* labels[], int count, std::string &preview ) { padding(-3, -6); ImGui::Text((" " + (std::string)name).c_str()); padding(0, -5); std::string hashname = "##" + std::string(name); // we dont want to render name of combo for (auto i = 0, j = 0; i < count; i++) { if (variable[i]) { if (j) preview += crypt_str(", ") + (std::string)labels[i]; else preview = labels[i]; j++; } } if (ImGui::BeginCombo(crypt_str(hashname.c_str()), preview.c_str())) // draw start { ImGui::Spacing(); ImGui::BeginGroup(); { for (auto i = 0; i < count; i++) ImGui::Selectable(labels[i], (bool*)&variable[i], ImGuiSelectableFlags_DontClosePopups); } ImGui::EndGroup(); ImGui::Spacing(); ImGui::EndCombo(); } preview = crypt_str("None"); // reset preview to use later } bool LabelClick(const char* label, bool* v, const char* unique_id) { ImGuiWindow* window = ImGui::GetCurrentWindow(); if (window->SkipItems) return false; // The concatoff/on thingies were for my weapon config system so if we're going to make that, we still need this aids. char Buf[64]; _snprintf(Buf, 62, crypt_str("%s"), label); char getid[128]; sprintf_s(getid, 128, crypt_str("%s%s"), label, unique_id); ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(getid); const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); const ImRect check_bb(window->DC.CursorPos, ImVec2(label_size.y + style.FramePadding.y * 2 + window->DC.CursorPos.x, window->DC.CursorPos.y + label_size.y + style.FramePadding.y * 2)); ImGui::ItemSize(check_bb, style.FramePadding.y); ImRect total_bb = check_bb; if (label_size.x > 0) { ImGui::SameLine(0, style.ItemInnerSpacing.x); const ImRect text_bb(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), ImVec2(window->DC.CursorPos.x + label_size.x, window->DC.CursorPos.y + style.FramePadding.y + label_size.y)); ImGui::ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); } if (!ImGui::ItemAdd(total_bb, id)) return false; bool hovered, held; bool pressed = ImGui::ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) *v = !(*v); if (*v) ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(126 / 255.f, 131 / 255.f, 219 / 255.f, 1.f)); if (label_size.x > 0.0f) ImGui::RenderText(ImVec2(check_bb.GetTL().x + 12, check_bb.GetTL().y), Buf); if (*v) ImGui::PopStyleColor(); return pressed; } void draw_keybind(const char* label, key_bind* key_bind, const char* unique_id) { // reset bind if we re pressing esc if (key_bind->key == KEY_ESCAPE) key_bind->key = KEY_NONE; auto clicked = false; auto text = (std::string)m_inputsys()->ButtonCodeToString(key_bind->key); if (key_bind->key <= KEY_NONE || key_bind->key >= KEY_MAX) text = crypt_str("None"); // if we clicked on keybind if (hooks::input_shouldListen && hooks::input_receivedKeyval == &key_bind->key) { clicked = true; text = crypt_str("..."); } auto textsize = ImGui::CalcTextSize(text.c_str()).x + 8 * c_menu::get().dpi_scale; auto labelsize = ImGui::CalcTextSize(label); ImGui::Text(label); ImGui::SameLine(); ImGui::SetCursorPosX(ImGui::GetWindowSize().x - (ImGui::GetWindowSize().x - ImGui::CalcItemWidth()) - max(50 * c_menu::get().dpi_scale, textsize)); ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 3 * c_menu::get().dpi_scale); if (ImGui::KeybindButton(text.c_str(), unique_id, ImVec2(max(50 * c_menu::get().dpi_scale, textsize), 23 * c_menu::get().dpi_scale), clicked)) clicked = true; if (clicked) { hooks::input_shouldListen = true; hooks::input_receivedKeyval = &key_bind->key; } static auto hold = false, toggle = false; switch (key_bind->mode) { case HOLD: hold = true; toggle = false; break; case TOGGLE: toggle = true; hold = false; break; } if (ImGui::BeginPopup(unique_id)) { ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 6 * c_menu::get().dpi_scale); ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ((ImGui::GetCurrentWindow()->Size.x / 2) - (ImGui::CalcTextSize("Hold").x / 2))); ImGui::SetCursorPosX(ImGui::GetCursorPosX() - 11); if (LabelClick(crypt_str("Hold"), &hold, unique_id)) { if (hold) { toggle = false; key_bind->mode = HOLD; } else if (toggle) { hold = false; key_bind->mode = TOGGLE; } else { toggle = false; key_bind->mode = HOLD; } ImGui::CloseCurrentPopup(); } ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ((ImGui::GetCurrentWindow()->Size.x / 2) - (ImGui::CalcTextSize("Toggle").x / 2))); ImGui::SetCursorPosX(ImGui::GetCursorPosX() - 11); ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 9 * c_menu::get().dpi_scale); if (LabelClick(crypt_str("Toggle"), &toggle, unique_id)) { if (toggle) { hold = false; key_bind->mode = TOGGLE; } else if (hold) { toggle = false; key_bind->mode = HOLD; } else { hold = false; key_bind->mode = TOGGLE; } ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } void draw_semitabs(const char* labels[], int count, int &tab, ImGuiStyle style) { ImGui::SetCursorPosY(ImGui::GetCursorPosY() - (2 * c_menu::get().dpi_scale)); // center of main child float offset = 343 * c_menu::get().dpi_scale; // text size padding + frame padding for (int i = 0; i < count; i++) offset -= (ImGui::CalcTextSize(labels[i]).x) / 2 + style.FramePadding.x * 2; // set new padding ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offset); ImGui::BeginGroup(); for (int i = 0; i < count; i++) { // switch current tab if (ImGui::ContentTab(labels[i], tab == i)) tab = i; // continue drawing on same line if (i + 1 != count) { ImGui::SameLine(); ImGui::SetCursorPosX(ImGui::GetCursorPosX() + style.ItemSpacing.x); } } ImGui::EndGroup(); } __forceinline void tab_start() { ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + (20 * c_menu::get().dpi_scale), ImGui::GetCursorPosY() + (5 * c_menu::get().dpi_scale))); } __forceinline void tab_end() { ImGui::PopStyleVar(); ImGui::SetWindowFontScale(c_menu::get().dpi_scale); } // TODO: do it for every script void lua_edit(std::string window_name) { const char* child_name = (window_name + window_name).c_str(); ImGui::SetNextWindowSize(ImVec2(700, 600), ImGuiCond_Once); ImGui::Begin(window_name.c_str(), nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 5.f); static bool load = false; static TextEditor editor; if (!load) { auto lang = TextEditor::LanguageDefinition::Lua(); editor.SetLanguageDefinition(lang); editor.SetReadOnly(false); // TODO: get correct path to lua file (now it's Counter Strike../lua/..) static const char* fileToEdit = "lua/kon_utils.lua"; { std::ifstream t(fileToEdit); if (t.good()) // does while exist? { std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); editor.SetText(str); // setup script content } } load = true; } // dpi scale for font // we dont need to resize it for full scale ImGui::SetWindowFontScale(1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f)); // new size depending on dpi scale ImGui::SetWindowSize(ImVec2(ImFloor(800 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f))), ImFloor(700 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f))))); editor.Render(child_name, ImGui::GetWindowSize() - ImVec2(0, 66 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f)))); // seperate code with buttons ImGui::Separator(); // set cursor pos to right edge of window ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetWindowSize().x - (16.f * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f))) - (250.f * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f)))); ImGui::BeginGroup(); if (ImGui::CustomButton("Save", ("Save" + window_name).c_str(), ImVec2(125 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f)), 0), true, c_menu::get().ico_bottom, "S")) { std::ofstream out; // TODO: correct file path out.open("lua/kon_utils.lua"); out << editor.GetText() << std::endl; out.close(); } ImGui::SameLine(); // TOOD: close button will close window (return in start of function) if (ImGui::CustomButton("Close", ("Close" + window_name).c_str(), ImVec2(125 * (1.f + ((c_menu::get().dpi_scale - 1.0) * 0.5f)), 0))) { } ImGui::EndGroup(); ImGui::PopStyleVar(); ImGui::End(); } // SEMITABS FUNCTIONS void c_menu::draw_tabs_ragebot() { const char* rage_sections[2] = { "General", "Weapon" }; draw_semitabs(rage_sections, 2, rage_section, ImGui::GetStyle()); } void c_menu::draw_ragebot(int child) { if (!rage_section) { if (!child) { child_title("Ragebot"); tab_start(); ImGui::BeginChild("##RAGE1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Enable"), &g_cfg.ragebot.enable); if (g_cfg.ragebot.enable) g_cfg.legitbot.enabled = false; ImGui::SliderInt(crypt_str("Field of view"), &g_cfg.ragebot.field_of_view, 1, 180); ImGui::Checkbox(crypt_str("Silent aim"), &g_cfg.ragebot.silent_aim); ImGui::Checkbox(crypt_str("Automatic wall"), &g_cfg.ragebot.autowall); ImGui::Checkbox(crypt_str("Aimbot with zeus"), &g_cfg.ragebot.zeus_bot); ImGui::Checkbox(crypt_str("Aimbot with knife"), &g_cfg.ragebot.knife_bot); ImGui::Checkbox(crypt_str("Automatic fire"), &g_cfg.ragebot.autoshoot); ImGui::Checkbox(crypt_str("Automatic scope"), &g_cfg.ragebot.autoscope); ImGui::Checkbox(crypt_str("Pitch desync correction"), &g_cfg.ragebot.pitch_antiaim_correction); ImGui::Spacing(); ImGui::Checkbox(crypt_str("Double tap"), &g_cfg.ragebot.double_tap); if (g_cfg.ragebot.double_tap) { ImGui::SameLine(); draw_keybind("", &g_cfg.ragebot.double_tap_key, "##HOTKEY_DT"); ImGui::Checkbox(crypt_str("Slow teleport"), &g_cfg.ragebot.slow_teleport); } ImGui::Checkbox(crypt_str("Hide shots"), &g_cfg.antiaim.hide_shots); if (g_cfg.antiaim.hide_shots) { ImGui::SameLine(); draw_keybind("", &g_cfg.antiaim.hide_shots_key, "##HOTKEY_HIDESHOTS"); } } ImGui::EndChild(); tab_end(); } else { child_title("Anti-aim"); tab_start(); ImGui::BeginChild("##RAGE2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { static auto type = 0; ImGui::Checkbox(crypt_str("Enable"), &g_cfg.antiaim.enable); draw_combo(crypt_str("Anti-aim type"), g_cfg.antiaim.antiaim_type, antiaim_type, ARRAYSIZE(antiaim_type)); if (g_cfg.antiaim.antiaim_type) { padding(0, 3); draw_combo(crypt_str("Desync"), g_cfg.antiaim.desync, desync, ARRAYSIZE(desync)); if (g_cfg.antiaim.desync) { padding(0, 3); draw_combo(crypt_str("LBY type"), g_cfg.antiaim.legit_lby_type, lby_type, ARRAYSIZE(lby_type)); if (g_cfg.antiaim.desync == 1) { draw_keybind("Invert desync", &g_cfg.antiaim.flip_desync, "##HOTKEY_INVERT_DESYNC"); } } } else { draw_combo(crypt_str("Movement type"), type, movement_type, ARRAYSIZE(movement_type)); padding(0, 3); draw_combo(crypt_str("Pitch"), g_cfg.antiaim.type[type].pitch, pitch, ARRAYSIZE(pitch)); padding(0, 3); draw_combo(crypt_str("Yaw"), g_cfg.antiaim.type[type].yaw, yaw, ARRAYSIZE(yaw)); padding(0, 3); draw_combo(crypt_str("Base angle"), g_cfg.antiaim.type[type].base_angle, baseangle, ARRAYSIZE(baseangle)); if (g_cfg.antiaim.type[type].yaw) { ImGui::SliderInt(g_cfg.antiaim.type[type].yaw == 1 ? crypt_str("Jitter range") : crypt_str("Spin range"), &g_cfg.antiaim.type[type].range, 1, 180); if (g_cfg.antiaim.type[type].yaw == 2) ImGui::SliderInt(crypt_str("Spin speed"), &g_cfg.antiaim.type[type].speed, 1, 15); padding(0, 3); } draw_combo(crypt_str("Desync"), g_cfg.antiaim.type[type].desync, desync, ARRAYSIZE(desync)); if (g_cfg.antiaim.type[type].desync) { if (type == ANTIAIM_STAND) { padding(0, 3); draw_combo(crypt_str("LBY type"), g_cfg.antiaim.lby_type, lby_type, ARRAYSIZE(lby_type)); } if (type != ANTIAIM_STAND || !g_cfg.antiaim.lby_type) { ImGui::SliderInt(crypt_str("Desync range"), &g_cfg.antiaim.type[type].desync_range, 1, 100, "%.0f%%"); ImGui::SliderInt(crypt_str("Body lean"), &g_cfg.antiaim.type[type].body_lean, 0, 100); ImGui::SliderInt(crypt_str("Inverted body lean"), &g_cfg.antiaim.type[type].inverted_body_lean, 0, 100); } if (g_cfg.antiaim.type[type].desync == 1) { draw_keybind("Invert desync", &g_cfg.antiaim.flip_desync, "##HOTKEY_INVERT_DESYNC"); } } draw_keybind("Manual back", &g_cfg.antiaim.manual_back, "##HOTKEY_INVERT_BACK"); draw_keybind("Manual left", &g_cfg.antiaim.manual_left, "##HOTKEY_INVERT_LEFT"); draw_keybind("Manual right", &g_cfg.antiaim.manual_right, "##HOTKEY_INVERT_RIGHT"); if (g_cfg.antiaim.manual_back.key > KEY_NONE && g_cfg.antiaim.manual_back.key < KEY_MAX || g_cfg.antiaim.manual_left.key > KEY_NONE && g_cfg.antiaim.manual_left.key < KEY_MAX || g_cfg.antiaim.manual_right.key > KEY_NONE && g_cfg.antiaim.manual_right.key < KEY_MAX) { ImGui::Checkbox(crypt_str("Manuals indicator"), &g_cfg.antiaim.flip_indicator); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##invc"), &g_cfg.antiaim.flip_indicator_color, ALPHA); } } } ImGui::EndChild(); tab_end(); } } else { static int rage_weapon = 0; const char* rage_weapons[8] = { "R8 & Deagle", "Pistols", "SMGs", "Rifles", "Auto snipers", "Scout", "AWP", "Heavy" }; if (!child) { child_title("General"); tab_start(); ImGui::BeginChild("##RAGE1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Spacing(); draw_combo(crypt_str("Current weapon"), rage_weapon, rage_weapons, ARRAYSIZE(rage_weapons)); ImGui::Spacing(); draw_combo(crypt_str("Target selection"), g_cfg.ragebot.weapon[rage_weapon].selection_type, selection, ARRAYSIZE(selection)); padding(0, 3); draw_multicombo(crypt_str("Hitboxes"), g_cfg.ragebot.weapon[rage_weapon].hitscan, hitboxes, ARRAYSIZE(hitboxes), preview); // TODO: Uncomment me //ImGui::Checkbox(crypt_str("Enable max misses"), &g_cfg.ragebot.weapon[rage_weapon].max_misses); // //if (g_cfg.ragebot.weapon[rage_weapon].max_misses) // ImGui::SliderInt("Max misses", &g_cfg.ragebot.weapon[rage_weapon].max_misses_amount, 0, 6); //ImGui::Checkbox(crypt_str("Prefer safe points"), &g_cfg.ragebot.weapon[rage_weapon].prefer_safe_points); //ImGui::Checkbox(crypt_str("Prefer body aim"), &g_cfg.ragebot.weapon[rage_weapon].prefer_body_aim); //draw_keybind("Force safe points", &g_cfg.ragebot.safe_point_key, "##HOKEY_FORCE_SAFE_POINTS"); draw_keybind("Force body aim", &g_cfg.ragebot.baim_key, "##HOKEY_FORCE_BODY_AIM"); } ImGui::EndChild(); tab_end(); } else { child_title("Accuracy"); tab_start(); ImGui::BeginChild("##RAGE2_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { // TODO: проверь, чтобы все настройки тут были из обычного меню текущего ImGui::Checkbox(crypt_str("Automatic stop"), &g_cfg.ragebot.weapon[rage_weapon].autostop); if (g_cfg.ragebot.weapon[rage_weapon].autostop) draw_multicombo("Modifiers", g_cfg.ragebot.weapon[rage_weapon].autostop_modifiers, autostop_modifiers, ARRAYSIZE(autostop_modifiers), preview); ImGui::Checkbox(crypt_str("Hitchance"), &g_cfg.ragebot.weapon[rage_weapon].hitchance); if (g_cfg.ragebot.weapon[rage_weapon].hitchance) ImGui::SliderInt(crypt_str("Hitchance amount"), &g_cfg.ragebot.weapon[rage_weapon].hitchance_amount, 1, 100); if (g_cfg.ragebot.double_tap && rage_weapon <= 4) { ImGui::Checkbox(crypt_str("Double tap hitchance"), &g_cfg.ragebot.weapon[rage_weapon].double_tap_hitchance); if (g_cfg.ragebot.weapon[rage_weapon].double_tap_hitchance) ImGui::SliderInt(crypt_str("Double tap hitchance amount"), &g_cfg.ragebot.weapon[rage_weapon].double_tap_hitchance_amount, 1, 100); } ImGui::SliderInt(crypt_str("Minimum visible damage"), &g_cfg.ragebot.weapon[rage_weapon].minimum_visible_damage, 1, 120); if (g_cfg.ragebot.autowall) ImGui::SliderInt(crypt_str("Minimum wall damage"), &g_cfg.ragebot.weapon[rage_weapon].minimum_damage, 1, 120); draw_keybind("Damage override", &g_cfg.ragebot.weapon[rage_weapon].damage_override_key, "##HOTKEY__DAMAGE_OVERRIDE"); if (g_cfg.ragebot.weapon[rage_weapon].damage_override_key.key > KEY_NONE && g_cfg.ragebot.weapon[rage_weapon].damage_override_key.key < KEY_MAX) ImGui::SliderInt(crypt_str("Minimum override damage"), &g_cfg.ragebot.weapon[rage_weapon].minimum_override_damage, 1, 120); } ImGui::EndChild(); tab_end(); } } } /* struct weapon_t { int awall_dmg; float target_switch_delay; } weapon[8]; */ void c_menu::draw_tabs_legit() { const char* legit_sections[1] = { "General" }; draw_semitabs(legit_sections, 1, legit_section, ImGui::GetStyle()); } void c_menu::draw_legit(int child) { static int legit_weapon = 0; const char* legit_weapons[6] = { "Deagle", "Pistols", "Rifles", "SMGs", "Sniper", "Heavy" }; const char* hitbox_legit[3] = { "Nearest", "Head", "Body" }; if (!child) { child_title("Legitbot"); tab_start(); ImGui::BeginChild("##RAGE1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { padding(0, 6); ImGui::Checkbox(crypt_str("Enabled"), &g_cfg.legitbot.enabled); ImGui::SameLine(); draw_keybind(crypt_str(""), &g_cfg.legitbot.key, crypt_str("##HOTKEY_LGBT_KEY")); if (g_cfg.legitbot.enabled) g_cfg.ragebot.enable = false; ImGui::Checkbox(crypt_str("Friendly fire"), &g_cfg.legitbot.friendly_fire); ImGui::Checkbox(crypt_str("Auto pistols"), &g_cfg.legitbot.autopistol); ImGui::Checkbox(crypt_str("Auto scope"), &g_cfg.legitbot.autoscope); if (g_cfg.legitbot.autoscope) ImGui::Checkbox(crypt_str("Unscope after shot"), &g_cfg.legitbot.unscope); ImGui::Checkbox(crypt_str("Sniper in zoom only"), &g_cfg.legitbot.sniper_in_zoom_only); ImGui::Checkbox(crypt_str("Scan in air"), &g_cfg.legitbot.do_if_local_in_air); ImGui::Checkbox(crypt_str("Scan if flashed"), &g_cfg.legitbot.do_if_local_flashed); ImGui::Checkbox(crypt_str("Scan in smoke"), &g_cfg.legitbot.do_if_enemy_in_smoke); draw_keybind(crypt_str("Autofire key"), &g_cfg.legitbot.autofire_key, crypt_str("##HOTKEY_AUTOFIRE_LGBT_KEY")); ImGui::SliderInt(crypt_str("Autofire delay"), &g_cfg.legitbot.autofire_delay, 0, 12, (!g_cfg.legitbot.autofire_delay ? "No" : (g_cfg.legitbot.autofire_delay == 1 ? "%dtick" : "%dticks"))); } ImGui::EndChild(); tab_end(); } else { child_title("Weapon settings"); tab_start(); ImGui::BeginChild("##RAGE1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Spacing(); draw_combo(crypt_str("Weapon preset"), legit_weapon, legit_weapons, ARRAYSIZE(legit_weapons)); ImGui::Spacing(); draw_combo(crypt_str("Hitbox"), g_cfg.legitbot.weapon[legit_weapon].priority, hitbox_legit, ARRAYSIZE(hitbox_legit)); ImGui::Checkbox(crypt_str("Auto stop"), &g_cfg.legitbot.weapon[legit_weapon].auto_stop); draw_combo(crypt_str("Fov type"), g_cfg.legitbot.weapon[legit_weapon].fov_type, LegitFov, ARRAYSIZE(LegitFov)); ImGui::SliderFloat(crypt_str("Fov amount"), &g_cfg.legitbot.weapon[legit_weapon].fov, 0.f, 30.f, "%.2f"); ImGui::Spacing(); ImGui::SliderFloat(crypt_str("Silent fov"), &g_cfg.legitbot.weapon[legit_weapon].silent_fov, 0.f, 30.f, (!g_cfg.legitbot.weapon[legit_weapon].silent_fov ? "No" : "%.2f")); ImGui::Spacing(); draw_combo(crypt_str("Smooth type"), g_cfg.legitbot.weapon[legit_weapon].smooth_type, LegitSmooth, ARRAYSIZE(LegitSmooth)); ImGui::SliderFloat(crypt_str("Smooth amount"), &g_cfg.legitbot.weapon[legit_weapon].smooth, 1.f, 12.f, "%.1f"); ImGui::Spacing(); draw_combo(crypt_str("RCS type"), g_cfg.legitbot.weapon[legit_weapon].rcs_type, RCSType, ARRAYSIZE(RCSType)); ImGui::SliderFloat(crypt_str("RCS amount"), &g_cfg.legitbot.weapon[legit_weapon].rcs, 0.f, 100.f, "%.0f%%", 1.f); if (g_cfg.legitbot.weapon[legit_weapon].rcs > 0) { ImGui::SliderFloat(crypt_str("RCS Custom Fov"), &g_cfg.legitbot.weapon[legit_weapon].custom_rcs_fov, 0.f, 30.f, (!g_cfg.legitbot.weapon[legit_weapon].custom_rcs_fov ? "No" : "%.2f")); ImGui::SliderFloat(crypt_str("RCS Custom Smooth"), &g_cfg.legitbot.weapon[legit_weapon].custom_rcs_smooth, 0.f, 12.f, (!g_cfg.legitbot.weapon[legit_weapon].custom_rcs_smooth ? "No" : "%.1f")); } ImGui::Spacing(); ImGui::SliderInt(crypt_str("Autowall damage"), &g_cfg.legitbot.weapon[legit_weapon].awall_dmg, 0, 100, (!g_cfg.legitbot.weapon[legit_weapon].awall_dmg ? "No" : "%d")); ImGui::SliderInt(crypt_str("Autofire hitchance"), &g_cfg.legitbot.weapon[legit_weapon].autofire_hitchance, 0, 100, (!g_cfg.legitbot.weapon[legit_weapon].autofire_hitchance ? "No" : "%d")); ImGui::SliderFloat(crypt_str("Target switch delay"), &g_cfg.legitbot.weapon[legit_weapon].target_switch_delay, 0.f, 1.f, "%.3fs"); } ImGui::EndChild(); tab_end(); } } void c_menu::draw_tabs_visuals() { const char* visuals_sections[3] = { "General", "Viewmodel", "Skinchanger" }; draw_semitabs(visuals_sections, 3, visuals_section, ImGui::GetStyle()); } void c_menu::draw_visuals(int child) { if (visuals_section != 2) { if (!child) { if (!visuals_section) { child_title("General"); tab_start(); ImGui::BeginChild("##VISUAL1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Enable"), &g_cfg.player.enable); draw_multicombo("Indicators", g_cfg.esp.indicators, indicators, ARRAYSIZE(indicators), preview); padding(0, 3); draw_multicombo("Removals", g_cfg.esp.removals, removals, ARRAYSIZE(removals), preview); if (g_cfg.esp.removals[REMOVALS_ZOOM]) ImGui::Checkbox(crypt_str("Fix zoom sensivity"), &g_cfg.esp.fix_zoom_sensivity); ImGui::Checkbox(crypt_str("Grenade prediction"), &g_cfg.esp.grenade_prediction); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##grenpredcolor"), &g_cfg.esp.grenade_prediction_color, ALPHA); if (g_cfg.esp.grenade_prediction) { ImGui::Checkbox(crypt_str("On click"), &g_cfg.esp.on_click); ImGui::Text(crypt_str("Tracer color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##tracergrenpredcolor"), &g_cfg.esp.grenade_prediction_tracer_color, ALPHA); } ImGui::Checkbox(crypt_str("Grenade projectiles"), &g_cfg.esp.projectiles); if (g_cfg.esp.projectiles) draw_multicombo("Grenade ESP", g_cfg.esp.grenade_esp, proj_combo, ARRAYSIZE(proj_combo), preview); if (g_cfg.esp.grenade_esp[GRENADE_ICON] || g_cfg.esp.grenade_esp[GRENADE_TEXT]) { ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##projectcolor"), &g_cfg.esp.projectiles_color, ALPHA); } if (g_cfg.esp.grenade_esp[GRENADE_BOX]) { ImGui::Text(crypt_str("Box color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##grenade_box_color"), &g_cfg.esp.grenade_box_color, ALPHA); } if (g_cfg.esp.grenade_esp[GRENADE_GLOW]) { ImGui::Text(crypt_str("Glow color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##grenade_glow_color"), &g_cfg.esp.grenade_glow_color, ALPHA); } ImGui::Checkbox(crypt_str("Fire timer"), &g_cfg.esp.molotov_timer); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##molotovcolor"), &g_cfg.esp.molotov_timer_color, ALPHA); ImGui::Checkbox(crypt_str("Bomb indicator"), &g_cfg.esp.bomb_timer); draw_multicombo("Weapon ESP", g_cfg.esp.weapon, weaponesp, ARRAYSIZE(weaponesp), preview); if (g_cfg.esp.weapon[WEAPON_ICON] || g_cfg.esp.weapon[WEAPON_TEXT] || g_cfg.esp.weapon[WEAPON_DISTANCE]) { ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##weaponcolor"), &g_cfg.esp.weapon_color, ALPHA); } if (g_cfg.esp.weapon[WEAPON_BOX]) { ImGui::Text(crypt_str("Box color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##weaponboxcolor"), &g_cfg.esp.box_color, ALPHA); } if (g_cfg.esp.weapon[WEAPON_GLOW]) { ImGui::Text(crypt_str("Glow color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##weaponglowcolor"), &g_cfg.esp.weapon_glow_color, ALPHA); } if (g_cfg.esp.weapon[WEAPON_AMMO]) { ImGui::Text(crypt_str("Ammo bar color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##weaponammocolor"), &g_cfg.esp.weapon_ammo_color, ALPHA); } ImGui::Checkbox(crypt_str("Client bullet impacts"), &g_cfg.esp.client_bullet_impacts); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##clientbulletimpacts"), &g_cfg.esp.client_bullet_impacts_color, ALPHA); ImGui::Checkbox(crypt_str("Server bullet impacts"), &g_cfg.esp.server_bullet_impacts); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##serverbulletimpacts"), &g_cfg.esp.server_bullet_impacts_color, ALPHA); ImGui::Checkbox(crypt_str("Local bullet tracers"), &g_cfg.esp.bullet_tracer); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##bulltracecolor"), &g_cfg.esp.bullet_tracer_color, ALPHA); ImGui::Checkbox(crypt_str("Enemy bullet tracers"), &g_cfg.esp.enemy_bullet_tracer); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##enemybulltracecolor"), &g_cfg.esp.enemy_bullet_tracer_color, ALPHA); ImGui::Checkbox(crypt_str("Hitmarker"), &g_cfg.esp.hitmarker); ImGui::Checkbox(crypt_str("Damage marker"), &g_cfg.esp.damage_marker); ImGui::Checkbox(crypt_str("Kill effect"), &g_cfg.esp.kill_effect); if (g_cfg.esp.kill_effect) ImGui::SliderFloat(crypt_str("Duration"), &g_cfg.esp.kill_effect_duration, 0.01f, 3.0f); draw_keybind("Thirdperson", &g_cfg.misc.thirdperson_toggle, "##TPKEY__HOTKEY"); ImGui::Checkbox(crypt_str("Thirdperson when spectating"), &g_cfg.misc.thirdperson_when_spectating); if (g_cfg.misc.thirdperson_toggle.key > KEY_NONE && g_cfg.misc.thirdperson_toggle.key < KEY_MAX) ImGui::SliderInt(crypt_str("Thirdperson distance"), &g_cfg.misc.thirdperson_distance, 100, 300); ImGui::SliderInt(crypt_str("Field of view"), &g_cfg.esp.fov, 0, 89); ImGui::Checkbox(crypt_str("Taser range"), &g_cfg.esp.taser_range); ImGui::Checkbox(crypt_str("Show spread"), &g_cfg.esp.show_spread); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##spredcolor"), &g_cfg.esp.show_spread_color, ALPHA); ImGui::Checkbox(crypt_str("Penetration crosshair"), &g_cfg.esp.penetration_reticle); } ImGui::EndChild(); tab_end(); } else { child_title("General"); tab_start(); ImGui::BeginChild("##VISUAL2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Rare animations"), &g_cfg.skins.rare_animations); ImGui::SliderInt(crypt_str("Viewmodel field of view"), &g_cfg.esp.viewmodel_fov, 0, 89); ImGui::SliderInt(crypt_str("Viewmodel X"), &g_cfg.esp.viewmodel_x, -50, 50); ImGui::SliderInt(crypt_str("Viewmodel Y"), &g_cfg.esp.viewmodel_y, -50, 50); ImGui::SliderInt(crypt_str("Viewmodel Z"), &g_cfg.esp.viewmodel_z, -50, 50); ImGui::SliderInt(crypt_str("Viewmodel roll"), &g_cfg.esp.viewmodel_roll, -180, 180); } ImGui::EndChild(); tab_end(); } } else { if (!visuals_section) { child_title("World"); tab_start(); ImGui::BeginChild("##VISUAL1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Full bright"), &g_cfg.esp.bright); draw_combo("Skybox", g_cfg.esp.skybox, skybox, ARRAYSIZE(skybox)); ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##skyboxcolor"), &g_cfg.esp.skybox_color, NOALPHA); if (g_cfg.esp.skybox == 21) { static char sky_custom[64] = "\0"; if (!g_cfg.esp.custom_skybox.empty()) strcpy_s(sky_custom, sizeof(sky_custom), g_cfg.esp.custom_skybox.c_str()); ImGui::Text(crypt_str("Name")); if (ImGui::InputText(crypt_str("##customsky"), sky_custom, sizeof(sky_custom))) g_cfg.esp.custom_skybox = sky_custom; } ImGui::Checkbox(crypt_str("Night mode"), &g_cfg.esp.nightmode); if (g_cfg.esp.nightmode) { ImGui::Text(crypt_str("World color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##worldcolor"), &g_cfg.esp.world_color, ALPHA); ImGui::Text(crypt_str("Props color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##propscolor"), &g_cfg.esp.props_color, ALPHA); } ImGui::Checkbox(crypt_str("World modulation"), &g_cfg.esp.world_modulation); if (g_cfg.esp.world_modulation) { ImGui::SliderFloat(crypt_str("Bloom"), &g_cfg.esp.bloom, 0.0f, 750.0f); ImGui::SliderFloat(crypt_str("Exposure"), &g_cfg.esp.exposure, 0.0f, 2000.0f); ImGui::SliderFloat(crypt_str("Ambient"), &g_cfg.esp.ambient, 0.0f, 1500.0f); } ImGui::Checkbox(crypt_str("Fog modulation"), &g_cfg.esp.fog); if (g_cfg.esp.fog) { ImGui::SliderInt(crypt_str("Distance"), &g_cfg.esp.fog_distance, 0, 2500); ImGui::SliderInt(crypt_str("Density"), &g_cfg.esp.fog_density, 0, 100); ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##fogcolor"), &g_cfg.esp.fog_color, NOALPHA); } } ImGui::EndChild(); tab_end(); } else { child_title("Chams"); tab_start(); ImGui::BeginChild("##VISUAL2_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Arms chams"), &g_cfg.esp.arms_chams); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##armscolor"), &g_cfg.esp.arms_chams_color, ALPHA); draw_combo(crypt_str("Arms chams material"), g_cfg.esp.arms_chams_type, chamstype, ARRAYSIZE(chamstype)); if (g_cfg.esp.arms_chams_type != 6) { ImGui::Checkbox(crypt_str("Arms double material "), &g_cfg.esp.arms_double_material); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##armsdoublematerial"), &g_cfg.esp.arms_double_material_color, ALPHA); } ImGui::Checkbox(crypt_str("Arms animated material "), &g_cfg.esp.arms_animated_material); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##armsanimatedmaterial"), &g_cfg.esp.arms_animated_material_color, ALPHA); ImGui::Spacing(); ImGui::Checkbox(crypt_str("Weapon chams"), &g_cfg.esp.weapon_chams); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##weaponchamscolors"), &g_cfg.esp.weapon_chams_color, ALPHA); draw_combo(crypt_str("Weapon chams material"), g_cfg.esp.weapon_chams_type, chamstype, ARRAYSIZE(chamstype)); if (g_cfg.esp.weapon_chams_type != 6) { ImGui::Checkbox(crypt_str("Weapon double material "), &g_cfg.esp.weapon_double_material); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##weapondoublematerial"), &g_cfg.esp.weapon_double_material_color, ALPHA); } ImGui::Checkbox(crypt_str("Weapon animated material "), &g_cfg.esp.weapon_animated_material); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##weaponanimatedmaterial"), &g_cfg.esp.weapon_animated_material_color, ALPHA); } ImGui::EndChild(); tab_end(); } } } else if (child == -1) { // hey stewen, what r u doing there? he, hm heee, DRUGS static bool drugs = false; // some animation logic(switch) static bool active_animation = false; static bool preview_reverse = false; static float switch_alpha = 1.f; static int next_id = -1; if (active_animation) { if (preview_reverse) { if (switch_alpha == 1.f) { preview_reverse = false; active_animation = false; } switch_alpha = math::clamp(switch_alpha + (4.f * ImGui::GetIO().DeltaTime), 0.01f, 1.f); } else { if (switch_alpha == 0.01f) { preview_reverse = true; } switch_alpha = math::clamp(switch_alpha - (4.f * ImGui::GetIO().DeltaTime), 0.01f, 1.f); } } else switch_alpha = math::clamp(switch_alpha + (4.f * ImGui::GetIO().DeltaTime), 0.0f, 1.f); // TODO: delete g_cfg.skin.enable and auto force it to TRUE g_cfg.skins.enable = true; ImGui::BeginChild("##SKINCHANGER__TAB", ImVec2(686 * dpi_scale, child_height * dpi_scale)); // first functional child { ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha) * public_alpha * switch_alpha); child_title(current_profile == -1 ? "Skinchanger" : game_data::weapon_names[current_profile].name); tab_start(); ImGui::BeginChild("##SKINCHANGER__CHILD", ImVec2(686 * dpi_scale, (child_height - 35)* dpi_scale)); { // we need to count our items in 1 line int same_line_counter = 0; // if we didnt choose any weapon if (current_profile == -1) { for (auto i = 0; i < g_cfg.skins.skinChanger.size(); i++) { // do we need update our preview for some reasons? if (all_skins[i] == nullptr) all_skins[i] = get_skin_preview(get_wep(i, (i == 0 || i == 1) ? g_cfg.skins.skinChanger.at(i).definition_override_vector_index : -1, i == 0).c_str(), g_cfg.skins.skinChanger.at(i).skin_name, device); // we licked on weapon if (ImGui::ImageButton(all_skins[i], ImVec2(107 * dpi_scale, 76 * dpi_scale))) { next_id = i; active_animation = true; } // if our animation step is half from all - switch profile if (active_animation && preview_reverse) { ImGui::SetScrollY(0); current_profile = next_id; } if (same_line_counter < 4) { // continue push same-line ImGui::SameLine(); same_line_counter++; } else { // we have maximum elements in 1 line same_line_counter = 0; } } } else { // update skin preview bool static bool need_update[36]; // we pressed "Save & Close" button static bool leave; // update if we have nullptr texture or if we push force update if (all_skins[current_profile] == nullptr || need_update[current_profile]) { all_skins[current_profile] = get_skin_preview(get_wep(current_profile, (current_profile == 0 || current_profile == 1) ? g_cfg.skins.skinChanger.at(current_profile).definition_override_vector_index : -1, current_profile == 0).c_str(), g_cfg.skins.skinChanger.at(current_profile).skin_name, device); need_update[current_profile] = false; } // get settings for selected weapon auto& selected_entry = g_cfg.skins.skinChanger[current_profile]; selected_entry.itemIdIndex = current_profile; ImGui::BeginGroup(); ImGui::PushItemWidth(260 * dpi_scale); // search input later static char search_skins[64] = ""; static auto item_index = selected_entry.paint_kit_vector_index; if (!current_profile) { ImGui::Text("Knife"); ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * c_menu::get().dpi_scale); if (ImGui::Combo("##Knife_combo", &selected_entry.definition_override_vector_index, [](void* data, int idx, const char** out_text) { *out_text = game_data::knife_names[idx].name; return true; }, nullptr, IM_ARRAYSIZE(game_data::knife_names))) need_update[current_profile] = true; // push force update } else if (current_profile == 1) { ImGui::Text("Gloves"); ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * c_menu::get().dpi_scale); if (ImGui::Combo("##Glove_combo", &selected_entry.definition_override_vector_index, [](void* data, int idx, const char** out_text) { *out_text = game_data::glove_names[idx].name; return true; }, nullptr, IM_ARRAYSIZE(game_data::glove_names))) { item_index = 0; // set new generated paintkits element to 0; need_update[current_profile] = true; // push force update } } else selected_entry.definition_override_vector_index = 0; if (current_profile != 1) { ImGui::Text("Search"); if (ImGui::InputText("##search", search_skins, sizeof(search_skins))) item_index = -1; } auto main_kits = current_profile == 1 ? SkinChanger::gloveKits : SkinChanger::skinKits; auto display_index = 0; SkinChanger::displayKits = main_kits; // we dont need custom gloves if (current_profile == 1) { for (auto i = 0; i < main_kits.size(); i++) { auto main_name = main_kits.at(i).name; for (auto i = 0; i < main_name.size(); i++) if (iswalpha((main_name.at(i)))) main_name.at(i) = towlower(main_name.at(i)); char search_name[64]; if (!strcmp(game_data::glove_names[selected_entry.definition_override_vector_index].name, "Hydra")) strcpy_s(search_name, sizeof(search_name), "Bloodhound"); else strcpy_s(search_name, sizeof(search_name), game_data::glove_names[selected_entry.definition_override_vector_index].name); for (auto i = 0; i < sizeof(search_name); i++) if (iswalpha(search_name[i])) search_name[i] = towlower(search_name[i]); if (main_name.find(search_name) != std::string::npos) { SkinChanger::displayKits.at(display_index) = main_kits.at(i); display_index++; } } SkinChanger::displayKits.erase(SkinChanger::displayKits.begin() + display_index, SkinChanger::displayKits.end()); } else { // TODO: fix ru finding symbols ('Градиент' не будет найден по запросу 'градиент' etc) if (strcmp(search_skins, "")) //-V526 { for (auto i = 0; i < main_kits.size(); i++) { auto main_name = main_kits.at(i).name; for (auto i = 0; i < main_name.size(); i++) if (iswalpha(main_name.at(i))) main_name.at(i) = towlower(main_name.at(i)); char search_name[64]; strcpy_s(search_name, sizeof(search_name), search_skins); for (auto i = 0; i < sizeof(search_name); i++) if (iswalpha(search_name[i])) search_name[i] = towlower(search_name[i]); if (main_name.find(search_name) != std::string::npos) { SkinChanger::displayKits.at(display_index) = main_kits.at(i); display_index++; } } SkinChanger::displayKits.erase(SkinChanger::displayKits.begin() + display_index, SkinChanger::displayKits.end()); } else item_index = selected_entry.paint_kit_vector_index; } ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f); if (!SkinChanger::displayKits.empty()) { if (ImGui::ListBox("##PAINTKITS", &item_index, [](void* data, int idx, const char** out_text) { while (SkinChanger::displayKits.at(idx).name.find("С‘") != std::string::npos) //-V807 SkinChanger::displayKits.at(idx).name.replace(SkinChanger::displayKits.at(idx).name.find("С‘"), 2, "Рµ"); *out_text = SkinChanger::displayKits.at(idx).name.c_str(); return true; }, nullptr, SkinChanger::displayKits.size(), SkinChanger::displayKits.size() > 9 ? 9 : SkinChanger::displayKits.size()) || !all_skins[current_profile]) { g_ctx.globals.force_skin_update = true; need_update[current_profile] = true; auto i = 0; while (i < main_kits.size()) { if (main_kits.at(i).id == SkinChanger::displayKits.at(item_index).id) { selected_entry.paint_kit_vector_index = i; break; } i++; } } } ImGui::PopStyleVar(); if (ImGui::InputInt("Seed", &selected_entry.seed, 1, 100)) g_ctx.globals.force_skin_update = true; if (ImGui::InputInt("StatTrak", &selected_entry.stat_trak, 1, 15)) g_ctx.globals.force_skin_update = true; if (ImGui::SliderFloat("Wear", &selected_entry.wear, 0.0f, 1.0f)) drugs = true; else if (drugs) { g_ctx.globals.force_skin_update = true; drugs = false; } ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 6 * c_menu::get().dpi_scale); ImGui::Text("Quality"); ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * c_menu::get().dpi_scale); if (ImGui::Combo("##Quality_combo", &selected_entry.entity_quality_vector_index, [](void* data, int idx, const char** out_text) { *out_text = game_data::quality_names[idx].name; return true; }, nullptr, IM_ARRAYSIZE(game_data::quality_names))) g_ctx.globals.force_skin_update = true; if (current_profile != 1) { if (!g_cfg.skins.custom_name_tag[current_profile].empty()) strcpy_s(selected_entry.custom_name, sizeof(selected_entry.custom_name), g_cfg.skins.custom_name_tag[current_profile].c_str()); ImGui::Text("Name Tag"); if (ImGui::InputText("##nametag", selected_entry.custom_name, sizeof(selected_entry.custom_name))) { g_cfg.skins.custom_name_tag[current_profile] = selected_entry.custom_name; g_ctx.globals.force_skin_update = true; } } ImGui::PopItemWidth(); ImGui::EndGroup(); ImGui::SameLine(); ImGui::SetCursorPosX(ImGui::GetCursorPosX() + 286 * dpi_scale - 200 * dpi_scale); ImGui::BeginGroup(); if (ImGui::ImageButton(all_skins[current_profile], ImVec2(190 * dpi_scale, 155 * dpi_scale))) { // maybe i will do smth later where, who knows :/ } if (ImGui::CustomButton("Save & Close", "##SAVE__CLOSE__SKING", ImVec2(198 * dpi_scale, 26 * dpi_scale))) { // start animation active_animation = true; next_id = -1; leave = true; } ImGui::EndGroup(); // update element selected_entry.update(); // we need to reset profile in the end to prevent render images with massive's index == -1 if (leave && ((active_animation && preview_reverse) || !active_animation)) { g_ctx.globals.force_skin_update = true; ImGui::SetScrollY(0); current_profile = next_id; leave = false; } } } ImGui::EndChild(); tab_end(); } ImGui::EndChild(); } } void c_menu::draw_tabs_players() { const char* players_sections[3] = { "Enemy", "Team", "Local" }; draw_semitabs(players_sections, 3, players_section, ImGui::GetStyle()); } void c_menu::draw_players(int child) { auto player = players_section; static std::vector <Player_list_data> players; if (!g_cfg.player_list.refreshing) { players.clear(); for (auto player : g_cfg.player_list.players) players.emplace_back(player); } static auto current_player = 0; if (!child) { if (players_section < 3) { child_title("ESP"); tab_start(); ImGui::BeginChild("##ESP1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Enable"), &g_cfg.player.enable); if (player == ENEMY) { ImGui::Checkbox(crypt_str("OOF arrows"), &g_cfg.player.arrows); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##arrowscolor"), &g_cfg.player.arrows_color, ALPHA); if (g_cfg.player.arrows) { ImGui::SliderInt(crypt_str("Arrows distance"), &g_cfg.player.distance, 1, 100); ImGui::SliderInt(crypt_str("Arrows size"), &g_cfg.player.size, 1, 100); } } ImGui::Checkbox(crypt_str("Bounding box"), &g_cfg.player.type[player].box); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##boxcolor"), &g_cfg.player.type[player].box_color, ALPHA); ImGui::Checkbox(crypt_str("Name"), &g_cfg.player.type[player].name); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##namecolor"), &g_cfg.player.type[player].name_color, ALPHA); ImGui::Checkbox(crypt_str("Health bar"), &g_cfg.player.type[player].health); ImGui::Checkbox(crypt_str("Health color"), &g_cfg.player.type[player].custom_health_color); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##healthcolor"), &g_cfg.player.type[player].health_color, ALPHA); for (auto i = 0, j = 0; i < ARRAYSIZE(flags); i++) { if (g_cfg.player.type[player].flags[i]) { if (j) preview += crypt_str(", ") + (std::string)flags[i]; else preview = flags[i]; j++; } } draw_multicombo("Flags", g_cfg.player.type[player].flags, flags, ARRAYSIZE(flags), preview); draw_multicombo("Weapon", g_cfg.player.type[player].weapon, weaponplayer, ARRAYSIZE(weaponplayer), preview); if (g_cfg.player.type[player].weapon[WEAPON_ICON] || g_cfg.player.type[player].weapon[WEAPON_TEXT]) { ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##weapcolor"), &g_cfg.player.type[player].weapon_color, ALPHA); } ImGui::Checkbox(crypt_str("Skeleton"), &g_cfg.player.type[player].skeleton); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##skeletoncolor"), &g_cfg.player.type[player].skeleton_color, ALPHA); ImGui::Checkbox(crypt_str("Ammo bar"), &g_cfg.player.type[player].ammo); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##ammocolor"), &g_cfg.player.type[player].ammobar_color, ALPHA); ImGui::Checkbox(crypt_str("Footsteps"), &g_cfg.player.type[player].footsteps); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##footstepscolor"), &g_cfg.player.type[player].footsteps_color, ALPHA); if (g_cfg.player.type[player].footsteps) { ImGui::SliderInt(crypt_str("Thickness"), &g_cfg.player.type[player].thickness, 1, 10); ImGui::SliderInt(crypt_str("Radius"), &g_cfg.player.type[player].radius, 50, 500); } if (player == ENEMY || player == TEAM) { ImGui::Checkbox(crypt_str("Snap lines"), &g_cfg.player.type[player].snap_lines); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##snapcolor"), &g_cfg.player.type[player].snap_lines_color, ALPHA); if (player == ENEMY) { if (g_cfg.ragebot.enable) { ImGui::Checkbox(crypt_str("Aimbot points"), &g_cfg.player.show_multi_points); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##showmultipointscolor"), &g_cfg.player.show_multi_points_color, ALPHA); } ImGui::Checkbox(crypt_str("Aimbot hitboxes"), &g_cfg.player.lag_hitbox); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##lagcompcolor"), &g_cfg.player.lag_hitbox_color, ALPHA); } } else { draw_combo(crypt_str("Player model T"), g_cfg.player.player_model_t, player_model_t, ARRAYSIZE(player_model_t)); padding(0, 3); draw_combo(crypt_str("Player model CT"), g_cfg.player.player_model_ct, player_model_ct, ARRAYSIZE(player_model_ct)); } } ImGui::EndChild(); tab_end(); } else { child_title("Players"); tab_start(); ImGui::BeginChild("##ESP2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { if (!players.empty()) { std::vector <std::string> player_names; for (auto player : players) player_names.emplace_back(player.name); ImGui::PushItemWidth(291 * dpi_scale); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f); ImGui::ListBoxConfigArray(crypt_str("##PLAYERLIST"), &current_player, player_names, 14); ImGui::PopStyleVar(); ImGui::PopItemWidth(); } } ImGui::EndChild(); tab_end(); } } else { if (players_section > 2) { child_title("Settings"); tab_start(); ImGui::BeginChild("##ESP1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { if (!players.empty()) { if (current_player >= players.size()) current_player = players.size() - 1; //-V103 ImGui::Checkbox(crypt_str("White list"), &g_cfg.player_list.white_list[players.at(current_player).i]); //-V106 //-V807 if (!g_cfg.player_list.white_list[players.at(current_player).i]) //-V106 { // TODO: arty pidoras uncomment ImGui::Checkbox(crypt_str("High priority"), &g_cfg.player_list.high_priority[players.at(current_player).i]); //-V106 //ImGui::Checkbox(crypt_str("Force safe points"), &g_cfg.player_list.force_safe_points[players.at(current_player).i]); //-V106 ImGui::Checkbox(crypt_str("Force body aim"), &g_cfg.player_list.force_body_aim[players.at(current_player).i]); //-V106 //ImGui::Checkbox(crypt_str("Low delta"), &g_cfg.player_list.low_delta[players.at(current_player).i]); //-V106 } } } ImGui::EndChild(); tab_end(); } else { child_title("Model"); tab_start(); ImGui::BeginChild("##ESP2_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Spacing(); if (player == LOCAL) draw_combo(crypt_str("Type"), g_cfg.player.local_chams_type, local_chams_type, ARRAYSIZE(local_chams_type)); if (player != LOCAL || !g_cfg.player.local_chams_type) draw_multicombo("Chams", g_cfg.player.type[player].chams, g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE] ? chamsvisact : chamsvis, g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE] ? ARRAYSIZE(chamsvisact) : ARRAYSIZE(chamsvis), preview); if (g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE] || player == LOCAL && g_cfg.player.local_chams_type) { if (player == LOCAL && g_cfg.player.local_chams_type) { ImGui::Checkbox(crypt_str("Enable desync chams"), &g_cfg.player.fake_chams_enable); ImGui::Checkbox(crypt_str("Visualize lag"), &g_cfg.player.visualize_lag); ImGui::Checkbox(crypt_str("Layered"), &g_cfg.player.layered); draw_combo(crypt_str("Player chams material"), g_cfg.player.fake_chams_type, chamstype, ARRAYSIZE(chamstype)); ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##fakechamscolor"), &g_cfg.player.fake_chams_color, ALPHA); if (g_cfg.player.fake_chams_type != 6) { ImGui::Checkbox(crypt_str("Double material "), &g_cfg.player.fake_double_material); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##doublematerialcolor"), &g_cfg.player.fake_double_material_color, ALPHA); } ImGui::Checkbox(crypt_str("Animated material"), &g_cfg.player.fake_animated_material); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##animcolormat"), &g_cfg.player.fake_animated_material_color, ALPHA); } else { draw_combo(crypt_str("Player chams material"), g_cfg.player.type[player].chams_type, chamstype, ARRAYSIZE(chamstype)); if (g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE]) { ImGui::Text(crypt_str("Visible ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##chamsvisible"), &g_cfg.player.type[player].chams_color, ALPHA); } if (g_cfg.player.type[player].chams[PLAYER_CHAMS_VISIBLE] && g_cfg.player.type[player].chams[PLAYER_CHAMS_INVISIBLE]) { ImGui::Text(crypt_str("Invisible ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##chamsinvisible"), &g_cfg.player.type[player].xqz_color, ALPHA); } if (g_cfg.player.type[player].chams_type != 6) { ImGui::Checkbox(crypt_str("Double material "), &g_cfg.player.type[player].double_material); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##doublematerialcolor"), &g_cfg.player.type[player].double_material_color, ALPHA); } ImGui::Checkbox(crypt_str("Animated material"), &g_cfg.player.type[player].animated_material); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##animcolormat"), &g_cfg.player.type[player].animated_material_color, ALPHA); if (player == ENEMY) { ImGui::Checkbox(crypt_str("Backtrack chams"), &g_cfg.player.backtrack_chams); if (g_cfg.player.backtrack_chams) { draw_combo(crypt_str("Backtrack chams material"), g_cfg.player.backtrack_chams_material, chamstype, ARRAYSIZE(chamstype)); ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("##backtrackcolor"), &g_cfg.player.backtrack_chams_color, ALPHA); } } } } if (player == ENEMY || player == TEAM) { ImGui::Checkbox(crypt_str("Ragdoll chams"), &g_cfg.player.type[player].ragdoll_chams); if (g_cfg.player.type[player].ragdoll_chams) { draw_combo(crypt_str("Ragdoll chams material"), g_cfg.player.type[player].ragdoll_chams_material, chamstype, ARRAYSIZE(chamstype)); ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("ragdollcolor"), &g_cfg.player.type[player].ragdoll_chams_color, ALPHA); } } else if (!g_cfg.player.local_chams_type) { ImGui::Checkbox(crypt_str("Transparency in scope"), &g_cfg.player.transparency_in_scope); if (g_cfg.player.transparency_in_scope) ImGui::SliderFloat(crypt_str("Alpha"), &g_cfg.player.transparency_in_scope_amount, 0.0f, 1.0f); } ImGui::Spacing(); ImGui::Checkbox(crypt_str("Glow"), &g_cfg.player.type[player].glow); if (g_cfg.player.type[player].glow) { draw_combo(crypt_str("Glow type"), g_cfg.player.type[player].glow_type, glowtype, ARRAYSIZE(glowtype)); ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("glowcolor"), &g_cfg.player.type[player].glow_color, ALPHA); } } ImGui::EndChild(); tab_end(); } } } void c_menu::draw_tabs_misc() { const char* misc_sections[2] = { "Main", "Additives" }; draw_semitabs(misc_sections, 2, misc_section, ImGui::GetStyle()); } void c_menu::draw_misc(int child) { if (!child) { if (!misc_section) { child_title("General"); tab_start(); ImGui::BeginChild("##MISC1_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Anti-untrusted"), &g_cfg.misc.anti_untrusted); ImGui::Checkbox(crypt_str("Rank reveal"), &g_cfg.misc.rank_reveal); ImGui::Checkbox(crypt_str("Unlock inventory access"), &g_cfg.misc.inventory_access); ImGui::Checkbox(crypt_str("Gravity ragdolls"), &g_cfg.misc.ragdolls); ImGui::Checkbox(crypt_str("Preserve killfeed"), &g_cfg.esp.preserve_killfeed); ImGui::Checkbox(crypt_str("Aspect ratio"), &g_cfg.misc.aspect_ratio); if (g_cfg.misc.aspect_ratio) { padding(0, -5); ImGui::SliderFloat(crypt_str("Amount"), &g_cfg.misc.aspect_ratio_amount, 1.0f, 2.0f); } ImGui::Checkbox(crypt_str("Fake lag"), &g_cfg.antiaim.fakelag); if (g_cfg.antiaim.fakelag) { draw_combo(crypt_str("Fake lag type"), g_cfg.antiaim.fakelag_type, fakelags, ARRAYSIZE(fakelags)); ImGui::SliderInt(crypt_str("Limit"), &g_cfg.antiaim.fakelag_amount, 1, 16); draw_multicombo("Fake lag triggers", g_cfg.antiaim.fakelag_enablers, lagstrigger, ARRAYSIZE(lagstrigger), preview); auto enabled_fakelag_triggers = false; for (auto i = 0; i < ARRAYSIZE(lagstrigger); i++) if (g_cfg.antiaim.fakelag_enablers[i]) enabled_fakelag_triggers = true; if (enabled_fakelag_triggers) ImGui::SliderInt(crypt_str("Triggers limit"), &g_cfg.antiaim.triggers_fakelag_amount, 1, 16); } draw_keybind("Teleport Exploit", &g_cfg.misc.teleport_exploit, "##TP_HOTKEY"); } ImGui::EndChild(); tab_end(); } else { child_title("Information"); tab_start(); ImGui::BeginChild("##MISC1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Watermark"), &g_cfg.menu.watermark); ImGui::Checkbox(crypt_str("Spectators list"), &g_cfg.misc.spectators_list); draw_combo(crypt_str("Hitsound"), g_cfg.esp.hitsound, sounds, ARRAYSIZE(sounds)); ImGui::Checkbox(crypt_str("Killsound"), &g_cfg.esp.killsound); draw_multicombo(crypt_str("Logs"), g_cfg.misc.events_to_log, events, ARRAYSIZE(events), preview); padding(0, 3); draw_multicombo(crypt_str("Logs output"), g_cfg.misc.log_output, events_output, ARRAYSIZE(events_output), preview); if (g_cfg.misc.events_to_log[EVENTLOG_HIT] || g_cfg.misc.events_to_log[EVENTLOG_ITEM_PURCHASES] || g_cfg.misc.events_to_log[EVENTLOG_BOMB]) { ImGui::Text(crypt_str("Color ")); ImGui::SameLine(); ImGui::ColorEdit(crypt_str("logcolor"), &g_cfg.misc.log_color, ALPHA); } ImGui::Checkbox(crypt_str("Show CS:GO logs"), &g_cfg.misc.show_default_log); } ImGui::EndChild(); tab_end(); } } else { if (!misc_section) { child_title("Movement"); tab_start(); ImGui::BeginChild("##MISC2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Automatic jump"), &g_cfg.misc.bunnyhop); draw_combo(crypt_str("Automatic strafes"), g_cfg.misc.airstrafe, strafes, ARRAYSIZE(strafes)); ImGui::Checkbox(crypt_str("Crouch in air"), &g_cfg.misc.crouch_in_air); ImGui::Checkbox(crypt_str("Fast stop"), &g_cfg.misc.fast_stop); ImGui::Checkbox(crypt_str("Slide walk"), &g_cfg.misc.slidewalk); ImGui::Checkbox(crypt_str("No duck cooldown"), &g_cfg.misc.noduck); if (g_cfg.misc.noduck) draw_keybind(crypt_str("Fakeduck"), &g_cfg.misc.fakeduck_key, crypt_str("##FAKEDUCK__HOTKEY")); draw_keybind(crypt_str("Slowwalk"), &g_cfg.misc.slowwalk_key, crypt_str("##SLOWWALK__HOTKEY")); draw_keybind(crypt_str("Auto peek"), &g_cfg.misc.automatic_peek, crypt_str("##AUTOPEEK__HOTKEY")); draw_keybind(crypt_str("Edge jump"), &g_cfg.misc.edge_jump, crypt_str("##EDGEJUMP__HOTKEY")); } ImGui::EndChild(); tab_end(); } else { child_title("Extra"); tab_start(); ImGui::BeginChild("##MISC2_SECOND", ImVec2(317 * dpi_scale, (child_height - 35)* dpi_scale)); { ImGui::Checkbox(crypt_str("Anti-screenshot"), &g_cfg.misc.anti_screenshot); ImGui::Checkbox(crypt_str("Clantag"), &g_cfg.misc.clantag_spammer); ImGui::Checkbox(crypt_str("Chat spam"), &g_cfg.misc.chat); ImGui::Checkbox(crypt_str("Enable buybot"), &g_cfg.misc.buybot_enable); draw_combo(crypt_str("Snipers"), g_cfg.misc.buybot1, mainwep, ARRAYSIZE(mainwep)); padding(0, 3); draw_combo(crypt_str("Pistols"), g_cfg.misc.buybot2, secwep, ARRAYSIZE(secwep)); padding(0, 3); draw_multicombo("Other", g_cfg.misc.buybot3, grenades, ARRAYSIZE(grenades), preview); #if !RELEASE ImGui::Text("DPI Scale"); ImGui::SetCursorPosY(ImGui::GetCursorPosY() - 5 * dpi_scale); if (ImGui::DragFloat("##DPIScale", &dpi_scale, 0.005f, 1.f, 1.8f, "%.2f")) update_dpi = true; #endif } ImGui::EndChild(); tab_end(); } } } void c_menu::draw_settings(int child) { child_title("Configs"); tab_start(); ImGui::BeginChild("##CONFIGS__FIRST", ImVec2(686 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::BeginChild("##CONFIGS__FIRST_POSHELNAHUI", ImVec2(686 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::PushItemWidth(629 * c_menu::get().dpi_scale); static auto should_update = true; if (should_update) { should_update = false; cfg_manager->config_files(); files = cfg_manager->files; for (auto& current : files) if (current.size() > 2) current.erase(current.size() - 3, 3); } if (ImGui::CustomButton("Open configs folder", "##CONFIG__FOLDER", ImVec2(629 * dpi_scale, 26 * dpi_scale))) { std::string folder; auto get_dir = [&folder]() -> void { static TCHAR path[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, NULL, path))) folder = std::string(path) + crypt_str("\\Legendware\\Configs\\"); CreateDirectory(folder.c_str(), NULL); }; get_dir(); ShellExecute(NULL, crypt_str("open"), folder.c_str(), NULL, NULL, SW_SHOWNORMAL); } ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f); ImGui::ListBoxConfigArray(crypt_str("##CONFIGS"), &g_cfg.selected_config, files, 7); ImGui::PopStyleVar(); if (ImGui::CustomButton("Refresh configs", "##CONFIG__REFRESH", ImVec2(629 * dpi_scale, 26 * dpi_scale))) { cfg_manager->config_files(); files = cfg_manager->files; for (auto& current : files) if (current.size() > 2) current.erase(current.size() - 3, 3); } static char config_name[64] = "\0"; ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f); ImGui::InputText(crypt_str("##configname"), config_name, sizeof(config_name)); ImGui::PopStyleVar(); if (ImGui::CustomButton("Create config", "##CONFIG__CREATE", ImVec2(629 * dpi_scale, 26 * dpi_scale))) { g_cfg.new_config_name = config_name; add_config(); } /* SAVE BUTTON */ static bool next_save = false; static bool prenext_save = false; static bool clicked_sure = false; static auto save_time = m_globals()->m_realtime; static float save_alpha = 1.f; save_alpha = math::clamp(save_alpha + (4.f * ImGui::GetIO().DeltaTime * (!prenext_save ? 1.f : -1.f)), 0.01f, 1.f); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, save_alpha * public_alpha * (1.f - preview_alpha)); if (!next_save) { clicked_sure = false; if (prenext_save && save_alpha <= 0.01f) next_save = true; if (ImGui::CustomButton("Save config", "##CONFIG__SAVE", ImVec2(629 * dpi_scale, 26 * dpi_scale))) { save_time = m_globals()->m_realtime; prenext_save = true; } } else { if (prenext_save && save_alpha <= 0.01f) { prenext_save = false; next_save = !clicked_sure; } if (ImGui::CustomButton("Are you sure?", "##AREYOUSURE__SAVE", ImVec2(629 * dpi_scale, 26 * dpi_scale))) { save_config(); prenext_save = true; clicked_sure = true; } if (!clicked_sure && m_globals()->m_realtime > save_time + 3.f) { prenext_save = true; clicked_sure = true; } } ImGui::PopStyleVar(); /* */ if (ImGui::CustomButton("Load config", "##CONFIG__LOAD", ImVec2(629 * dpi_scale, 26 * dpi_scale))) load_config(); /* DELETE BUTTON */ static bool next_delete = false; static bool prenext_delete = false; static bool clicked_sure_del = false; static auto delete_time = m_globals()->m_realtime; static float delete_alpha = 1.f; delete_alpha = math::clamp(delete_alpha + (4.f * ImGui::GetIO().DeltaTime * (!prenext_delete ? 1.f : -1.f)), 0.01f, 1.f); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, delete_alpha * public_alpha * (1.f - preview_alpha)); if (!next_delete) { clicked_sure_del = false; if (prenext_delete && delete_alpha <= 0.01f) next_delete = true; if (ImGui::CustomButton("Remove config", "##CONFIG__delete", ImVec2(629 * dpi_scale, 26 * dpi_scale))) { delete_time = m_globals()->m_realtime; prenext_delete = true; } } else { if (prenext_delete && delete_alpha <= 0.01f) { prenext_delete = false; next_delete = !clicked_sure_del; } if (ImGui::CustomButton("Are you sure?", "##AREYOUSURE__delete", ImVec2(629 * dpi_scale, 26 * dpi_scale))) { remove_config(); prenext_delete = true; clicked_sure_del = true; } if (!clicked_sure_del && m_globals()->m_realtime > delete_time + 3.f) { prenext_delete = true; clicked_sure_del = true; } } ImGui::PopStyleVar(); /* */ ImGui::PopItemWidth(); } ImGui::EndChild(); ImGui::SetWindowFontScale(c_menu::get().dpi_scale); } ImGui::EndChild(); ImGui::PopStyleVar(); } void c_menu::draw_lua(int child) { if (!child) { child_title("Scripts"); tab_start(); ImGui::BeginChild("##LUA_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::PushItemWidth(291 * c_menu::get().dpi_scale); static auto should_update = true; if (should_update) { should_update = false; scripts = c_lua::get().scripts; for (auto& current : scripts) { if (current.size() >= 5 && current.at(current.size() - 1) == 'c') current.erase(current.size() - 5, 5); else if (current.size() >= 4) current.erase(current.size() - 4, 4); } } if (ImGui::CustomButton("Open scripts folder", "##LUAS__FOLDER", ImVec2(291 * dpi_scale, 26 * dpi_scale))) { std::string folder; auto get_dir = [&folder]() -> void { static TCHAR path[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, NULL, path))) folder = std::string(path) + crypt_str("\\Legendware\\Scripts\\"); CreateDirectory(folder.c_str(), NULL); }; get_dir(); ShellExecute(NULL, crypt_str("open"), folder.c_str(), NULL, NULL, SW_SHOWNORMAL); } ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f); if (scripts.empty()) ImGui::ListBoxConfigArray(crypt_str("##LUAS"), &selected_script, scripts, 10); else { auto backup_scripts = scripts; for (auto& script : scripts) { auto script_id = c_lua::get().get_script_id(script + crypt_str(".lua")); if (script_id == -1) continue; if (c_lua::get().loaded.at(script_id)) scripts.at(script_id) += crypt_str(" [loaded]"); } ImGui::ListBoxConfigArray(crypt_str("##LUAS"), &selected_script, scripts, 10); scripts = std::move(backup_scripts); } ImGui::PopStyleVar(); if (ImGui::CustomButton("Refresh scripts", "##LUA__REFRESH", ImVec2(291 * dpi_scale, 26 * dpi_scale))) { c_lua::get().refresh_scripts(); scripts = c_lua::get().scripts; if (selected_script >= scripts.size()) selected_script = scripts.size() - 1; //-V103 for (auto& current : scripts) { if (current.size() >= 5 && current.at(current.size() - 1) == 'c') current.erase(current.size() - 5, 5); else if (current.size() >= 4) current.erase(current.size() - 4, 4); } } // TOOD: заставить кнопку работать if (ImGui::CustomButton("Edit script", "##LUA__EDIT", ImVec2(291 * dpi_scale, 26 * dpi_scale))) { } ImGui::PopItemWidth(); } ImGui::EndChild(); tab_end(); } else { child_title("Script elements"); tab_start(); ImGui::BeginChild("##LUA_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { } ImGui::EndChild(); tab_end(); } } void c_menu::draw_radar(int child) { if (!child) { child_title("Hud radar"); tab_start(); ImGui::BeginChild("##RADAR_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Engine radar"), &g_cfg.misc.engine_radar); ImGui::Checkbox(crypt_str("Disable rendering"), &g_cfg.misc.disable_radar_render); // TODO: cl_drawhud 0 } ImGui::EndChild(); tab_end(); } else { child_title("Custom radar"); tab_start(); ImGui::BeginChild("##RADAR_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { ImGui::Checkbox(crypt_str("Draw custom radar"), &g_cfg.misc.ingame_radar); ImGui::Checkbox(crypt_str("Render local"), &g_cfg.radar.render_local); ImGui::Checkbox(crypt_str("Render enemy"), &g_cfg.radar.render_enemy); ImGui::Checkbox(crypt_str("Render team"), &g_cfg.radar.render_team); ImGui::Checkbox(crypt_str("Show planted c4"), &g_cfg.radar.render_planted_c4); ImGui::Checkbox(crypt_str("Show dropped c4"), &g_cfg.radar.render_dropped_c4); ImGui::Checkbox(crypt_str("Show health"), &g_cfg.radar.render_health); } ImGui::EndChild(); tab_end(); } } void c_menu::draw_profile(int child) { auto player = players_section; static std::vector <Player_list_data> players; if (!g_cfg.player_list.refreshing) { players.clear(); for (auto player : g_cfg.player_list.players) players.emplace_back(player); } static auto current_player = 0; if (!child) { child_title("Players"); tab_start(); ImGui::BeginChild("##ESP2_FIRST", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { if (!players.empty()) { std::vector <std::string> player_names; for (auto player : players) player_names.emplace_back(player.name); ImGui::PushItemWidth(291 * dpi_scale); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f); ImGui::ListBoxConfigArray(crypt_str("##PLAYERLIST"), &current_player, player_names, 14); ImGui::PopStyleVar(); ImGui::PopItemWidth(); } } ImGui::EndChild(); tab_end(); } else { child_title("Settings"); tab_start(); ImGui::BeginChild("##ESP1_SECOND", ImVec2(317 * dpi_scale, (child_height - 35) * dpi_scale)); { if (!players.empty()) { if (current_player >= players.size()) current_player = players.size() - 1; //-V103 ImGui::Checkbox(crypt_str("White list"), &g_cfg.player_list.white_list[players.at(current_player).i]); //-V106 //-V807 if (!g_cfg.player_list.white_list[players.at(current_player).i]) //-V106 { // TODO: arty pidoras uncomment ImGui::Checkbox(crypt_str("High priority"), &g_cfg.player_list.high_priority[players.at(current_player).i]); //-V106 //ImGui::Checkbox(crypt_str("Force safe points"), &g_cfg.player_list.force_safe_points[players.at(current_player).i]); //-V106 ImGui::Checkbox(crypt_str("Force body aim"), &g_cfg.player_list.force_body_aim[players.at(current_player).i]); //-V106 //ImGui::Checkbox(crypt_str("Low delta"), &g_cfg.player_list.low_delta[players.at(current_player).i]); //-V106 } } } ImGui::EndChild(); tab_end(); } } void c_menu::draw(bool is_open) { // animation related code static float m_alpha = 0.0002f; m_alpha = math::clamp(m_alpha + (3.f * ImGui::GetIO().DeltaTime * (is_open ? 1.f : -1.f)), 0.0001f, 1.f); // set alpha in class to use later in widgets public_alpha = m_alpha; if (m_alpha == 0.0001f) return; // set new alpha ImGui::PushStyleVar(ImGuiStyleVar_Alpha, m_alpha); // setup colors and some styles if (!menu_setupped) menu_setup(ImGui::GetStyle()); ImGui::PushStyleColor(ImGuiCol_ScrollbarGrab, ImVec4(ImGui::GetStyle().Colors[ImGuiCol_ScrollbarGrab].x, ImGui::GetStyle().Colors[ImGuiCol_ScrollbarGrab].y, ImGui::GetStyle().Colors[ImGuiCol_ScrollbarGrab].z, m_alpha)); // default menu size const int x = 850, y = 560; // last active tab to switch effect & reverse alpha & preview alpha // IMPORTANT: DO TAB SWITCHING BY LAST_TAB!!!!! static int last_tab = active_tab; static bool preview_reverse = false; // preview for multicombos std::string preview = "None"; // lua editor (test) // TODO: get name of script(not a path!!!!!) lua_edit("kon_utils"); // start menu render ImGui::Begin("lw3", nullptr, ImGuiWindowFlags_NoDecoration); { auto p = ImGui::GetWindowPos(); // main dpi update logic // KEYWORD : DPI_FIND if (update_dpi) { // prevent oversizing dpi_scale = min(1.8f, max(dpi_scale, 1.f)); // font and window size setting ImGui::SetWindowFontScale(dpi_scale); ImGui::SetWindowSize(ImVec2(ImFloor(x * dpi_scale), ImFloor(y * dpi_scale))); // styles resizing dpi_resize(dpi_scale, ImGui::GetStyle()); // setup new window sizes width = ImFloor(x * dpi_scale); height = ImFloor(y * dpi_scale); // end of dpi updating update_dpi = false; } // set padding to draw { tabs , main functional area } / close group to draw last bottom child at x-0 pos ImGui::SetCursorPos(ImVec2(10 * dpi_scale, 13 * dpi_scale)); ImGui::BeginGroup(); ImGui::BeginChild("##tabs_area", ImVec2(124 * dpi_scale, 509 * dpi_scale)); // there will be tabs { // KEYWORD : TABS_FIND ImGui::PushFont(futura); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(8.f * dpi_scale, 12.f * dpi_scale)); // some extra pdding ImGui::Spacing(); // we need some more checks to prevent over-switching tabs if (ImGui::MainTab("Ragebot", ico_menu, "R", active_tab == 0, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 0; if (ImGui::MainTab("Legit", ico_menu, "L", active_tab == 1, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 1; if (ImGui::MainTab("Visuals", ico_menu, "V", active_tab == 2, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 2; if (ImGui::MainTab("Players", ico_menu, "P", active_tab == 3, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 3; if (ImGui::MainTab("Misc", ico_menu, "M", active_tab == 4, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 4; if (ImGui::MainTab("Settings", ico_menu, "S", active_tab == 5, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 5; // seperate our main-func tabs with additional tabs ImGui::Spacing(); ImGui::Spacing(); if (ImGui::MainTab("Player list", ico_bottom, "P", active_tab == 8, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 8; if (ImGui::MainTab("Radar", ico_bottom, "R", active_tab == 7, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 7; if (ImGui::MainTab("Lua", ico_bottom, "L", active_tab == 6, ImVec2(124 * dpi_scale, 0)) && last_tab == active_tab && !preview_reverse) active_tab = 6; ImGui::PopStyleVar(); ImGui::PopFont(); } ImGui::EndChild(); ImGui::SameLine(); // vertical separator after tabs ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorPos() + p + ImVec2(3 * dpi_scale, 0), ImGui::GetCursorPos() + p + ImVec2(4 * dpi_scale, 479 * dpi_scale), ImGui::ColorConvertFloat4ToU32(ImVec4(66 / 255.f, 68 / 255.f, 125 / 255.f, m_alpha * 0.3f))); /* \\ let's set alpha of rect when we will switch tab // */ // ̶c̶h̶e̶c̶k̶ ̶E̶n̶d̶C̶h̶i̶l̶d̶()̶ ̶f̶o̶r̶ ̶m̶o̶r̶e̶ ̶i̶n̶f̶o̶r̶m̶a̶t̶i̶o̶n if (last_tab != active_tab || (last_tab == active_tab && preview_reverse)) { if (!preview_reverse) { if (preview_alpha == 1.f) preview_reverse = true; preview_alpha = math::clamp(preview_alpha + (4.f * ImGui::GetIO().DeltaTime), 0.01f, 1.f); } else { last_tab = active_tab; if (preview_alpha == 0.01f) { preview_reverse = false; } preview_alpha = math::clamp(preview_alpha - (4.f * ImGui::GetIO().DeltaTime), 0.01f, 1.f); } } else preview_alpha = math::clamp(preview_alpha - (4.f * ImGui::GetIO().DeltaTime), 0.0f, 1.f); /* \\--------------------------------------------------------------// */ ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (12 * dpi_scale)); ImGui::BeginChild("##content_area", ImVec2(686 * dpi_scale, 479 * dpi_scale)); // there wiil be main cheat functional { // KEYWORD : FUNC_FIND ImGui::PushFont(futura); if (last_tab > 4) child_height = 471; else child_height = 435; // push alpha-channel adjustment ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha) * m_alpha); // semitabs rendering switch (last_tab % 9) { case 0: draw_tabs_ragebot(); break; case 1: draw_tabs_legit(); break; case 2: draw_tabs_visuals(); break; case 3: draw_tabs_players(); break; case 4: draw_tabs_misc(); break; default: break; } ImGui::PopStyleVar(); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (6 * dpi_scale) + ((dpi_scale - 1.f) * 8.f)); ImGui::BeginGroup(); // groupping two childs to prevent multipadding { ImGui::PushFont(futura_small); if (last_tab == 2 && visuals_section == 2) { draw_visuals(-1); } else if (last_tab == 5) { ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha)* m_alpha); draw_settings(0); } else { ImGui::BeginChild("##content_first", ImVec2(339 * dpi_scale, child_height * dpi_scale)); // first functional child { ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha) * m_alpha); switch (last_tab % 9) { case 0: draw_ragebot(0); break; case 1: draw_legit(0); break; case 2: draw_visuals(0); break; case 3: draw_players(0); break; case 4: draw_misc(0); break; case 6: draw_lua(0); break; case 7: draw_radar(0); break; case 8: draw_profile(0); break; default: break; } } ImGui::EndChild(); ImGui::SameLine(); ImGui::BeginChild("##content_second", ImVec2(339 * dpi_scale, child_height * dpi_scale)); // second functional child { ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (1.f - preview_alpha) * m_alpha); switch (last_tab % 9) { case 0: draw_ragebot(1); break; case 1: draw_legit(1); break; case 2: draw_visuals(1); break; case 3: draw_players(1); break; case 4: draw_misc(1); break; case 6: draw_lua(1); break; case 7: draw_radar(1); break; case 8: draw_profile(1); break; default: break; } } ImGui::EndChild(); } ImGui::PopFont(); }; ImGui::EndGroup(); ImGui::PopFont(); } ImGui::EndChild(); ImGui::EndGroup(); /* ------ BOTTOM ------ */ // Fill bottom ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorPos() + p, ImGui::GetCursorPos() + p + ImVec2(850 * dpi_scale, ((dpi_scale >= 1.04f && dpi_scale <= 1.07f) ? 2 : 0) + (29 * dpi_scale + (9.45f * (dpi_scale - 1.f)))), ImGui::ColorConvertFloat4ToU32(ImVec4(66 / 255.f, 68 / 255.f, 125 / 255.f, m_alpha)), 7.f * dpi_scale, ImDrawCornerFlags_Bot); ImGui::PushFont(gotham); ImGui::SetCursorPos(ImGui::GetCursorPos() + ImVec2(850 * dpi_scale - ImGui::CalcTextSize("legendawre.pw v3").x - (11 * dpi_scale), (16 * dpi_scale) - (ImGui::CalcTextSize("legendawre.pw v3").y / 2))); ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.f, 1.f, 1.f, 1.f)); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, m_alpha); ImGui::Text("legendware.pw v3"); ImGui::PopStyleVar(); ImGui::PopStyleColor(); ImGui::PopFont(); } ImGui::End(); ImGui::PopStyleColor(); ImGui::PopStyleVar(); }
32.634443
353
0.669592
[ "render", "vector", "model" ]
80338642587696c85e8070a42c97590c0a344609
7,473
cpp
C++
src/mongo/db/s/resharding/resharding_oplog_session_application.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/s/resharding/resharding_oplog_session_application.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/s/resharding/resharding_oplog_session_application.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2021-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/db/s/resharding/resharding_oplog_session_application.h" #include "mongo/db/catalog_raii.h" #include "mongo/db/concurrency/exception_util.h" #include "mongo/db/dbdirectclient.h" #include "mongo/db/operation_context.h" #include "mongo/db/repl/oplog_entry.h" #include "mongo/db/s/resharding/resharding_data_copy_util.h" #include "mongo/db/storage/write_unit_of_work.h" #include "mongo/db/transaction_participant.h" #include "mongo/logv2/redaction.h" namespace mongo { ReshardingOplogSessionApplication::ReshardingOplogSessionApplication(NamespaceString oplogBufferNss) : _oplogBufferNss(std::move(oplogBufferNss)) {} boost::optional<repl::OpTime> ReshardingOplogSessionApplication::_logPrePostImage( OperationContext* opCtx, const ReshardingDonorOplogId& opId, const repl::OpTime& prePostImageOpTime) const { DBDirectClient client(opCtx); auto prePostImageTxnOpId = ReshardingDonorOplogId{opId.getClusterTime(), prePostImageOpTime.getTimestamp()}; auto prePostImageNonTxnOpId = ReshardingDonorOplogId{prePostImageOpTime.getTimestamp(), prePostImageOpTime.getTimestamp()}; auto result = client.findOne(_oplogBufferNss, BSON(repl::OplogEntry::k_idFieldName << BSON("$in" << BSON_ARRAY(prePostImageTxnOpId.toBSON() << prePostImageNonTxnOpId.toBSON())))); tassert(6344401, str::stream() << "Could not find pre/post image oplog entry with op time " << redact(prePostImageOpTime.toBSON()), !result.isEmpty()); auto prePostImageOp = uassertStatusOK(repl::DurableOplogEntry::parse(result)); uassert(4990408, str::stream() << "Expected a no-op oplog entry for pre/post image oplog entry: " << redact(prePostImageOp.toBSON()), prePostImageOp.getOpType() == repl::OpTypeEnum::kNoop); auto noopEntry = uassertStatusOK(repl::MutableOplogEntry::parse(prePostImageOp.toBSON())); // Reset the OpTime so logOp() can assign a new one. noopEntry.setOpTime(OplogSlot()); noopEntry.setWallClockTime(opCtx->getServiceContext()->getFastClockSource()->now()); noopEntry.setFromMigrate(true); return writeConflictRetry( opCtx, "ReshardingOplogSessionApplication::_logPrePostImage", NamespaceString::kRsOplogNamespace.ns(), [&] { AutoGetOplog oplogWrite(opCtx, OplogAccessMode::kWrite); WriteUnitOfWork wuow(opCtx); const auto& opTime = repl::logOp(opCtx, &noopEntry); uassert(4990409, str::stream() << "Failed to create new oplog entry for pre/post image oplog" " entry with original opTime: " << prePostImageOp.getOpTime().toString() << ": " << redact(noopEntry.toBSON()), !opTime.isNull()); wuow.commit(); return opTime; }); } boost::optional<SharedSemiFuture<void>> ReshardingOplogSessionApplication::tryApplyOperation( OperationContext* opCtx, const mongo::repl::OplogEntry& op) const { invariant(op.getSessionId()); invariant(op.getTxnNumber()); invariant(op.get_id()); auto lsid = *op.getSessionId(); if (isInternalSessionForNonRetryableWrite(lsid)) { // Skip internal sessions for non-retryable writes since they only support transactions // and those transactions are not retryable so there is no need to transfer the write // history to resharding recipient(s). return boost::none; } if (isInternalSessionForRetryableWrite(lsid)) { // The oplog preparer should have turned each applyOps oplog entry for a retryable internal // transaction into retryable write CRUD oplog entries. invariant(op.getCommandType() != repl::OplogEntry::CommandType::kApplyOps); if (op.getCommandType() == repl::OplogEntry::CommandType::kAbortTransaction) { // Skip this oplog entry since there is no retryable write history to apply and writing // a sentinel noop oplog entry would make retryable write statements that successfully // executed outside of this internal transaction not retryable. return boost::none; } } auto txnNumber = *op.getTxnNumber(); bool isRetryableWrite = op.isCrudOpType(); auto o2Field = isRetryableWrite ? op.getEntry().getRaw() : TransactionParticipant::kDeadEndSentinel; auto stmtIds = isRetryableWrite ? op.getStatementIds() : std::vector<StmtId>{kIncompleteHistoryStmtId}; invariant(!stmtIds.empty()); auto opId = ReshardingDonorOplogId::parse({"ReshardingOplogSessionApplication"}, op.get_id()->getDocument().toBson()); boost::optional<repl::OpTime> preImageOpTime; if (auto originalPreImageOpTime = op.getPreImageOpTime()) { preImageOpTime = _logPrePostImage(opCtx, opId, *originalPreImageOpTime); } boost::optional<repl::OpTime> postImageOpTime; if (auto originalPostImageOpTime = op.getPostImageOpTime()) { postImageOpTime = _logPrePostImage(opCtx, opId, *originalPostImageOpTime); } return resharding::data_copy::withSessionCheckedOut( opCtx, lsid, txnNumber, stmtIds.front(), [&] { resharding::data_copy::updateSessionRecord(opCtx, std::move(o2Field), std::move(stmtIds), std::move(preImageOpTime), std::move(postImageOpTime)); }); } } // namespace mongo
45.290909
100
0.653553
[ "vector" ]
d9a6b889edefa46298574076f280718c07966102
1,260
hpp
C++
src/Core/CommandInterpreter.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2017-02-17T13:01:13.000Z
2017-02-17T13:01:13.000Z
src/Core/CommandInterpreter.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
null
null
null
src/Core/CommandInterpreter.hpp
mlaszko/DisCODe
0042280ae6c1ace8c6e0fa25ae4d440512c113f6
[ "MIT" ]
1
2018-07-23T00:05:58.000Z
2018-07-23T00:05:58.000Z
/*! * \file CommandInterpreter.hpp * \brief Command interpreter. * \author mstefanc * \date Oct 3, 2010 */ #ifndef COMMANDINTERPRETER_HPP_ #define COMMANDINTERPRETER_HPP_ #include <vector> #include <string> #include <map> #include <boost/function.hpp> #include "Informer.hpp" namespace Core { struct Command { std::string command; std::vector<std::string> arguments; void print(); }; /*! * \brief Command interpreter */ class CommandInterpreter { public: typedef boost::function<std::string(std::vector<std::string>)> handler; CommandInterpreter(); virtual ~CommandInterpreter(); /*! * Try to parse and execute given command string. * * @param cmd command to execute * @return true on success */ std::string execute(const std::string & cmd); void addHandler(const std::string & cmd, handler h); void addInformer(Informer * informer) { informer->registerHandlers(*this); } void printCommands(); protected: /*! * Parse given command and return list of tokens. * * @param cmd command to parse * @return list of tokens */ Command parse(const std::string & cmd); typedef std::pair<std::string, handler> handler_pair; std::map<std::string, handler > handlers; }; } #endif /* COMMANDINTERPRETER_HPP_ */
17.260274
72
0.699206
[ "vector" ]
d9a96af5e02eba37cadd5f56cbfe8982b0dbea4f
9,151
cpp
C++
PearlSDL/src/Pearl/Core/Application.cpp
tissinn/PearlSDL
afae586a47a33118036f56ae1f9ea33efccacb1d
[ "Apache-2.0" ]
1
2020-06-29T06:55:10.000Z
2020-06-29T06:55:10.000Z
PearlSDL/src/Pearl/Core/Application.cpp
tissinn/PearlSDL
afae586a47a33118036f56ae1f9ea33efccacb1d
[ "Apache-2.0" ]
null
null
null
PearlSDL/src/Pearl/Core/Application.cpp
tissinn/PearlSDL
afae586a47a33118036f56ae1f9ea33efccacb1d
[ "Apache-2.0" ]
null
null
null
#include "pearlpch.h" #include "Application.h" namespace Pearl { Application* Application::s_Instance = nullptr; /** * Default Constructor * Clients: Do not initialize values in constructor: * See "OnAttach()". */ Application::Application() : m_Title(DEFAULT_TITLE), m_Width(DEFAULT_WIDTH), m_Height(DEFAULT_HEIGHT), m_Running(false) { s_Instance = this; m_InitTimer = Timer(); m_Window = NULL; m_Renderer = NULL; Uint32 windowFlags = DEFAULT_WINDOW_FLAGS; Uint32 renderFlags = DEFAULT_RENDER_FLAGS; m_InitTimer.Start(); if (!Create(windowFlags, renderFlags)) PL_LOG_ERROR("PearlSDL could not initialize."); } /** * Window Property Constructor * Sets custom window properties defined by client * Clients: Do not initialize values in constructor: * See "OnAttach()". * * @param title Sets the local title variable * @param width Sets the local width variable * @param height Sets the local height varaible * @param windowFlags Sets the window flags for the Create funtion. * @param renderFlags Sets the renderer flags for the Create function. */ Application::Application(const char* title, int width, int height, Uint32 windowFlags, Uint32 renderFlags) { s_Instance = this; m_Title = title; m_Width = width; m_Height = height; m_Running = false; m_InitTimer = Timer(); m_Window = NULL; m_Renderer = NULL; m_InitTimer.Start(); if (!Create(windowFlags, renderFlags)) PL_LOG_ERROR("PearlSDL could not initialize."); } /** * Destructor * Disposes of all the resources in the application. */ Application::~Application() { // Destroy InputManager delete m_InputManager; // Deallocate Scene Resources for (auto& value : m_SceneStack->GetScenes()) { if (value.second) value.second->OnDetach(); } // Destroy Assets & AssetStack delete m_AssetStack; // Destroy SceneStack delete m_SceneStack; // Destroy render target SDL_DestroyTexture(m_RenderTarget); // Destroy window & renderer SDL_DestroyRenderer(m_Renderer); SDL_DestroyWindow(m_Window); m_Window = NULL; m_Renderer = NULL; PL_LOG_INFO("Window and renderer successfully destroyed."); // Quit SDL subsystems TTF_Quit(); Mix_Quit(); IMG_Quit(); SDL_Quit(); PL_LOG_INFO("All SDL subsystems quit. Closing application..."); } /** * This is the window creation function. * * Initializes all of SDL's subsystems and creates window. * Creates the extern Renderer variable from Core.h * * @return Retuns bool flag whether created successfully * @param windowFlags Window flags from constructors * @param renderFlags Renderer flags from constructors */ bool Application::Create(Uint32 windowFlags, Uint32 renderFlags) { // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { PL_LOG_CRITICAL("SDL could not initialize! SDL Error: {}", SDL_GetError()); return false; } else { PL_LOG_INFO("Initialized SDL2"); // Set texture filtering to linear if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) { PL_LOG_WARN("Linear texture filtering not enalbed!"); } // Set default window flags if (!(windowFlags & DEFAULT_WINDOW_FLAGS)) { windowFlags |= DEFAULT_WINDOW_FLAGS; } // Create window m_Window = SDL_CreateWindow(m_Title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, m_Width, m_Height, windowFlags); if (m_Window == NULL) { PL_LOG_CRITICAL("Window could not be created! SDL Error: {}", SDL_GetError()); return false; } else { // Set default window flags if (!(renderFlags & DEFAULT_RENDER_FLAGS)) { renderFlags |= DEFAULT_RENDER_FLAGS; } // Create renderer for window m_Renderer = SDL_CreateRenderer(m_Window, -1, renderFlags); if (m_Renderer == NULL) { PL_LOG_CRITICAL("Renderer could not be created! SDL Error: {}", SDL_GetError()); return false; } else { // Create renderer target texture m_RenderTarget = SDL_CreateTexture(m_Renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, m_Width, m_Height); // Set resolution scaling SDL_RenderSetLogicalSize(m_Renderer, m_Width, m_Height); if (m_RenderTarget == NULL) { PL_LOG_CRITICAL("Renderer texture target could not be created! SDL Error: {}", SDL_GetError()); return false; } else { SDL_SetRenderTarget(m_Renderer, m_RenderTarget); } // Initialize renderer color SDL_SetRenderDrawColor(m_Renderer, 0, 0, 0, 0); // Initialize SDL2_image if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) { PL_LOG_CRITICAL("SDL2_image could not initialize! SDL_image Error: {}", IMG_GetError()); return false; } // Set window icon SDL_Surface* icon = IMG_Load("C:/Dev/PearlSDL/PearlSDL/src/Pearl/.res/icon.png"); SDL_SetWindowIcon(m_Window, icon); PL_LOG_INFO("Initialized SDL2 image"); // Initialize SDL2_mixer if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_CHANNELS, 2048) < 0) { PL_LOG_CRITICAL("SDL2_mixer could not initialize! SDL_mixer Error: {}", Mix_GetError()); return false; } PL_LOG_INFO("Initialized SDL2 mixer"); // Initialize SDL_ttf if (TTF_Init() == -1) { PL_LOG_CRITICAL("SDL2_ttf could not initialize! SDL_ttf Error: {}", TTF_GetError()); return false; } PL_LOG_INFO("Initialized SDL2 ttf"); } } } return true; } /** * This is the application initialization function * Initializes PearlSDL subsytems * * @return Retuns bool flag whether init successfully. */ bool Application::Init() { // Init subsystems m_SceneStack = new SceneStack(); m_AssetStack = new AssetStack(); m_InputManager = new InputManager(); // Call derived OnAttach(); // Enter game loop Start(); // End Initialization Timer PL_LOG_INFO("Done! Initialized PearlSDL in {} ms.", m_InitTimer); m_InitTimer.Stop(); return true; } /** * This is the internal event handling function. * Handles SDL_Event objects in a while loop. * * @param e SDL_Event object passed in from Run() */ void Application::IOnEvent(SDL_Event& e) { // Update InputManager m_InputManager->UpdateInput(); // Call derived OnInput(); // Handle Scene Input m_SceneStack->OnInput(); // Update previous inputs m_InputManager->UpdatePrevInput(); // Poll events in the queue while (SDL_PollEvent(&e) != 0) { // User requests quit if (e.type == SDL_QUIT) { Stop(); } // Call derived OnEvent(e); // Call SceneStack m_SceneStack->OnEvent(e); } } /** * This is the internal game update function. * Updates the SceneStack. * * @param ts Timestep object that keeps track of delta time. */ void Application::IOnUpdate(Timestep ts) { // Fade out render target as necessary if (m_FadingOut) { if (m_FadeAlpha - (m_FadeSpeed * ts) <= 0) { m_FadeAlpha = 0.0f; m_FadingOut = false; } else { m_FadeAlpha -= m_FadeSpeed * ts; } } // Fade in render target as necessary if (m_FadingIn) { if (m_FadeAlpha + (m_FadeSpeed * ts) >= 255.0f) { m_FadeAlpha = 255.0f; m_FadingIn = false; } else { m_FadeAlpha += m_FadeSpeed * ts; } } // Call derived OnUpdate(ts); // Call SceneStack m_SceneStack->OnUpdate(ts); } /** * This is the internal rendering function. * Renders the SceneStack. */ void Application::IOnRender() { // Set render target SDL_SetRenderTarget(m_Renderer, m_RenderTarget); // Clear screen SDL_SetRenderDrawColor(m_Renderer, 0, 0, 0, 0); SDL_RenderClear(m_Renderer); // Set blend mode for target SDL_SetRenderDrawBlendMode(m_Renderer, SDL_BLENDMODE_BLEND); // Call derived OnRender(); // Call SceneStack m_SceneStack->OnRender(); // Reset render target SDL_SetRenderTarget(m_Renderer, NULL); // Set blend mode for null SDL_SetRenderDrawBlendMode(m_Renderer, SDL_BLENDMODE_BLEND); // Set target alpha SDL_SetTextureColorMod(m_RenderTarget, (Uint8) m_FadeAlpha, (Uint8) m_FadeAlpha, (Uint8) m_FadeAlpha); // Draw the target texture SDL_RenderCopy(m_Renderer, m_RenderTarget, NULL, NULL); // Update screen SDL_RenderPresent(m_Renderer); } /** * This is the base-level "run" function that holds the game loop and delta time. * Calls IOnEvent(), IOnUpdate(Timestep ts), IOnRender() * The end of the function exits the application and calls the destructor. */ void Application::Run() { Init(); // Event handler object SDL_Event e; while (m_Running) { IOnEvent(e); float time = (float) SDL_GetTicks(); Timestep timestep = time - m_LastFrameTime; m_LastFrameTime = time; IOnUpdate(timestep); IOnRender(); } // Call derived OnDetach(); } /** * Sets running true */ void Application::Start() { if (m_Running) return; m_Running = true; } /** * Sets running false */ void Application::Stop() { if (!m_Running) return; m_Running = false; } }
22.103865
123
0.67173
[ "render", "object" ]
d9ae7e96835701c80a1a605e0bc96040de719e51
8,210
cpp
C++
dev/dev_in_native_CPP/dev/src/StubCreater/CCHeaderCreator.cpp
CountrySideEngineer/CStubMk
fda187747eee04d54e242904567c650de88e70a5
[ "MIT" ]
null
null
null
dev/dev_in_native_CPP/dev/src/StubCreater/CCHeaderCreator.cpp
CountrySideEngineer/CStubMk
fda187747eee04d54e242904567c650de88e70a5
[ "MIT" ]
null
null
null
dev/dev_in_native_CPP/dev/src/StubCreater/CCHeaderCreator.cpp
CountrySideEngineer/CStubMk
fda187747eee04d54e242904567c650de88e70a5
[ "MIT" ]
null
null
null
/* * CCHeaderCreater.cpp * * Created on: 2016/04/01 * Author: Kensuke */ #include <iostream> #include <sstream> #include <string> #include <algorithm> #include <cctype> #include <cstdio> #include "CCHeaderCreator.h" using namespace std; String CCHeaderCreator::CreateHeaderMacro(String FileName) { String HeaderDefineMacro; HeaderDefineMacro = FileName + "_h_"; // 文字を全て大文字にする。 transform(HeaderDefineMacro.begin(), HeaderDefineMacro.end(), HeaderDefineMacro.begin(), ::toupper); return HeaderDefineMacro; } inline String CreateGetterMacro(String VarName) { String GetterName; GetterName = String("get_") + VarName + String("()"); transform(GetterName.begin(), GetterName.end(), GetterName.begin(), ::toupper); return (GetterName); } inline String CreateGetterMacroIndex(String VarName) { String GetterName; GetterName = String("get_") + VarName; transform(GetterName.begin(), GetterName.end(), GetterName.begin(), ::toupper); GetterName += String("(idx)"); return (GetterName); } inline String CreateSetterMacro(String VarName) { String SetterName; SetterName = String("set_") + VarName; transform(SetterName.begin(), SetterName.end(), SetterName.begin(), ::toupper); SetterName += String("(value)"); return (SetterName); } inline String CreateSetterMacroIndex(String VarName) { String SetterName; SetterName = String("set_") + VarName; transform(SetterName.begin(), SetterName.end(), SetterName.begin(), ::toupper); SetterName = SetterName + String("(idx, value)"); return (SetterName); } CCHeaderCreator::CCHeaderCreator() { setFileExtention(String(".h")); } CCHeaderCreator::~CCHeaderCreator() {} /** * ヘッダーファイルの先頭部分(#define マクロ、__cplusplus)などを追加する。 */ VOID CCHeaderCreator::SetStartSection(String FileName) { String FileNameNoExt = this->RemoveExtention(FileName); String HeaderDefineMacro = CreateHeaderMacro(FileNameNoExt); this->WriteLine(String("#ifndef ") + HeaderDefineMacro); this->WriteLine(String("#define ") + HeaderDefineMacro); this->WriteLine(String("")); this->WriteLine(String("#ifdef __cplusplus")); this->WriteLine(String("extern \"C\" {")); this->WriteLine(String("#endif /* __cplusplus */")); } /** * ヘッダーファイルの末尾部分(#endif マクロ)を追加する。 */ VOID CCHeaderCreator::SetEndSection(String FileName) { String FileNameNoExt = this->RemoveExtention(FileName); String HeaderDefineMacro = CreateHeaderMacro(FileNameNoExt); this->WriteLine(String("")); this->WriteLine(String("#ifdef __cplusplus")); this->WriteLine(String("}")); this->WriteLine(String("#endif /* __cplusplus */")); this->WriteLine(String("#endif /* ") + HeaderDefineMacro + String(" */")); } /* * スタブ関数の宣言本体を作成する。 */ VOID CCHeaderCreator::CreateBody(CParamInfo *FuncInfo) { /* * スタブ関数、及び各引数とそれぞれのgetter/setterの記入開始 */ this->CreateStubDec(FuncInfo); this->CreateVariableDec(FuncInfo); this->CreateVarGetSetMacro(FuncInfo); } /* * 関数の宣言の開始を示す部分を作成する。 */ VOID CCHeaderCreator::SetSectionSep(String FuncName) { //実行前に、画面にログを出力する。 cout << String("Create a header of ") << FuncName << endl; AStubCreater::SetSectionSep(FuncName); } /* * スタブ関数の宣言のセット */ VOID CCHeaderCreator::CreateStubDec(CParamInfo *FuncInfo) { String StubFuncName = CreateStubFuncName(FuncInfo->getName()); String FuncDec = String(""); list<String> ArgNameList; list<String> ArgDataList; list<String>::iterator ArgDataIterator; list<String>::iterator ArgNameIterator; // 各バッファーの初期化関数の宣言 FuncDec = String("extern void ") + this->CreateInitialFuncName(FuncInfo->getName()) + String("();"); this->WriteLine(FuncDec); // スタブ関数の宣言の作成 this->CreateArgList(FuncInfo, &ArgDataList, &ArgNameList); if ((0 == ArgDataList.size()) && (0 == ArgNameList.size())) { // 引数がない場合は不要な改行の挿入を回避し、その場で括弧を閉じる FuncDec = String("extern ") + FuncInfo->getDataType() + String(" ") + StubFuncName + (String("();")); } else { // 引数あり:引数ごとに1行 FuncDec = String("extern ") + FuncInfo->getDataType() + String(" ") + StubFuncName + (String("(\n")); ArgDataIterator = ArgDataList.begin(); ArgNameIterator = ArgNameList.begin(); int index = 1; while ((ArgDataList.end() != ArgDataIterator) && (ArgNameList.end() != ArgNameIterator)) { String ArgName = AddIndex("Arg", index); String ArgDef = String("\t") + *ArgDataIterator + String(" ") + ArgName; ArgDataIterator++; ArgNameIterator++; if ((ArgDataList.end() != ArgDataIterator) && (ArgNameList.end() != ArgNameIterator)) { ArgDef += ", \n"; index++; } else { ArgDef += String(");"); } FuncDec += ArgDef; } } this->WriteLine(FuncDec); } /* * 呼び出し回数、および引数を格納する配列を追加する。 */ VOID CCHeaderCreator::CreateVariableDec(CParamInfo *FuncInfo) { String StubFuncName = CreateStubFuncName(FuncInfo->getName()); String CalledCountVarName = CreateCalledCountVarName(StubFuncName); String RetValArrayVarName = CreateRetValArrayName(StubFuncName); list<String> ArgDataTypeList; list<String> ArgNameList; list<String>::iterator ArgDataIterator; list<String>::iterator ArgNameIterator; this->CreateArgList(FuncInfo, &ArgDataTypeList, &ArgNameList); this->WriteLine(String("extern int ") + CalledCountVarName + String(";")); this->WriteLine(String("extern int ") + RetValArrayVarName + String("[];")); ArgDataIterator = ArgDataTypeList.begin(); ArgNameIterator = ArgNameList.begin(); while ((ArgDataTypeList.end() != ArgDataIterator) && (ArgNameList.end() != ArgNameIterator)) { String DataType = this->RemoveConstModifier(*ArgDataIterator); this->WriteLine(String("extern ") + DataType + String(" ") + *ArgNameIterator + String("[];")); ArgDataIterator++; ArgNameIterator++; } } /* * 引数を格納する配列へのgetter/setterを追記する。 */ VOID CCHeaderCreator::CreateVarGetSetMacro(CParamInfo *FuncInfo) { String StubFuncName = CreateStubFuncName(FuncInfo->getName()); String CalledCountVarName = CreateCalledCountVarName(StubFuncName); String RetValArrayVarName = CreateRetValArrayName(StubFuncName); list<String> ArgNameList; list<String> ArgDataList; list<String>::iterator ArgDataIterator; list<String>::iterator ArgNameIterator; this->CreateArgList(FuncInfo, &ArgDataList, &ArgNameList); this->WriteLine(String("#define\t") + CreateGetterMacro(CalledCountVarName) + String("\t\\\n\t(") + CalledCountVarName + String(")")); this->WriteLine(String("#define\t") + CreateSetterMacro(CalledCountVarName) + String("\t\\\n\t(") + CalledCountVarName + String(" = value)")); ArgNameIterator = ArgNameList.begin(); while (ArgNameList.end() != ArgNameIterator) { // getter マクロを追加 this->WriteLine(String("#define\t") + CreateGetterMacroIndex(*ArgNameIterator) + String("\t\\\n\t(") + *ArgNameIterator + String("[idx])")); // setter マクロを追加 this->WriteLine(String("#define\t") + CreateSetterMacroIndex(*ArgNameIterator) + String("\t\\\n\t(") + *ArgNameIterator + String("[idx] = value)")); ArgNameIterator++; } this->WriteLine(String("#define\t") + CreateGetterMacroIndex(RetValArrayVarName) + String("\t\\\n\t(") + RetValArrayVarName + String("[idx])")); this->WriteLine(String("#define\t") + CreateSetterMacroIndex(RetValArrayVarName) + String("\t\\\n\t(") + RetValArrayVarName + String("[idx] = value)")); }
29.963504
78
0.622168
[ "transform" ]
d9b34a15440cb797d4aaca6ef8f30831fd3e8f72
28,227
cpp
C++
OpenGL_GLFW_Project/GLFW_Init.cpp
millerf1234/OpenGL_Windows_Projects
26161ba3c820df366a83baaf6e2a275d874c6acd
[ "MIT" ]
null
null
null
OpenGL_GLFW_Project/GLFW_Init.cpp
millerf1234/OpenGL_Windows_Projects
26161ba3c820df366a83baaf6e2a275d874c6acd
[ "MIT" ]
null
null
null
OpenGL_GLFW_Project/GLFW_Init.cpp
millerf1234/OpenGL_Windows_Projects
26161ba3c820df366a83baaf6e2a275d874c6acd
[ "MIT" ]
null
null
null
// Performs the necessary steps to get GLFW up and running on program startup. // Performs the necessary steps to get GLFW up and running on program startup. // Also does the steps to close the window once program has completed running. // // GLFW_Init.cpp // // First Created by Forrest Miller on 2/12/18 on a Macbook Pro using XCode. // Modified to work on windows on July 16, 2018 by Forrest Miller // And Honestly I've Been Modifying This In Little Bits Continuously Up To June // 2019 and probably beyond that too. /////////////////////////////////////////////////////////////////////////////// //////// DISCLAIMER [Please Read] //////// If you are someone who isn't me and you happen to be reading this //////// code, I apologize profusely as to its confuzzled and contradictory //////// nature. The issue stems from this code being about 6 months older //////// than pretty much every other file in this project. When I wrote this, //////// I was still only half a year into my computer science school program //////// and had only been writing in C++ since the fall. At the time I wrote //////// this, I had no idea what I was doing and was just trying to get //////// something together quickly that would be functional while allowing me //////// to get to the actual rendering. When I eventually migrated from //////// developing on Mac OS to Windows, this class was the only piece that //////// I left pretty much entirely intact. //////// Since then, I have made several attempts to replace this class //////// with something better, but have never gotten to being able to reach //////// a finishing implementation, usually due to the scope ballooning beyond //////// what I have time to write (the large number of callback functions //////// always slowed me way down...) //////// I have made numerous updates to this class since it was first //////// imported. I would typically accompany these updates with multiple //////// attempts at refactoring many of the poorly written sections of code. //////// Unfortunately these refactoring projects I wouldn't always see to //////// completion, often because I constantly will see numerous little tiny //////// issues within the code that seem easy enough to quickly fix but instead //////// evolve into a much larger and more elaborate solution. Thus a good //////// number of refactoring attempts on this class I never saw through //////// to completion. //////// //////// //////// //////// HERE IS WHAT YOU NEED TO KNOW ABOUT WHAT THIS CLASS DOES: //////// //////// - Construct self with a reasonable default state //////// - Possibly accept configuration from client code //////// through public member functions //////// - Set GLFW state and error-callback before init //////// - Initialize GLFW and register 'atexit' functions //////// to ensure that proper GLFW termination //////// procedures are performed before the program //////// exits //////// - Create an OpenGL context and window using GLFW //////// - Provide some sort of means to establish callback //////// functions for created windows //////// - Finally, wrap all of the relevant data covering //////// everything a running Application might possibly //////// want to ever know about the created window it is //////// getting handed by the Application (including a handle //////// to the window itself), all within an intuitively //////// organized single data struct. //////// //////// As things stand right now, this class has always done a pretty decent //////// job of doing most everything on that list, enough so that I have not //////// made replacing it with a better replacement a priority. /////////////////////////////////////////////////////////////////////////////// #include "GLFW_Init.h" //#include "Timepoint.h" //Note that in GLFW3.h these are defined, might want to make the cursor invisible when game launches... // #define GLFW_CURSOR_NORMAL 0x00034001 // #define GLFW_CURSOR_HIDDEN 0x00034002 // #define GLFW_CURSOR_DISABLED 0x00034003 GLFW_Init::GLFW_Init() { width = height = refreshRate = 0; //pixelWidth = pixelHeight = 0; //Since GLFW3, screen coordinates and viewport pixels are separate concepts connectedDisplayCount = 0; monitors = nullptr; mWindow = nullptr; decoratedBorder = resizeable = forwardCompatible = true; contextResetStrategy = GLFW_NO_RESET_NOTIFICATION; contextVersionMajor = DEFAULT_OPENGL_VERSION_MAJOR; contextVersionMinor = DEFAULT_OPENGL_VERSION_MINOR; aaSamples = DEFAULT_AA_SAMPLES; if (USE_VSYNC) { vSyncInterval = 1; //Should only be 0 or 1 } else { vSyncInterval = 0; } openFullScreen = USE_FULLSCREEN; defaultMonitor = MONITOR_TO_USE; GLFW_INIT_INTERNAL::GLFW_IS_INIT() = false; } GLFW_Init::~GLFW_Init() noexcept { //The call to glfwTerminate() has been moved to be an 'atexit()' callback function //which ensures that it properly gets called while also decoupling it from the lifetime //of this object //if (GLFW_INIT_INTERNAL::GLFW_IS_INIT()) { // GLFW_INIT_INTERNAL::GLFW_IS_INIT() = false; // glfwTerminate(); //} } //void GLFW_Init::terminate() { //The call to glfwTerminate() has been moved to be an 'atexit()' callback function //which ensures that it properly gets called while also decoupling it from requiring //access to this object //if (!GLFW_INIT_INTERNAL::GLFW_IS_INIT()) { return; } //if (mWindow) // glfwDestroyWindow(mWindow); //This function should be called for each window created by this application! //glfwTerminate(); //Terminating is quite a bit easier than setting up, as you can see //GLFW_INIT_INTERNAL::GLFW_IS_INIT() = false; //} inline static void errorCallbackFunctionForGLFW(int error, const char* description) { //Build a formated error message printout std::stringstream errorMessage; errorMessage << "\n\n"; for (int i = 0; i < 80; i++) { errorMessage << "^"; } errorMessage << "\n\tGLFW Error " << error << "!\n"; errorMessage << "\tERROR DESCRIPTION: " << description << "\n"; for (int i = 0; i < 80; i++) { errorMessage << "v"; } errorMessage << "\n\n"; //Print the message to the ERRLOG fprintf(ERRLOG, "%s", errorMessage.str().c_str()); } //Do window setup routines and return a struct representing information on detected monitors std::unique_ptr<InitReport> GLFW_Init::initialize() { //There are a handful of hints for GLFW that must be set before 'glfwInit()' //is called. As of GLFW 3.3, the only hint that matters for non-MacOS-platforms //this JoystickHatHint glfwInitHint(GLFW_JOYSTICK_HAT_BUTTONS, GLFW_TRUE); //Treat joystick hats as separate from Joystick buttons //Set the GLFW error callback function fprintf(MSGLOG, "\nSetting GLFW Error Callback Function..."); // SET THE GLFW ERROR CALLBACK FUNC //========================== [MOVE THIS TO IT's OWN FUNCTION?] =============================== //It seems as though setting the error callback function cannot fail. //'glfwSetErrorCallback()' returns NULL if no error callback had been previously set, //or returns a pointer to the previously set error callback function if one had been set //previously. const auto prevErrorCBFunc = glfwSetErrorCallback(errorCallbackFunctionForGLFW); if (!prevErrorCBFunc) //If there was no error callback function already in place fprintf(MSGLOG, "DONE\n"); else { fprintf(WRNLOG, "\nWarning! While setting up the error callback function\n" "for GLFW Application has detected that it replaced a\n" "previously specified error callback function!\n" "Please investigate this further because it is unexpected!\n"); } //============================================================================================== fprintf(MSGLOG, "Initializing GLFW..."); fprintf(MSGLOG, " (This may take some time)\n"); //Sometimes DLLs load too slow if (!glfwInit()) { fprintf(ERRLOG, "\nError initializing GLFW!\n"); GLFW_INIT_INTERNAL::GLFW_IS_INIT() = false; return nullptr; } GLFW_INIT_INTERNAL::GLFW_IS_INIT() = true; assignGLFWRelatedAtExitCallbackFunctions(); fprintf(MSGLOG, "DONE! GLFW version: %s\n", glfwGetVersionString()); //Now that GLFW is initialized, we begin configuring it by providing it 'hints'. //The vast majority of these hints are of the 'WindowHint' variety, each of which //sets a component of GLFW's global state affecting the creation of the next window. fprintf(MSGLOG, "\tWindow Context Rendering provided through OpenGL %d.%d\n", contextVersionMajor, contextVersionMinor); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, contextVersionMajor); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, contextVersionMinor); fprintf(MSGLOG, "\tConfiguring OpenGL Context...\n"); fprintf(MSGLOG, "\t GL Profile: CORE\n"); //Always use CORE glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); fprintf(MSGLOG, "\t Create as debug context: "); //Enabling this may reduce performance if (USE_DEBUG) { fprintf(MSGLOG, "ENABLED\n"); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); } else { fprintf(MSGLOG, "DISABLED\n"); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_FALSE); } fprintf(MSGLOG, "\t Setting Context Robustness / Reset Strategy: "); //Can be set to either GLFW_NO_RESET_NOTIFICATION or GLFW_LOSE_CONTEXT_ON_RESET switch (contextResetStrategy) { default: contextResetStrategy = GLFW_NO_RESET_NOTIFICATION; [[fallthrough]] ; case GLFW_NO_RESET_NOTIFICATION: fprintf(MSGLOG, "NO_NOTIFICATION_ON_RESET\n"); break; case GLFW_LOSE_CONTEXT_ON_RESET: fprintf(MSGLOG, "LOSE_CONTEXT_ON_RESET\n"); break; } //contextResetStrategy = GLFW_LOSE_CONTEXT_ON_RESET; glfwWindowHint(GLFW_CONTEXT_ROBUSTNESS, contextResetStrategy); fprintf(MSGLOG, "\t FORWARD COMPATIBILITY: "); if (forwardCompatible) { glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); fprintf(MSGLOG, "TRUE\n"); } else { glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_FALSE); fprintf(MSGLOG, "FALSE\n"); } fprintf(MSGLOG, "\t DOUBLE BUFFERING: "); if constexpr (DOUBLE_BUFFERING) { glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE); fprintf(MSGLOG, "ENABLED!\n"); } else { //Not double buffering produces weird enough //results that we probably should confirm this //choice with the user before continuing. glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_FALSE); fprintf(MSGLOG, "NOT ENABLED!!!!!!!!!!\n"); fprintf(MSGLOG, "" "\t _Y_Y_Y_Y_Y_Y_Y_Y_\n" "\t | | | | | | | | \n" "\t | | | | | | | | \n" "\t V V V V V V V V \n" "\t Are you sure?\n" "\t [press ENTER to be sure]\n"); std::cin.get(); } fprintf(MSGLOG, "\t Decorate Window Border: "); if (decoratedBorder) { glfwWindowHint(GLFW_DECORATED, GLFW_TRUE); fprintf(MSGLOG, "TRUE\n"); } else { glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); fprintf(MSGLOG, "FALSE\n"); } fprintf(MSGLOG, "\t WINDOW RESIZEABLE: "); if (this->resizeable) { glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); fprintf(MSGLOG, "TRUE\n"); } else { glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); fprintf(MSGLOG, "FALSE\n"); } fprintf(MSGLOG, "\t WINDOW AUTO_ICONIFY: "); if constexpr (true) { glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_TRUE); fprintf(MSGLOG, "TRUE\n"); } else { glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_FALSE); fprintf(MSGLOG, "FALSE\n"); } //Deprecated? maybe... //glfwWindowHint(GLFW_SRGB_CAPABLE, GL_TRUE); //NOT SURE IF THIS IS NEEDED fprintf(MSGLOG, "\t Full-Screen MSAA Samples: %d\n", aaSamples); glfwWindowHint(GL_SAMPLES, aaSamples); if (vSyncInterval == 0) { fprintf(MSGLOG, "\t VSYNC: OFF\n"); glfwSwapInterval(0); } else { fprintf(MSGLOG, "\t VSYNC: ON\n"); glfwSwapInterval(1); } fprintf(MSGLOG, "OpenGL context configured!\n"); fprintf(MSGLOG, "\nDetecting monitors...\n"); monitors = glfwGetMonitors(&connectedDisplayCount);//Tell GLFW to look for all monitors connected currently. if ((connectedDisplayCount == 0) || (monitors == nullptr) ) { fprintf(ERRLOG, "ERROR! GLFW was unable to detect any connected monitors!\n"); fprintf(ERRLOG, "\n\t[Press Enter to exit program]\n"); std::cin.get(); //glfwTerminate(); //glfwIsInitialized = false; //GLFW_INIT_INTERNAL::GLFW_IS_INIT() = false; return nullptr; } fprintf(MSGLOG, "\t%d connected displays are detected!\n", connectedDisplayCount); //First try to make the window open on the specified display if (openFullScreen) { if (connectedDisplayCount >= (defaultMonitor + 1)) { //Check to make sure there is at least enough connected displays for defaultMonitor to exist detectDisplayResolution(defaultMonitor, width, height, refreshRate); if (!GLFW_INIT_INTERNAL::GLFW_IS_INIT()) { fprintf(ERRLOG, "\nError detecting display resolution!\n"); fprintf(ERRLOG, "\n\t[Press Enter to exit program]\n"); std::cin.get(); glfwTerminate(); std::exit(EXIT_FAILURE); return nullptr; } //Otherwise log the display information std::ostringstream displayInfoString; displayInfoString << " Window will open on display: " << this->defaultMonitor + 1 << "\n Name of Display: " << glfwGetMonitorName(monitors[this->defaultMonitor]) << "\n Resolution of this Display: " << this->width << "x" << this->height << "\n Display Refresh Rate: " << this->refreshRate << "\n"; fprintf(MSGLOG, "%s\nOpening Window...\n", displayInfoString.str().c_str()); mWindow = glfwCreateWindow(width, height, NAME_OF_APPLICATION, monitors[defaultMonitor], nullptr); if (mWindow) { fprintf(MSGLOG, "Window Successfully Created!\n\n"); } else { fprintf(ERRLOG, "Error occurred creating GLFW window in Fullscreen mode on monitor!\n"); } } //TODO... Fix this //Re-Implement more robust window checking later... [12 months later... HA!] ////If specified display is not connected, try opening on the first non-primary display detected //else if (this->connectedDisplayCount >= 2) { // detectDisplayResolution(1, this->width, this->height, this->refreshRate); // //REMEMBER TO CHECK TO SEE IF CONTEXT IS STILL VALID AFTER DETECTING DISPLAY INFO // std::cout << " Window will open on display: " << 2 << std::endl; // this->defaultMonitor = 1; // std::cout << " Name of Display: " << glfwGetMonitorName(monitors[this->defaultMonitor]) << std::endl; // std::cout << " Resolution of this Display: " << this->width << "x" << this->height << std::endl; // std::cout << " Display Refresh Rate: " << this->refreshRate << std::endl; // std::cout << "Window Context is ready to open on this Display" << std::endl; // this->mWindow = glfwCreateWindow(this->width, this->height, NAME_OF_APPLICATION, // monitors[1], nullptr); //} ////If all that fails, open on the primary display //else { // detectDisplayResolution(0, this->width, this->height, this->refreshRate); // std::cout << " Window will open on display: " << 1 << std::endl; // this->defaultMonitor = 0; // std::cout << " Name of Display: " << glfwGetMonitorName(monitors[this->defaultMonitor]) << std::endl; // std::cout << " Resolution of this Display: " << this->width << "x" << this->height << std::endl; // std::cout << " Display Refresh Rate: " << this->refreshRate << std::endl; // std::cout << "Window Context is ready to open on this Display" << std::endl; // this->mWindow = glfwCreateWindow(this->width, this->height, NAME_OF_APPLICATION, // glfwGetPrimaryMonitor(), nullptr); //} } else { //Open windowed fprintf(MSGLOG, "\nWindow Context set to open in windowed mode...\n\nOpening Window\n"); //(If not on a 4k monitor, then this resolution works fine. However with 4k, this is tiny. //mWindow = glfwCreateWindow(1670, 960, NAME_OF_APPLICATION, nullptr, nullptr); //Open as window //So if using a 4k monitor, then do something more like: mWindow = glfwCreateWindow(3600, 1800, NAME_OF_APPLICATION, nullptr, nullptr); //Open as window defaultMonitor = 0; if (mWindow) { //#define IS_4K #ifdef IS_4K glfwSetWindowMonitor(mWindow, NULL, 30, 50, 3600, 1800, GLFW_DONT_CARE); #else glfwSetWindowMonitor(mWindow, NULL, 30, 50, 900, 700, GLFW_DONT_CARE); #endif fprintf(MSGLOG, "Window Successfully Opened!\n\n"); } else { fprintf(ERRLOG, "Error opening a GLFW window in Windowed mode (i.e. not FullCcreen)!\n" " (Screen Position: [%d, %d] Screen Dimensions: [%d, %d]\n\n", 30, 50, 3600, 1800); return nullptr; } } //I do one additional check to make sure mWindow definitely is not nullptr (this check //is superfluous but doesn't hurt) if (mWindow == nullptr) { fprintf(ERRLOG, "Failed Creating OpenGL Context and Window\n"); GLFW_INIT_INTERNAL::GLFW_IS_INIT() = false; glfwTerminate(); return nullptr; } else { glfwMakeContextCurrent(mWindow); //Context must be made current here due to load dependencies GLFW_INIT_INTERNAL::GLFW_IS_INIT() = true; //Timepoint temp("GLFW has been initialized!\n"); //This Timepoint No Longer In Use } //return (std::move(generateDetectedMonitorsStruct())); //Don't do this! See comment about return value for function generateDetectedMonitorsStruct() below std::unique_ptr<InitReport> initReport = generateDetectedMonitorsStruct(); return std::move(initReport); } void GLFW_Init::specifyWindowCallbackFunctions() { if (mWindow) { //assert(mWindow); glfwSetWindowSizeCallback(mWindow, WindowCallbackInternal::windowSizeCallback); glfwSetFramebufferSizeCallback(mWindow, WindowCallbackInternal::framebufferSizeCallback); glfwSetWindowPosCallback(mWindow, WindowCallbackInternal::windowPositionCallback); glfwSetWindowOpacity(mWindow, INITIAL_WINDOW_OPACITY); glfwSetDropCallback(mWindow, WindowCallbackInternal::filedropCallback); glfwSetWindowMaximizeCallback(mWindow, WindowCallbackInternal::windowMaximizeCallback); glfwSetJoystickCallback(WindowCallbackInternal::joystickConnectionCallback); //glfwSetMouseButtonCallback(mWindow, mouseButtonCallback); //glfwSetScrollCallback(mWindow, mouseScrollCallback); //glfwSetCursorEnterCallback(mWindow, curserEnterCallback); //glfwSetCursorPosCallback(mWindow, curserPositionCallback); } } void GLFW_Init::setWindowUserPointer(void* userPointer) { if (mWindow) { glfwSetWindowUserPointer(mWindow, userPointer); } else { fprintf(ERRLOG, "\nERROR setting user pointer for window! Window is NULL!!!\n"); fprintf(ERRLOG, "\t [Press ENTER to abort]\n"); std::cin.get(); std::exit(EXIT_FAILURE); } } //Detects the resolution of the active display void GLFW_Init::detectDisplayResolution(int displayNum, int& width, int& height, int& refreshRate) { const GLFWvidmode* mode = nullptr; if (displayNum == 0) mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); else mode = glfwGetVideoMode(this->monitors[displayNum]); //Make sure mode isn't nullptr for some reason if (mode != nullptr) { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Set screen resolution here? //(Make sure to understand the difference between // // viewport size and framebuffer size, GLFW's // // documentation explains this) //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! width = mode->width; height = mode->height; refreshRate = mode->refreshRate; } else { fprintf(ERRLOG, "Error! GLFW failed while communicating with your display.\nError is due to the following reason:\n" "\tUNABLE TO RETRIEVE MONITOR VIDEO MODE INFORMATION. PERHAPS TRY A DIFFERENT MONITOR? OR REBOOT? OR CALL I.T.\n" "[If you are IT and you are reading this message, then chances are something is funky with the monitor since\n" "it is not communicating nicely with this program]\n\n"); //this->glfwIsInitialized = false; } } //Save warning state #pragma warning( push ) //4102 is for unused labels #pragma warning (disable : 4102) //Creates a struct from the members of this class std::unique_ptr<InitReport> GLFW_Init::generateDetectedMonitorsStruct() { if (!GLFW_INIT_INTERNAL::GLFW_IS_INIT()) { fprintf(ERRLOG, "\n\n\nAn Irrecoverable Issue Has Occurred With GLFW Initialization!\n" " [Press ENTER to crash]\n\n"); std::cin.get(); std::exit(EXIT_FAILURE); } assert(mWindow != nullptr); try { //Generate the struct std::unique_ptr<InitReport> report = std::make_unique<InitReport>(); //ReportEnumeratedMonitors: //Record Details on Enumerated Monitors report->monitors.enumeratedMonitors.count = connectedDisplayCount; report->monitors.enumeratedMonitors.enumeratedHandles = monitors; //Record Details on the target active Monitor report->monitors.activeMonitor.activeMonitorArrayIndex = defaultMonitor; report->monitors.activeMonitor.activeMonitor = monitors[defaultMonitor]; report->monitors.activeMonitor.nativeWidth = width; report->monitors.activeMonitor.nativeHeight = height; assert(defaultMonitor < connectedDisplayCount); report->monitors.activeMonitor.nativeRefreshRate = glfwGetVideoMode(monitors[defaultMonitor])->refreshRate; //ReportWindowContext: //Report On Context report->windowContext.context.contextValid = GLFW_INIT_INTERNAL::GLFW_IS_INIT(); report->windowContext.context.versionMajor = contextVersionMajor; report->windowContext.context.versionMinor = contextVersionMinor; report->windowContext.context.forwardCompat = forwardCompatible; report->windowContext.context.isDebug = USE_DEBUG; //report->windowContext.context.forceContextAppSync = ? ? ? ; //Not set during GLFW init report->windowContext.context.loseOnReset = (glfwGetWindowAttrib(mWindow, GLFW_CONTEXT_ROBUSTNESS) == GLFW_LOSE_CONTEXT_ON_RESET); //Report on Window report->windowContext.window.window = mWindow; report->windowContext.window.fullscreen = openFullScreen; glfwGetFramebufferSize(mWindow, &(report->windowContext.window.framebufferWidth), &(report->windowContext.window.framebufferHeight)); report->windowContext.window.samples = aaSamples; //Set the variant part of Window based on if in Fullscreen or Windowed mode if (openFullScreen) { report->windowContext.window.conditionalInfo = WindowContext::WindowInfo::FullscreenInfo(); WindowContext::WindowInfo::FullscreenInfo* fullscrInfo = &(std::get<WindowContext::WindowInfo::FullscreenInfo>(report->windowContext.window.conditionalInfo)); fullscrInfo->vsync = USE_VSYNC; fullscrInfo->refreshRate = glfwGetVideoMode(monitors[defaultMonitor])->refreshRate; //Will always be set to monitor's default refresh rate (for now) } else { report->windowContext.window.conditionalInfo = WindowContext::WindowInfo::WindowedInfo(); WindowContext::WindowInfo::WindowedInfo* windowedInfo = &(std::get<WindowContext::WindowInfo::WindowedInfo>(report->windowContext.window.conditionalInfo)); windowedInfo->decorated = decoratedBorder; windowedInfo->resizeable = resizeable; } return std::move(report); } catch (const std::bad_alloc & e) { (void)e; fprintf(ERRLOG, "\nBad Allocation!\nTime To Crash!!!\n"); std::exit(EXIT_FAILURE); } catch (const std::bad_variant_access & e) { (void)e; fprintf(ERRLOG, "\n\n\nOH NO! There is a bug in the GLFW init code!\n" "A Bad Variant Access has occurred at:\n%s\n\n [Press ENTER to crash]\n\n", __FUNCTION__); std::cin.get(); std::exit(EXIT_FAILURE); } } //Restore warning state #pragma warning(pop) void GLFW_Init::assignAtExitTerminationFunction() noexcept { constexpr const int VALUE_ATEXIT_RETURNS_ON_SUCCESS = 0; const int success = std::atexit(GLFW_INIT_INTERNAL::atExitFuncToEnsureGLFWTerminateIsCalled); if (success != VALUE_ATEXIT_RETURNS_ON_SUCCESS) { fprintf(ERRLOG, "\n\n\nERROR! Unable to set the 'atexit()' GLFW Termination Function!\n"); fprintf(ERRLOG, "This is unfortunately not something this Application can simply ignore.\n" "Instead this Application must treat this as a FATAL ERROR since this\n" "callback function is responsible for performing one of the most vital rolls\n" "in making sure all resources allocated from the OS get properly released\n" "again by the time this Application exits.\n"); fprintf(ERRLOG, "Since there is no way of cleaning up after ourselves later,\n" "the Application is now entering into its shutdown procedure...\n" "\n\t\tTerminating Window...DONE\n\n"); glfwTerminate(); fprintf(ERRLOG, "\n\nREADY TO BEGIN FINAL APPLICATION CLEAN-UP!\n"); fprintf(ERRLOG, "\t [Press ENTER to abort]\n"); try { std::cin.get(); } catch (...) { ; } std::exit(EXIT_FAILURE); } } void GLFW_Init::assignAtExitFunctionForReleasingAllActiveWindowHandles() noexcept { constexpr const int VALUE_ATEXIT_RETURNS_ON_SUCCESS = 0; const int success = std::atexit(GLFW_INIT_INTERNAL::atExitFuncToReleaseAllActiveWindowHandles); if (success != VALUE_ATEXIT_RETURNS_ON_SUCCESS) { fprintf(WRNLOG, "\n\n\nWARNING! Unable to set the 'atexit' function for releasing\n" "GLFW Window Handles!\n"); fprintf(WRNLOG, "This is not a fatal error luckily but deserves closer attention\n" "none-the-less. Please contact a developer!\n"); } }
44.522082
160
0.629256
[ "object" ]
d9bdc59165fa05b411ed98283cecb437b0129eac
1,062
cpp
C++
c/class_compos_priv.cpp
bheckel/code
98309e8aa145901e49460546643c911eaaff54e6
[ "Apache-2.0" ]
1
2019-08-11T00:39:34.000Z
2019-08-11T00:39:34.000Z
c/class_compos_priv.cpp
bheckel/code
98309e8aa145901e49460546643c911eaaff54e6
[ "Apache-2.0" ]
null
null
null
c/class_compos_priv.cpp
bheckel/code
98309e8aa145901e49460546643c911eaaff54e6
[ "Apache-2.0" ]
1
2020-07-28T05:58:47.000Z
2020-07-28T05:58:47.000Z
////////////////////////////////////////////////////////////////////////////// // Name: class_composition_priv.cpp (see class_simple.h) // // Summary: Demo of using public composition within a basic, almost useless, // class. Does NOT use inheritance. // // Adapted: Wed 31 Oct 2001 14:06:05 (Bob Heckel -- Thinking in C++ Ch 14) ////////////////////////////////////////////////////////////////////////////// #include <iostream> #include "class_simple.h" class Y { private: int i; X x; // embedded object public: Y() { i = 0; } void f(int ii) { i = ii; x.set(ii); } int g() const { return i * x.read(); } int xread() { x.read(); } void permute() { x.permute(); } }; int main() { Y y; y.f(2); // set cout << "y.xread() after setting but before permute(): " << y.xread() << endl; y.permute(); cout << "y.xread() after permute(): " << y.xread() << endl; cout << "y.g(): " << y.g() << endl; // class Y specific function }
29.5
78
0.438795
[ "object" ]
d9c140087ee9edfadc52fc17e2c94bcb946d8f84
4,151
cpp
C++
COREdcs/clientGUI/src/DCSProfileWidget.cpp
m-fila/ELITPCdcs
5c6fdc09fb4c3c63139f8adc3e303ba74a3ad94e
[ "MIT" ]
null
null
null
COREdcs/clientGUI/src/DCSProfileWidget.cpp
m-fila/ELITPCdcs
5c6fdc09fb4c3c63139f8adc3e303ba74a3ad94e
[ "MIT" ]
null
null
null
COREdcs/clientGUI/src/DCSProfileWidget.cpp
m-fila/ELITPCdcs
5c6fdc09fb4c3c63139f8adc3e303ba74a3ad94e
[ "MIT" ]
null
null
null
#include "DCSProfileWidget.h" DCSProfileWidget::DCSProfileWidget(QWidget *parent) : QWidget(parent) { auto *mainLayout = new QHBoxLayout(this); auto *box = new QGroupBox("Profile", this); mainLayout->addWidget(box); setLayout(mainLayout); auto *innerLayout = new QHBoxLayout(this); box->setLayout(innerLayout); text = new QLabel("Selected:"); innerLayout->addWidget(text); key = new QLabel("none"); innerLayout->addWidget(key); selectButton = new QPushButton("Select", this); innerLayout->addWidget(selectButton); applyButton = new QPushButton("Apply", this); innerLayout->addWidget(applyButton); saveButton = new QPushButton("Save active", this); innerLayout->addWidget(saveButton); connectSignals(); } void DCSProfileWidget::connectSignals() { connect(applyButton, SIGNAL(pressed()), this, SIGNAL(applyProfile())); connect(saveButton, SIGNAL(pressed()), this, SLOT(showSaveDialog())); connect(selectButton, SIGNAL(pressed()), this, SLOT(showSelectDialog())); } void DCSProfileWidget::showSaveDialog() { bool ok; QString text = QInputDialog::getText(this, "Save active profile", "Name for new profile:", QLineEdit::Normal, "new", &ok); if(ok && !text.isEmpty()) { if(text == "None") { QMessageBox msgBox; msgBox.setText( "\"None\" is a reserved name. Choose other name for a profile."); msgBox.exec(); } else { emit saveProfile(text.toStdString()); } } } void DCSProfileWidget::showSelectDialog() { auto doc = QJsonDocument::fromJson(enabledProfiles.toUtf8()); if(doc.isObject()) { auto obj = doc.object(); DCSProfileDialog dial(obj, key->text(), this); auto retv = dial.exec(); if(retv) { emit setProfile(dial.getKey()); } } } void DCSProfileWidget::updateSelectedProfile(void *data) { auto *keyUA = static_cast<UA_String *>(data); std::string keyStr(reinterpret_cast<char *>(keyUA->data), keyUA->length); key->setText(QString::fromStdString(keyStr)); } void DCSProfileWidget::updateEnabledProfiles(void *data) { auto *profilesUA = static_cast<UA_String *>(data); std::string profilesStr(reinterpret_cast<char *>(profilesUA->data), profilesUA->length); enabledProfiles = QString::fromStdString(profilesStr); } void DCSProfileWidget::updateStatus(bool status) { applyButton->setEnabled(status); saveButton->setEnabled(status); connected = status; } DCSProfileDialog::DCSProfileDialog(const QJsonObject &json, QString activeKey, QWidget *parent) : QDialog(parent), json(json) { auto *outerLayout = new QVBoxLayout(this); auto *innerLayout = new QHBoxLayout(this); QLabel *label = new QLabel("Select profile:", this); setLayout(outerLayout); outerLayout->addWidget(label); outerLayout->addLayout(innerLayout); innerLayout->addWidget(&list); innerLayout->addWidget(&body); list.insertItem(1, "None"); list.insertItems(1, json.keys()); body.setReadOnly(true); QDialogButtonBox *buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); outerLayout->addWidget(buttonBox); connect(&list, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(keyChanged(QListWidgetItem *, QListWidgetItem *))); connect(buttonBox, &QDialogButtonBox::accepted, this, &DCSProfileDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &DCSProfileDialog::reject); auto found = list.findItems(activeKey, Qt::MatchExactly); if(!found.isEmpty()) { list.setCurrentItem(found.at(0)); } } void DCSProfileDialog::keyChanged(QListWidgetItem *current, QListWidgetItem *prev) { QJsonDocument doc(json.value(current->text()).toObject()); body.setText(doc.toJson(QJsonDocument::Indented)); } std::string DCSProfileDialog::getKey() { return list.currentItem()->text().toStdString(); }
35.784483
90
0.6649
[ "object" ]
d9ce60ac0f705166d48ceecfdc28db8ed64585a1
4,283
cpp
C++
Core/Tests/ListTests.cpp
DeltaEngine/DeltaEngineCpp
7be036473927750a89b8ccaefd425c07d7dd3319
[ "Apache-2.0" ]
7
2015-02-01T21:03:22.000Z
2021-06-29T03:27:28.000Z
Core/Tests/ListTests.cpp
DeltaEngine/DeltaEngineCpp
7be036473927750a89b8ccaefd425c07d7dd3319
[ "Apache-2.0" ]
null
null
null
Core/Tests/ListTests.cpp
DeltaEngine/DeltaEngineCpp
7be036473927750a89b8ccaefd425c07d7dd3319
[ "Apache-2.0" ]
7
2015-02-19T11:46:56.000Z
2019-08-17T12:37:04.000Z
#include "CppUnitTest.h" #include "CppUnitTestCoreSupport.h" #include "Core\List.h" #include "Core\ArrayHelper.h" #include <memory> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace DeltaEngine { namespace Core { namespace Tests { TEST_CLASS(ListTests) { public: TEST_METHOD(List_Empty) { auto list = List<float>(); Assert::IsTrue(0 == list.GetCount()); } TEST_METHOD(List_Add) { auto list = List<int>(); list.Add(2); list.Add(4); Assert::AreEqual(2, list.GetCount()); Assert::AreEqual(2, list[0]); Assert::AreEqual(4, list[1]); } TEST_METHOD(List_ReferenceCopyWithStdVectorPointer) { auto list = new std::vector<int>(); list->push_back(11); Assert::AreEqual(1U, list->size()); auto reference = list; Assert::AreEqual(1U, reference->size()); Assert::AreEqual(11, (*reference)[0]); list->push_back(33); reference->push_back(55); Assert::AreEqual(3U, list->size()); Assert::AreEqual(3U, reference->size()); Assert::AreEqual(33, (*reference)[1]); Assert::AreEqual(55, (*list)[2]); delete list; } TEST_METHOD(List_Reference) { auto list = List<int>(); list.Add(11); Assert::AreEqual(1, list.GetCount()); auto reference = &list; Assert::AreEqual(1, reference->GetCount()); Assert::AreEqual(11, (*reference)[0]); list.Add(33); Assert::AreEqual(2, list.GetCount()); Assert::AreEqual(2, reference->GetCount()); Assert::AreEqual(33, (*reference)[1]); } TEST_METHOD(List_Clone) { auto list = List<int>(); list.Add(11); Assert::AreEqual(1, list.GetCount()); auto clonedList = list; Assert::AreEqual(1, clonedList.GetCount()); clonedList.Add(22); Assert::AreEqual(11, clonedList[0]); Assert::AreEqual(22, clonedList[1]); Assert::AreEqual(1, list.GetCount()); } TEST_METHOD(List_Foreach) { auto list = List<int>(); list.Add(2); list.Add(4); int sum = 0; for (int number : list) sum += number; Assert::AreEqual(6, sum); } TEST_METHOD(List_Insert) { auto list = List<int>(); list.Add(2); list.Add(4); list.Insert(1, 0); list.Insert(3, 2); Assert::AreEqual(4, list.GetCount()); Assert::AreEqual(1, list[0]); Assert::AreEqual(2, list[1]); Assert::AreEqual(3, list[2]); Assert::AreEqual(4, list[3]); } TEST_METHOD(List_Remove) { auto list = List<int>(); list.Add(2); list.Add(4); list.Remove(2); Assert::AreEqual(1, list.GetCount()); Assert::AreEqual(4, list[0]); } TEST_METHOD(List_Clear) { auto list = List<int>(); list.Add(2); list.Add(4); list.Clear(); Assert::AreEqual(0, list.GetCount()); } TEST_METHOD(List_Contains) { auto list = List<int>(); list.Add(2); list.Add(4); Assert::AreEqual(2, list.GetCount()); Assert::IsTrue(list.Contains(2)); Assert::IsFalse(list.Contains(3)); } TEST_METHOD(List_ContainsWithStrings) { auto list = List<String>(); list.Add(String("Hi")); list.Add(String("Ho")); Assert::AreEqual(2, list.GetCount()); Assert::IsTrue(list.Contains(String("Hi"))); Assert::IsFalse(list.Contains(String("Ha"))); } TEST_METHOD(List_Iterate) { auto list = List<char>(); int count = 0; list.Add(1); list.Add(3); for (char value : list) count++; Assert::AreEqual(2, count); } TEST_METHOD(List_ToText) { auto list = List<String>(); list.Add("One"); list.Add("Two"); list.Add("Three"); AreEqual("One, Two, Three", list.ToText()); } TEST_METHOD(List_ToArray) { auto list = List<String>(); list.Add("One"); list.Add("Two"); list.Add("Three"); auto strings = ArrayHelper::Clone(list); Assert::AreEqual(3U, strings.size()); AreEqual(strings[0], "One"); AreEqual(strings[1], "Two"); AreEqual(strings[2], "Three"); } TEST_METHOD(List_WithTypes) { auto list = List<String>(); list.Add(typeid(int).name()); list.Add(typeid(List<String>).name()); list.Add(typeid(this).name()); list.Add(typeid(1).name()); AreEqual("int", list[0]); AreEqual("class DeltaEngine::Core::List<class DeltaEngine::Core::String>", list[1]); AreEqual("class DeltaEngine::Core::Tests::ListTests *", list[2]); Assert::AreEqual(list[0], list[3]); } }; }}}
23.026882
87
0.623395
[ "vector" ]
d9d402d7c51556a3b7a083c35a5d7176d13f8408
5,890
cpp
C++
QuantExt/qle/termstructures/blackvariancesurfacemoneyness.cpp
paul-giltinan/Engine
49b6e142905ca2cce93c2ae46e9ac69380d9f7a1
[ "BSD-3-Clause" ]
null
null
null
QuantExt/qle/termstructures/blackvariancesurfacemoneyness.cpp
paul-giltinan/Engine
49b6e142905ca2cce93c2ae46e9ac69380d9f7a1
[ "BSD-3-Clause" ]
null
null
null
QuantExt/qle/termstructures/blackvariancesurfacemoneyness.cpp
paul-giltinan/Engine
49b6e142905ca2cce93c2ae46e9ac69380d9f7a1
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2017 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <boost/make_shared.hpp> #include <ql/math/interpolations/bilinearinterpolation.hpp> #include <ql/math/interpolations/linearinterpolation.hpp> #include <ql/quotes/simplequote.hpp> #include <ql/termstructures/yield/forwardcurve.hpp> #include <qle/termstructures/blackvariancesurfacemoneyness.hpp> using namespace std; namespace QuantExt { BlackVarianceSurfaceMoneyness::BlackVarianceSurfaceMoneyness( const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times, const std::vector<Real>& moneyness, const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix, const DayCounter& dayCounter, bool stickyStrike) : BlackVarianceTermStructure(0, cal), stickyStrike_(stickyStrike), spot_(spot), dayCounter_(dayCounter), moneyness_(moneyness), quotes_(blackVolMatrix) { QL_REQUIRE(times.size() == blackVolMatrix.front().size(), "mismatch between times vector and vol matrix colums"); QL_REQUIRE(moneyness_.size() == blackVolMatrix.size(), "mismatch between moneyness vector and vol matrix rows"); QL_REQUIRE(times[0] >= 0, "cannot have times[0] < 0"); if (stickyStrike) { // we don't want to know if the spot has changed - we take a copy here spot_ = Handle<Quote>(boost::make_shared<SimpleQuote>(spot->value())); } else { registerWith(spot_); } Size j, i; // internally times_ is one bigger than the input "times" times_ = std::vector<Time>(times.size() + 1); times_[0] = 0.0; variances_ = Matrix(moneyness_.size(), times.size() + 1); for (i = 0; i < moneyness_.size(); i++) { variances_[i][0] = 0.0; } for (j = 1; j <= times.size(); j++) { times_[j] = times[j - 1]; QL_REQUIRE(times_[j] > times_[j - 1], "dates must be sorted unique!"); for (i = 0; i < moneyness_.size(); i++) { variances_[i][j] = 0.0; registerWith(blackVolMatrix[i][j - 1]); } } varianceSurface_ = Bilinear().interpolate(times_.begin(), times_.end(), moneyness_.begin(), moneyness_.end(), variances_); notifyObservers(); } void BlackVarianceSurfaceMoneyness::update() { TermStructure::update(); LazyObject::update(); } void BlackVarianceSurfaceMoneyness::performCalculations() const { for (Size j = 1; j < variances_.columns(); j++) { for (Size i = 0; i < variances_.rows(); i++) { Real vol = quotes_[i][j - 1]->value(); variances_[i][j] = times_[j] * vol * vol; } } varianceSurface_.update(); } Real BlackVarianceSurfaceMoneyness::blackVarianceImpl(Time t, Real strike) const { calculate(); if (t == 0.0) return 0.0; return blackVarianceMoneyness(t, moneyness(t, strike)); } Real BlackVarianceSurfaceMoneyness::blackVarianceMoneyness(Time t, Real m) const { if (t <= times_.back()) return varianceSurface_(t, m, true); else return varianceSurface_(times_.back(), m, true) * t / times_.back(); } BlackVarianceSurfaceMoneynessSpot::BlackVarianceSurfaceMoneynessSpot( const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times, const std::vector<Real>& moneyness, const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix, const DayCounter& dayCounter, bool stickyStrike) : BlackVarianceSurfaceMoneyness(cal, spot, times, moneyness, blackVolMatrix, dayCounter, stickyStrike) {} Real BlackVarianceSurfaceMoneynessSpot::moneyness(Time, Real strike) const { if (strike == Null<Real>() || strike == 0) return 1.0; else return strike / spot_->value(); } BlackVarianceSurfaceMoneynessForward::BlackVarianceSurfaceMoneynessForward( const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times, const std::vector<Real>& moneyness, const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix, const DayCounter& dayCounter, const Handle<YieldTermStructure>& forTS, const Handle<YieldTermStructure>& domTS, bool stickyStrike) : BlackVarianceSurfaceMoneyness(cal, spot, times, moneyness, blackVolMatrix, dayCounter, stickyStrike), forTS_(forTS), domTS_(domTS) { if (!stickyStrike) { QL_REQUIRE(!forTS_.empty(), "foreign discount curve required for atmf surface"); QL_REQUIRE(!domTS_.empty(), "foreign discount curve required for atmf surface"); registerWith(forTS_); registerWith(domTS_); } else { for (Size i = 0; i < times_.size(); i++) { Time t = times_[i]; Real fwd = spot_->value() * forTS_->discount(t) / domTS_->discount(t); forwards_.push_back(fwd); } forwardCurve_ = Linear().interpolate(times_.begin(), times_.end(), forwards_.begin()); } } Real BlackVarianceSurfaceMoneynessForward::moneyness(Time t, Real strike) const { Real fwd; if (strike == Null<Real>() || strike == 0) return 1.0; else { if (stickyStrike_) fwd = forwardCurve_(t, true); else fwd = spot_->value() * forTS_->discount(t) / domTS_->discount(t); return strike / fwd; } } } // namespace QuantExt
39.530201
119
0.677589
[ "vector", "model" ]